Subversion Repositories SmartDukaan

Rev

Rev 15842 | Rev 23672 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2171 rajveer 1
package in.shop2020.util;
3929 mandeep.dh 2
 
2171 rajveer 3
import in.shop2020.metamodel.core.Entity;
4
import in.shop2020.metamodel.core.EntityState;
5
import in.shop2020.metamodel.core.EntityStatus;
6
import in.shop2020.metamodel.util.CreationUtils;
5945 mandeep.dh 7
import in.shop2020.model.v1.catalog.CatalogService.Client;
2171 rajveer 8
import in.shop2020.model.v1.catalog.Item;
3560 rajveer 9
import in.shop2020.model.v1.catalog.Source;
2171 rajveer 10
import in.shop2020.model.v1.catalog.status;
3127 rajveer 11
import in.shop2020.thrift.clients.CatalogClient;
2733 rajveer 12
import in.shop2020.ui.util.ComparisonStatsFetcher;
3083 vikas 13
import in.shop2020.ui.util.NewVUI;
2367 rajveer 14
import in.shop2020.ui.util.PriceInsertor;
2838 mandeep.dh 15
import in.shop2020.ui.util.SpecialPageJSONConvertor;
3464 rajveer 16
import in.shop2020.utils.GmailUtils;
2171 rajveer 17
 
3083 vikas 18
import java.io.File;
6871 amit.gupta 19
import java.io.FileNotFoundException;
20
import java.io.FileReader;
3083 vikas 21
import java.io.IOException;
6871 amit.gupta 22
import java.io.Reader;
4098 anupam.sin 23
import java.text.SimpleDateFormat;
3083 vikas 24
import java.util.ArrayList;
25
import java.util.Calendar;
26
import java.util.Date;
27
import java.util.HashMap;
5479 amit.gupta 28
import java.util.Iterator;
3083 vikas 29
import java.util.LinkedHashMap;
30
import java.util.List;
31
import java.util.Map;
2171 rajveer 32
 
3464 rajveer 33
import javax.mail.MessagingException;
34
 
3083 vikas 35
import org.apache.commons.cli.CommandLine;
36
import org.apache.commons.cli.CommandLineParser;
37
import org.apache.commons.cli.HelpFormatter;
38
import org.apache.commons.cli.Options;
39
import org.apache.commons.cli.ParseException;
40
import org.apache.commons.cli.PosixParser;
5227 amit.gupta 41
import org.apache.commons.lang.StringUtils;
3929 mandeep.dh 42
import org.apache.commons.logging.Log;
43
import org.apache.commons.logging.LogFactory;
2171 rajveer 44
 
5084 phani.kuma 45
import com.google.gson.Gson;
6871 amit.gupta 46
import com.google.gson.reflect.TypeToken;
5084 phani.kuma 47
 
3929 mandeep.dh 48
public class ContentGenerationUtility {
49
    private static final String   UPDATE_TYPE_CATALOG         = "CATALOG";
2171 rajveer 50
 
3929 mandeep.dh 51
    private static final String   UPDATE_TYPE_CONTENT         = "CONTENT";
3083 vikas 52
 
4098 anupam.sin 53
    private static final String   COMMAND_LINE                = "java ContentGenerationUtility.class -t { ALL | INCREMENTAL | ONE } -s { yyyy-MM-dd-HH-mm-ss } -u { CONTENT | CATALOG } -e {EntityId} ";
3929 mandeep.dh 54
 
55
    private static Log            log                         = LogFactory
56
                                                                      .getLog(ContentGenerationUtility.class);
5227 amit.gupta 57
    private static long 			ONE_DAY					  = 24*60*60*1000;  	//milliseconds in a day						 	
3929 mandeep.dh 58
    // Commandline options
59
    private static Options        options                     = null;
60
    private static final String   GENERATION_TYPE_INCREMENTAL = "INCREMENTAL";
61
    private static final String   GENERATION_TYPE_ALL         = "ALL";
62
    private static final String   GENERATION_TYPE_ONE         = "ONE";
63
    private static final String   UPDATE_TYPE_OPTION          = "u";
64
    private static final String   GENERATION_TYPE_OPTION      = "t";
65
    private static final String   ENTITY_ID_OPTION            = "e";
4098 anupam.sin 66
    private static final String   TIMESTAMP_OPTION            = "s";
3929 mandeep.dh 67
 
68
    // Default values of cmdline options
69
    private static String         UPDATE_TYPE                 = UPDATE_TYPE_CONTENT;
70
    private static String         GENERATION_TYPE             = GENERATION_TYPE_INCREMENTAL;
71
    private static String         ENTITY_ID                   = "ALL";
5664 amit.gupta 72
    private static String [] 	  DOMAINPATHS 			      = Utils.DOMAIN_NAMES_FOR_CONTENT_GENERATION.split(";");
3929 mandeep.dh 73
 
4098 anupam.sin 74
    private Date 				  timeStamp			  		  = null;
3929 mandeep.dh 75
    private CommandLine           cmd                         = null;
76
    private Map<Long, List<Item>> entityIdItemMap             = new LinkedHashMap<Long, List<Item>>();
77
    private Long                  lastGenerationTime          = 0l;
9996 amit.gupta 78
    private Long                  lastGenerationTimeNonZero          = CreationUtils.getLastContentGenerationTime();
3929 mandeep.dh 79
    private Map<Long, Entity>     entities;
7662 amit.gupta 80
    private List<Long> removeEntities = new ArrayList<Long>();
3929 mandeep.dh 81
    private List<Item>            items;
82
    private List<Source>          sources;
83
    private CatalogClient         csc;
9996 amit.gupta 84
    List<Entity> validPartialEntities = new ArrayList<Entity>();
3929 mandeep.dh 85
    private Client                client;
5279 amit.gupta 86
    private List<Item>			  alertItems;	
3929 mandeep.dh 87
    private long                  newLastGenerationTime;
88
 
89
    static {
2171 rajveer 90
        options = new Options();
91
        options.addOption(GENERATION_TYPE_OPTION, true, "Generation type");
3929 mandeep.dh 92
        options.addOption(UPDATE_TYPE_OPTION, true, "Default is : "
93
                + UPDATE_TYPE);
94
        options.addOption(ENTITY_ID_OPTION, true, "all entities " + ENTITY_ID
95
                + " by default");
4098 anupam.sin 96
        options.addOption(TIMESTAMP_OPTION, true, "Manual timestamp");
97
 
2171 rajveer 98
    }
3929 mandeep.dh 99
 
100
    public ContentGenerationUtility() throws Exception {
3127 rajveer 101
        csc = new CatalogClient();
2171 rajveer 102
        client = csc.getClient();
3573 rajveer 103
        sources = client.getAllSources();
5279 amit.gupta 104
        alertItems = new ArrayList<Item>();	
2171 rajveer 105
    }
2367 rajveer 106
 
2171 rajveer 107
    /**
108
     * @param args
3929 mandeep.dh 109
     * @throws Exception
2171 rajveer 110
     */
3929 mandeep.dh 111
    public static void main(String[] args) throws Exception {
6192 amit.gupta 112
        ContentGenerationUtility cgu = new ContentGenerationUtility();
113
 
114
        // Load arguments
115
        cgu.loadArgs(args);
116
 
117
        // Call method based on arguments
118
        cgu.callMethod();
2171 rajveer 119
    }
2367 rajveer 120
 
3929 mandeep.dh 121
    /**
122
     * Validate and set command line arguments. Exit after printing usage if
123
     * anything is astray
124
     * 
125
     * @param args
126
     *            String[] args as featured in public static void main()
2171 rajveer 127
     */
3929 mandeep.dh 128
    private void loadArgs(String[] args) {
2171 rajveer 129
        CommandLineParser parser = new PosixParser();
3929 mandeep.dh 130
 
2171 rajveer 131
        try {
132
            cmd = parser.parse(options, args);
133
        } catch (ParseException e) {
3929 mandeep.dh 134
            log.error("Error parsing arguments", e);
2171 rajveer 135
            System.exit(1);
136
        }
3929 mandeep.dh 137
 
2171 rajveer 138
        // Check for mandatory args
3929 mandeep.dh 139
        if (!(cmd.hasOption(GENERATION_TYPE_OPTION) && cmd
140
                .hasOption(UPDATE_TYPE_OPTION))) {
2171 rajveer 141
            HelpFormatter formatter = new HelpFormatter();
3929 mandeep.dh 142
            formatter.printHelp(COMMAND_LINE, options);
2171 rajveer 143
            System.exit(1);
144
        }
4098 anupam.sin 145
 
146
 
2171 rajveer 147
        GENERATION_TYPE = cmd.getOptionValue(GENERATION_TYPE_OPTION);
4098 anupam.sin 148
 
2367 rajveer 149
        UPDATE_TYPE = cmd.getOptionValue(UPDATE_TYPE_OPTION);
3929 mandeep.dh 150
 
2171 rajveer 151
        // Look for optional args.
3929 mandeep.dh 152
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
153
            if (cmd.hasOption(ENTITY_ID_OPTION)) {
2171 rajveer 154
                ENTITY_ID = cmd.getOptionValue(ENTITY_ID_OPTION);
3929 mandeep.dh 155
            } else {
2171 rajveer 156
                HelpFormatter formatter = new HelpFormatter();
3929 mandeep.dh 157
                formatter.printHelp(COMMAND_LINE, options);
2171 rajveer 158
                System.exit(1);
159
            }
160
        }
4098 anupam.sin 161
 
162
        if (GENERATION_TYPE_INCREMENTAL.equals(GENERATION_TYPE))
163
        	if (cmd.hasOption(TIMESTAMP_OPTION)) {
164
        		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
165
        		try {
166
        		    timeStamp = df.parse(cmd.getOptionValue(TIMESTAMP_OPTION));
167
        		} catch(Exception e) {
168
        			HelpFormatter formatter = new HelpFormatter();
169
                    formatter.printHelp(COMMAND_LINE, options);
170
                    System.exit(1);
171
        		}
172
        	}
2367 rajveer 173
    }
3929 mandeep.dh 174
 
2367 rajveer 175
    /**
176
     * Call method based on arguments
3929 mandeep.dh 177
     * 
2367 rajveer 178
     * @throws Exception
179
     */
3929 mandeep.dh 180
    private void callMethod() {
181
        boolean isSuccess = false;
182
        String logfile = "/tmp/content-from-cms.log";
183
        if (UPDATE_TYPE.equals(UPDATE_TYPE_CONTENT)) {
184
            logfile = "/tmp/content-from-cms.log";
185
            try {
186
                this.generateContent();
187
                isSuccess = true;
188
            } catch (Exception e) {
189
                log.error("Error generating content", e);
190
            }
191
        }
192
 
193
        if (UPDATE_TYPE.equals(UPDATE_TYPE_CATALOG)) {
194
            logfile = "/tmp/content-from-catalog.log";
195
            try {
196
                this.updatePrices();
197
                isSuccess = true;
198
            } catch (Exception e) {
199
                log.error("Error updating prices", e);
200
            }
201
        }
202
 
4969 amit.gupta 203
        GmailUtils gm = new GmailUtils();
12972 amit.gupta 204
        String[] sendTo = { "amit.gupta@shop2020.in" };
4099 anupam.sin 205
 
206
        try {
207
            gm.sendSSLMessage(sendTo, "Content Generation Successful ? : "
208
                    + isSuccess, "Content generation completed at time : "
209
                    + Calendar.getInstance().getTime().toString(),
4311 rajveer 210
                    "build@shop2020.in", "cafe@nes", logfile);
4099 anupam.sin 211
        } catch (MessagingException e) {
212
            log.error("Could not send status mail", e);
4969 amit.gupta 213
        }
2367 rajveer 214
    }
215
 
3929 mandeep.dh 216
    public boolean cleanDir(File dir, boolean deleteSelf) {
217
        if (dir.isDirectory()) {
218
            String[] children = dir.list();
219
            for (int i = 0; i < children.length; i++) {
220
                boolean success = cleanDir(new File(dir, children[i]), true);
221
                if (!success) {
222
                    return false;
223
                }
224
            }
225
        }
226
 
227
        // The directory is now empty so delete it
228
        if (deleteSelf) {
229
            return dir.delete();
230
        }
231
 
232
        return true;
233
    }
234
 
235
    private void removeOldResources() throws IOException {
236
        File f = new File(Utils.EXPORT_SOLR_PATH);
237
        if (f.exists()) {
238
            cleanDir(f, false);
239
        }
5664 amit.gupta 240
 
241
        for(String domainPath : DOMAINPATHS){
242
        	String pathName = domainPath.split("\\.")[0].split(":")[0];
243
        	File f1 = new File(Utils.EXPORT_PATH + "html/entities-" +  pathName);
244
        	if (f1.exists()) {
245
        		cleanDir(f1, false);
246
        	}else {
247
        		f1.mkdir();
248
        	}
3929 mandeep.dh 249
        }
250
    }
251
 
2367 rajveer 252
    /**
253
     * Update the prices in the generated content
3929 mandeep.dh 254
     * 
2367 rajveer 255
     * @throws Exception
256
     */
257
    private void updatePrices() throws Exception {
3929 mandeep.dh 258
        lastGenerationTime = new Long(0);
7506 amit.gupta 259
        List<Long> activeItems = new ArrayList<Long>();
3929 mandeep.dh 260
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
2367 rajveer 261
            items = client.getItemsByCatalogId(Long.parseLong(ENTITY_ID));
5479 amit.gupta 262
            Iterator<Item> it = items.iterator();
263
            while(it.hasNext()){
7506 amit.gupta 264
            	Item ite = it.next();
265
            	status st = ite.getItemStatus();
5479 amit.gupta 266
            	if(!(st.equals(status.ACTIVE) || st.equals(status.PAUSED) || 
7506 amit.gupta 267
            				st.equals(status.COMING_SOON))){
5479 amit.gupta 268
            		it.remove();
269
            	}
7506 amit.gupta 270
            	if(st.equals(status.ACTIVE)){
271
            		activeItems.add(ite.getId());
272
            	}
5479 amit.gupta 273
            }
7710 amit.gupta 274
            try {
275
            	//Generate prices and availability data for amazon
276
            	AmazonSCDataGenerator.generatePricesAndAvailability(items);
277
            } catch (Exception e) {
278
            	log.info("Could not generate Amazon prices and availability", e);
279
            }
6274 amit.gupta 280
            //ProductListGenerator.updatePriceForEntity(Long.parseLong(ENTITY_ID), items.get(0).getSellingPrice(), items.get(0).getMrp());
3929 mandeep.dh 281
        } else {
6622 rajveer 282
        	log.info("Before getting active items.");
2367 rajveer 283
            items = client.getAllItemsByStatus(status.ACTIVE);
7506 amit.gupta 284
            for (Item item : items) {
285
            	activeItems.add(item.getId());
286
            }
6622 rajveer 287
            log.info("Before getting coming items.");
5227 amit.gupta 288
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
6622 rajveer 289
            log.info("Before getting paused items.");
2367 rajveer 290
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
3929 mandeep.dh 291
            // Clean up the data from the solr directories.
6622 rajveer 292
            log.info("Before removing old resources.");
2367 rajveer 293
            removeOldResources();
294
        }
3929 mandeep.dh 295
 
7662 amit.gupta 296
/*        if (GENERATION_TYPE.equals(GENERATION_TYPE_INCREMENTAL)) {
2367 rajveer 297
        }
7662 amit.gupta 298
*/
3929 mandeep.dh 299
        populateEntityIdItemMap();
6602 amit.gupta 300
        // Generate partners and json objects for phones only
301
        if (!GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
8143 amit.gupta 302
        	ProductListGenerator generator = new ProductListGenerator(entityIdItemMap);
303
 
304
        	log.info("Before auto suggest json");
305
        	synonymTitlesExporter();
7506 amit.gupta 306
 
8143 amit.gupta 307
        	log.info("Before product list js.");
308
        	generator.generateProductListJavascript(); 
6602 amit.gupta 309
        }
2367 rajveer 310
        PriceInsertor priceInserter = new PriceInsertor();
311
 
6842 amit.gupta 312
        Map<Long,List<String>> entityTags = client.getAllEntityTags();
6871 amit.gupta 313
        Map<Long, Integer> popularityMap = getPolularityMap();
7853 amit.gupta 314
        List<Long> pausedByRiskItems = getRiskyPausedItems();
3929 mandeep.dh 315
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
316
            long entityId = entry.getKey();
317
            List<Item> items = entry.getValue();
5664 amit.gupta 318
            double minPrice = 0d;
7506 amit.gupta 319
 
320
            //Evaluating availability
321
            String availability = "Out of Stock";
322
            for(Item i: items){
7670 amit.gupta 323
            	if(i.getItemStatus().equals(status.ACTIVE)) {
324
            		if(!(i.isRisky() && pausedByRiskItems.contains(i.getId()) )){
7506 amit.gupta 325
            			availability = "In Stock";
326
            		}
6602 amit.gupta 327
            	}
328
            }
5664 amit.gupta 329
            StringBuilder priceString = new StringBuilder();
6602 amit.gupta 330
            StringBuilder availabilityString = new StringBuilder();
5664 amit.gupta 331
            boolean domainOnce = true;
5669 amit.gupta 332
            boolean sourceOnce = true;
5664 amit.gupta 333
            for(String domainPath : DOMAINPATHS){
334
            	String domainName = domainPath;
335
            	String pathName = domainPath.split("\\.")[0].split(":")[0];
7662 amit.gupta 336
            	if(!removeEntities.contains(entityId)){
337
            		priceInserter.insertPriceInHtml(items, entityId, domainName, Utils.EXPORT_PATH + "html/entities-" +  pathName + "/", null);
338
            	}
7336 amit.gupta 339
            	if(domainOnce){
7662 amit.gupta 340
            		minPrice = getMinPrice(items, entityId, null);
7336 amit.gupta 341
            		priceString.append("<field name=\"F_50002\">" + minPrice + "</field>");
342
            		availabilityString.append("<field name=\"F_50028\">" + availability + "</field>");
343
            		if(entityTags.containsKey(entityId)) {
344
            			List<String> tags = entityTags.get(entityId);
345
            			for(String tag: tags){
346
            				availabilityString.append("\n<field name=\"F_50029\">" + tag + "</field>");
347
            			}
348
            		}
349
            		if(popularityMap.containsKey(entityId)) {
350
            			availabilityString.append("\n<field name=\"F_50030\">" + popularityMap.get(entityId) + "</field>");
351
            		}else {
352
            			availabilityString.append("\n<field name=\"F_50030\">" + "0" + "</field>");
353
            		}
354
            		domainOnce = false;
5664 amit.gupta 355
            	}
7336 amit.gupta 356
            	if(sources != null){
357
            		for (Source source : sources) {
7662 amit.gupta 358
						priceInserter.insertPriceInHtml(items, entityId,domainName, Utils.EXPORT_PATH + "html/entities-" + pathName + "/",source);
7336 amit.gupta 359
                        if(sourceOnce){
7662 amit.gupta 360
                        	minPrice = getMinPrice(items, entityId, source);
7336 amit.gupta 361
                        	priceString.append("<field name=\"F_50002_"
362
                                + source.getId() + "\">" + minPrice + "</field>");
363
                        }
364
            		}
365
            		sourceOnce = false;
366
            	}
2367 rajveer 367
            }
3929 mandeep.dh 368
 
369
            priceInserter.insertPriceInSolrData(entityId,
6602 amit.gupta 370
                    priceString.toString(), availabilityString.toString());
2367 rajveer 371
        }
3929 mandeep.dh 372
 
4058 rajveer 373
        priceInserter.copySolrSchemaFiles();
2367 rajveer 374
    }
375
 
7279 amit.gupta 376
	private Map<Long, Integer> getPolularityMap() {
6871 amit.gupta 377
		try {
378
			Reader reader = new FileReader(Utils.EXPORT_PATH + Utils.POPULARITY_JSON);
13605 amit.gupta 379
			Map<Long, Integer> result =  new Gson().fromJson(reader, new TypeToken<Map<Long, Integer>>() {}.getType());
380
			if(result == null) {
381
				result = new HashMap<Long, Integer>();
382
			}
383
			return result; 
8865 amit.gupta 384
		} catch (Exception e) {
6871 amit.gupta 385
			log.error("Could not read popularity file");
386
			e.printStackTrace();
387
			return new HashMap<Long, Integer>();
388
		}
389
 
390
	}
7853 amit.gupta 391
	private List<Long> getRiskyPausedItems() {
7670 amit.gupta 392
		try {
393
			Reader reader = new FileReader(Utils.EXPORT_PATH + Utils.RISKY_PAUSED_JSON);
13604 amit.gupta 394
			List<Long> result = new Gson().fromJson(reader, new TypeToken<List<Long>>() {}.getType());
395
			if(result==null){
396
				result = new ArrayList<Long>(); 
397
			}
398
			return result;
7670 amit.gupta 399
		} catch (FileNotFoundException e) {
7853 amit.gupta 400
			log.error("Could not read paused file");
7670 amit.gupta 401
			e.printStackTrace();
402
			return new ArrayList<Long>();
403
		}
404
	}
6871 amit.gupta 405
 
6602 amit.gupta 406
	/**
2171 rajveer 407
     * Generates content for the specified entity embedding links to the
408
     * specified domain name.
409
     * 
3929 mandeep.dh 410
     * The method will not generate content if one of the following conditions
411
     * is met:
2171 rajveer 412
     * <ol>
413
     * <li>The entity is not ready.
414
     * <li>The category has not been updated yet. (Set to -1).
2367 rajveer 415
     * <li>The content has not been updated.
2171 rajveer 416
     * </ol>
3929 mandeep.dh 417
     * 
2367 rajveer 418
     * @throws
2171 rajveer 419
     */
3929 mandeep.dh 420
    private void generateContent() throws Exception {
421
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
422
            entities = CreationUtils.getEntities();
2367 rajveer 423
            lastGenerationTime = new Long(0);
7506 amit.gupta 424
            items = client.getAllItemsByStatus(status.CONTENT_COMPLETE);
425
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
12973 amit.gupta 426
            //items.addAll(client.getAllItemsByStatus(status.PARTIALLY_ACTIVE));
7506 amit.gupta 427
            items.addAll(client.getAllItemsByStatus(status.ACTIVE));
428
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
3929 mandeep.dh 429
        } else if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
430
            entities = new HashMap<Long, Entity>();
431
            entities.put(Long.parseLong(ENTITY_ID),
432
                    CreationUtils.getEntity(Long.parseLong(ENTITY_ID)));
7506 amit.gupta 433
            items = client.getItemsByCatalogId(Long.parseLong(ENTITY_ID));
434
            Iterator<Item> ite = items.iterator();
435
            while(ite.hasNext()) {
436
            	Item i = ite.next();
437
            	if(!(i.getItemStatus().equals(status.ACTIVE) || i.getItemStatus().equals(status.PAUSED) 
438
            	|| i.getItemStatus().equals(status.CONTENT_COMPLETE) || i.getItemStatus().equals(status.COMING_SOON))){
439
            		ite.remove();
440
            	}
441
            }
3929 mandeep.dh 442
            lastGenerationTime = new Long(0);
443
        } else {
4098 anupam.sin 444
        	entities = CreationUtils.getEntities();
445
            //  When we read lastGenerationTime from database
446
            //  then only we should mark the 
447
            //	current time as newLastGenerationTime
13212 amit.gupta 448
        	newLastGenerationTime = new Date().getTime();
4098 anupam.sin 449
            if(timeStamp == null) {
450
            	lastGenerationTime = CreationUtils.getLastContentGenerationTime();
451
            } else {
452
            	lastGenerationTime = timeStamp.getTime();
453
            }
454
 
3929 mandeep.dh 455
            log.info("lastGenerationTime: " + lastGenerationTime);
456
            if (lastGenerationTime == null) {
2171 rajveer 457
                lastGenerationTime = new Long(0);
3929 mandeep.dh 458
            }
7506 amit.gupta 459
            items = client.getAllItemsByStatus(status.CONTENT_COMPLETE);
460
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
12973 amit.gupta 461
            //items.addAll(client.getAllItemsByStatus(status.PARTIALLY_ACTIVE));
4098 anupam.sin 462
        } 
3929 mandeep.dh 463
 
464
        // Filter invalid entities here
2367 rajveer 465
        List<Entity> validEntities = new ArrayList<Entity>();
7506 amit.gupta 466
        List<Long> validEntityIds = new ArrayList<Long>();
467
 
3929 mandeep.dh 468
        for (long entityID : entities.keySet()) {
469
            if (isValidEntity(entities.get(entityID))) {
470
                validEntities.add(entities.get(entityID));
7506 amit.gupta 471
                validEntityIds.add(entityID);
3929 mandeep.dh 472
            }
2171 rajveer 473
        }
7662 amit.gupta 474
 
12538 amit.gupta 475
        log.info("Generating synonyms");
7662 amit.gupta 476
        SynonymExporter sx = new SynonymExporter();
477
        sx.storeSynonyms(validEntities);
3929 mandeep.dh 478
 
479
        // Calculate comparison scores
480
        log.info("Calculating comparison scores");
2367 rajveer 481
        NewCMP cmp = new NewCMP(validEntities);
2171 rajveer 482
        Map<Long, Map<Long, Double>> slideScoresByEntity = cmp.getSlideScores();
2367 rajveer 483
        CreationUtils.storeSlideScores(slideScoresByEntity);
2658 rajveer 484
 
3516 rajveer 485
        // Fetch comparison statistics everyday and store them in BDB
7506 amit.gupta 486
        //This might be remove. 
3929 mandeep.dh 487
        log.info("Fetching comparison statistics");
3516 rajveer 488
        ComparisonStatsFetcher csf = new ComparisonStatsFetcher();
489
        csf.fetchAndStoreComparisonStats();
2726 rajveer 490
        populateEntityIdItemMap();
3929 mandeep.dh 491
 
4677 rajveer 492
 
3929 mandeep.dh 493
        log.info("Writing JSON file for special pages");
2838 mandeep.dh 494
        SpecialPageJSONConvertor bjc = new SpecialPageJSONConvertor();
3929 mandeep.dh 495
        bjc.writeToJSONFile(new File(Utils.EXPORT_JAVASCRIPT_CONTENT_PATH
496
                + "special-pages.json"));
2838 mandeep.dh 497
 
3929 mandeep.dh 498
        log.info("Generating velocity templates, images, documents etc.");
2171 rajveer 499
        NewVUI vui = new NewVUI(lastGenerationTime);
9280 amit.gupta 500
 
15844 amit.gupta 501
        for (Entity entity : validEntities) {
3929 mandeep.dh 502
            log.info("Processing Entityid: " + entity.getID());
503
            vui.generateContentForOneEntity(entity, Utils.EXPORT_VELOCITY_PATH);
15844 amit.gupta 504
        }
3929 mandeep.dh 505
 
9996 amit.gupta 506
        try {
13404 manas 507
        	/*AmazonSCDataGenerator ascdg = new AmazonSCDataGenerator(validPartialEntities);*/
508
        	AmazonSCDataGenerator ascdg = new AmazonSCDataGenerator(validPartialEntities,false);
9996 amit.gupta 509
        	ascdg.generateSCProdData();
510
        }catch (Exception e ){
511
        	log.info("Could not generate Jungle upload Feed");
512
        	e.printStackTrace();
513
        }
5004 varun.gupt 514
 
3929 mandeep.dh 515
        if (newLastGenerationTime != 0) {
516
            CreationUtils.storeLastContentGenerationTime(newLastGenerationTime);
517
        }
518
 
519
 
12538 amit.gupta 520
        log.info("Generating Solr files");
2367 rajveer 521
        NewIR ir = new NewIR(validEntities);
2227 rajveer 522
        ir.exportIRData();
3929 mandeep.dh 523
        // ir.transformIrDataXMLtoSolrXML();
7506 amit.gupta 524
 
525
        if(!GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
526
	        ir.exportIRMetaData();
527
	        ir.transformIrMetaDataXMLtoSolrSchemaXML();
528
	        ir.transformIrMetaDataXMLtoSolrCatchAllXML();
529
        }
2227 rajveer 530
 
3929 mandeep.dh 531
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
532
            List<Item> items = entry.getValue();
533
            for (Item item : items) {
7662 amit.gupta 534
                if (item.getItemStatus() == status.CONTENT_COMPLETE 
7506 amit.gupta 535
                		|| item.getItemStatus() == status.COMING_SOON) {
5360 amit.gupta 536
                	if(item.getStartDate() <= new Date().getTime() + ONE_DAY){
5227 amit.gupta 537
                		item.setItemStatus(status.ACTIVE);
538
                		item.setStatus_description("This item is active");
539
                	} else {
540
                		item.setItemStatus(status.COMING_SOON);
541
                		String productName = getProductName(item);
542
                		String statusDescription = productName + " is coming soon.";
543
                		if(item.getExpectedArrivalDate()>new Date().getTime() + ONE_DAY){
544
                			statusDescription = productName + " will be available by " 
545
                			+ new SimpleDateFormat("dd/MM/yy").format(new Date(item.getExpectedArrivalDate()));
546
                		}
5279 amit.gupta 547
                		//Send alert to Category team one day before expected arrival date
548
                		//So they may change the expected arrival date if they want to.
549
                		if(item.getExpectedArrivalDate() < new Date().getTime() + 2*ONE_DAY && 
550
                				item.getExpectedArrivalDate() > new Date().getTime() + ONE_DAY) {
551
                				alertItems.add(item);
552
                		}
5227 amit.gupta 553
                		item.setStatus_description(statusDescription);
554
                	}
2493 rajveer 555
                    client.updateItem(item);
5279 amit.gupta 556
            	}
3929 mandeep.dh 557
            }
2493 rajveer 558
        }
12538 amit.gupta 559
        sendAlertToCategoryTeam(alertItems);
2171 rajveer 560
    }
2367 rajveer 561
 
5279 amit.gupta 562
    private void sendAlertToCategoryTeam(List<Item> items) {
563
    	if(items!=null && items.size()!=0){
564
			GmailUtils util = new GmailUtils();
8053 amit.gupta 565
			String[] recipients = {"amit.gupta@shop2020.in", "chaitnaya.vats@shop2020.in", "khushal.bhatia@shop2020.in", "vrinda.k@shop2020.in"};
5279 amit.gupta 566
			String from = "build@shop2020.in";
567
			String password = "cafe@nes";
568
			String subject = Utils.EXPECTED_ARRIVAL_ACHIEVED_TEMPLATE;
569
			StringBuffer message = new StringBuffer("Please check the following items:\n");
570
			List<File> emptyList = new ArrayList<File>();
571
			for( Item item : items){
572
				message.append("\t" + getProductName(item));
573
			}
574
			try {
575
				util.sendSSLMessage(recipients, subject, message.toString(), from, password, emptyList);
576
			} catch (Exception e){
577
				log.info("Could not send alert" + e);
578
			}
579
    	}
580
	}
581
 
582
	private String getProductName(Item item) {
5227 amit.gupta 583
    	String brand = item.getBrand();
584
		String modelName = item.getModelName();
585
		String modelNumber = item.getModelNumber();
586
		String product = "";
587
		if(StringUtils.isEmpty(modelName)){
588
			product = brand + " " + modelNumber;
589
		}else {
590
			product = brand + " " + modelName + " " + modelNumber;
591
		}
592
		return product;
593
	}
594
 
2171 rajveer 595
    /**
3929 mandeep.dh 596
     * Checks weather entity is valid or not. Entity will be invalid in one of
597
     * these cases:
2367 rajveer 598
     * <ol>
599
     * <li>The entity is not ready.
600
     * <li>The category has not been updated yet. (Set to -1).
601
     * <li>Content has not been updated after last content generation timestamp.
602
     * </ol>
603
     * 
604
     * @param entity
605
     * @return
606
     * @throws Exception
2171 rajveer 607
     */
3929 mandeep.dh 608
    private boolean isValidEntity(Entity entity) throws Exception {
2367 rajveer 609
        EntityState state = CreationUtils.getEntityState(entity.getID());
7978 amit.gupta 610
        long categoryID = state.getCategoryID();
3929 mandeep.dh 611
        if (state.getStatus() != EntityStatus.READY || categoryID == -1) {
10000 amit.gupta 612
            return false;
2367 rajveer 613
        }
10000 amit.gupta 614
        if(state.getMerkedReadyOn().getTime() < this.lastGenerationTime) {
615
            return false;
2367 rajveer 616
        }
12538 amit.gupta 617
    	if(state.getMerkedReadyOn().getTime() > this.lastGenerationTimeNonZero){
10009 amit.gupta 618
        		Utils.info("Added to Partail:" + entity.getID());
9996 amit.gupta 619
        		validPartialEntities.add(entity);
620
        }
10000 amit.gupta 621
        return true;
2367 rajveer 622
    }
623
 
3929 mandeep.dh 624
    private void populateEntityIdItemMap() {
2171 rajveer 625
        Date todate = new Date();
4775 mandeep.dh 626
        Utils.info("Processing " + items.size() + " items");
3929 mandeep.dh 627
        for (Item item : items) {
4778 mandeep.dh 628
            Utils.info(item.getId() + ":" + item.getItemStatus() + ":" + item.getCatalogItemId());
3929 mandeep.dh 629
            // TODO Can be removed as we are checking in calling function
12972 amit.gupta 630
            /*if (!(item.getItemStatus() == status.ACTIVE
3929 mandeep.dh 631
                    || item.getItemStatus() == status.CONTENT_COMPLETE || item
5227 amit.gupta 632
                    .getItemStatus() == status.PAUSED || item.getItemStatus() == status.COMING_SOON)) {
2171 rajveer 633
                continue;
12972 amit.gupta 634
            }*/
8865 amit.gupta 635
            SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
636
            Utils.info(df1.format(item.getStartDate()) + ":" + item.getSellingPrice());
5227 amit.gupta 637
 
638
			if (todate.getTime() < item.getStartDate()
639
					&& (!item.isSetExpectedArrivalDate() || todate.getTime() < item.getComingSoonStartDate()) 
640
					|| item.getSellingPrice() == 0) {
641
				continue;
642
			}
4777 mandeep.dh 643
            Utils.info(item.getId() + " Item is adding");
2367 rajveer 644
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
3929 mandeep.dh 645
            if (itemList == null) {
2171 rajveer 646
                itemList = new ArrayList<Item>();
5227 amit.gupta 647
            } 
2171 rajveer 648
            itemList.add(item);
649
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
650
        }
2367 rajveer 651
 
4775 mandeep.dh 652
        Utils.info("Processing " + entityIdItemMap.size() + " entities");
3929 mandeep.dh 653
        // Remove all items which have not been updated since last content
654
        // generation.
7662 amit.gupta 655
        if (!(UPDATE_TYPE_CONTENT.equals(UPDATE_TYPE) || lastGenerationTime == 0)) {
656
	        for (Long entityId : entityIdItemMap.keySet()) {
657
	            boolean isValidEntity = false;
658
	            // If any one of the items has been updated before current
659
	            // timestamp, than we generate content for pricing
660
	            for (Item item : entityIdItemMap.get(entityId)) {
661
	                if (item.getUpdatedOn() > lastGenerationTime) {
662
	                    isValidEntity = true;
663
	                }
664
	            }
665
	            if (!isValidEntity) {
666
	                removeEntities.add(entityId);
667
	            }
668
	        }
2171 rajveer 669
        }
7506 amit.gupta 670
 
4775 mandeep.dh 671
        Utils.info("Final valid entities to be processed: " + entityIdItemMap.size());
2171 rajveer 672
    }
5084 phani.kuma 673
 
674
    private void synonymTitlesExporter() {
675
    	SynonymExporter sx = new SynonymExporter();
676
        Map<Long, Map<String,List<String>>> synonyms = sx.getSynonyms();
5453 phani.kuma 677
        Map<String, List<String>> finalsynonyms = new HashMap<String, List<String>>();
5084 phani.kuma 678
    	for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
679
            long entityId = entry.getKey();
680
	    	try{
681
	            String brand = "";
5453 phani.kuma 682
	            String originalModelName = "";
683
	            String originalModelNumber = "";
5084 phani.kuma 684
	            List<String> modelNameSynonyms =  new ArrayList<String>();
685
	            List<String> modelNumberSynonyms =  new ArrayList<String>();
686
	            List<String> titles = new ArrayList<String>();
687
	            Map<String,List<String>> synonymMap = synonyms.get(entityId);
688
	            if(synonymMap != null && !synonymMap.isEmpty()){
689
	            	if(synonymMap.get("ORIGINAL_MODEL_NAME") != null && !synonymMap.get("ORIGINAL_MODEL_NAME").isEmpty()){
690
	            		modelNameSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NAME"));
5453 phani.kuma 691
	            		originalModelName = synonymMap.get("ORIGINAL_MODEL_NAME").get(0);
5084 phani.kuma 692
	            	}
693
	            	if(synonymMap.get("MODEL_NAME") != null && !synonymMap.get("MODEL_NAME").isEmpty()){
694
	            		modelNameSynonyms.addAll(synonymMap.get("MODEL_NAME"));
695
	            	}
696
	            	if(synonymMap.get("ORIGINAL_MODEL_NUMBER") != null && !synonymMap.get("ORIGINAL_MODEL_NUMBER").isEmpty()){
697
	            		modelNumberSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NUMBER"));
5453 phani.kuma 698
	            		originalModelNumber = synonymMap.get("ORIGINAL_MODEL_NUMBER").get(0);
5084 phani.kuma 699
	            	}
700
	            	if(synonymMap.get("MODEL_NUMBER") != null && !synonymMap.get("MODEL_NUMBER").isEmpty()){
701
	            		modelNumberSynonyms.addAll(synonymMap.get("MODEL_NUMBER"));
702
	            	}
703
	            	brand = ((synonymMap.get("ORIGINAL_BRAND") != null && !synonymMap.get("ORIGINAL_BRAND").isEmpty()) ? synonymMap.get("ORIGINAL_BRAND").get(0) : "");
704
	            }
705
	            for(String model_name: modelNameSynonyms){
706
	            	for(String model_number: modelNumberSynonyms){
707
	            		String title = brand + " " + model_name + " " + model_number;
708
	            		title = title.replaceAll("  ", " ");
709
	            		titles.add(title);
710
	            	}
711
	            }
5453 phani.kuma 712
	            String originaltitle = brand + " " + originalModelName + " " + originalModelNumber;
713
	            originaltitle = originaltitle.replaceAll("  ", " ");
714
	            originaltitle = originaltitle.trim();
715
	            if(!originaltitle.isEmpty()) {
716
	            	finalsynonyms.put(originaltitle, titles);
717
	            }
5084 phani.kuma 718
	        } catch (Exception e) {
719
				e.printStackTrace();
720
			}
721
    	}
722
 
723
    	String autosuggestFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "autosuggest.json";
724
        Gson gson = new Gson();
725
		try {
726
			DBUtils.store(gson.toJson(finalsynonyms), autosuggestFilename);
727
		} catch (Exception e) {
728
			e.printStackTrace();
729
		}
730
    }
7662 amit.gupta 731
 
732
	public double getMinPrice(List<Item> items, long catalogId, Source source) {
733
		Item minPriceItem = null;
734
		for (Item item : items) {
735
			if (minPriceItem == null
736
					|| minPriceItem.getSellingPrice() > item.getSellingPrice()) {
737
				minPriceItem = item;
738
			}
739
		}
740
		return minPriceItem.getSellingPrice();
741
	}
2171 rajveer 742
}