Subversion Repositories SmartDukaan

Rev

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