Subversion Repositories SmartDukaan

Rev

Rev 7708 | Rev 7710 | 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;
7
import in.shop2020.metamodel.util.ExpandedEntity;
5945 mandeep.dh 8
import in.shop2020.model.v1.catalog.CatalogService.Client;
2171 rajveer 9
import in.shop2020.model.v1.catalog.Item;
3560 rajveer 10
import in.shop2020.model.v1.catalog.Source;
2171 rajveer 11
import in.shop2020.model.v1.catalog.status;
3127 rajveer 12
import in.shop2020.thrift.clients.CatalogClient;
2733 rajveer 13
import in.shop2020.ui.util.ComparisonStatsFetcher;
3083 vikas 14
import in.shop2020.ui.util.NewVUI;
2367 rajveer 15
import in.shop2020.ui.util.PriceInsertor;
2838 mandeep.dh 16
import in.shop2020.ui.util.SpecialPageJSONConvertor;
6602 amit.gupta 17
import in.shop2020.utils.ConfigClientKeys;
3464 rajveer 18
import in.shop2020.utils.GmailUtils;
2171 rajveer 19
 
3083 vikas 20
import java.io.File;
6871 amit.gupta 21
import java.io.FileNotFoundException;
22
import java.io.FileReader;
3083 vikas 23
import java.io.IOException;
6871 amit.gupta 24
import java.io.Reader;
4098 anupam.sin 25
import java.text.SimpleDateFormat;
3083 vikas 26
import java.util.ArrayList;
27
import java.util.Calendar;
28
import java.util.Date;
29
import java.util.HashMap;
5479 amit.gupta 30
import java.util.Iterator;
3083 vikas 31
import java.util.LinkedHashMap;
32
import java.util.List;
33
import java.util.Map;
2171 rajveer 34
 
3464 rajveer 35
import javax.mail.MessagingException;
36
 
3083 vikas 37
import org.apache.commons.cli.CommandLine;
38
import org.apache.commons.cli.CommandLineParser;
39
import org.apache.commons.cli.HelpFormatter;
40
import org.apache.commons.cli.Options;
41
import org.apache.commons.cli.ParseException;
42
import org.apache.commons.cli.PosixParser;
5227 amit.gupta 43
import org.apache.commons.lang.StringUtils;
3929 mandeep.dh 44
import org.apache.commons.logging.Log;
45
import org.apache.commons.logging.LogFactory;
2171 rajveer 46
 
5084 phani.kuma 47
import com.google.gson.Gson;
6871 amit.gupta 48
import com.google.gson.reflect.TypeToken;
5084 phani.kuma 49
 
3929 mandeep.dh 50
public class ContentGenerationUtility {
51
    private static final String   UPDATE_TYPE_CATALOG         = "CATALOG";
2171 rajveer 52
 
3929 mandeep.dh 53
    private static final String   UPDATE_TYPE_CONTENT         = "CONTENT";
3083 vikas 54
 
4098 anupam.sin 55
    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 56
 
57
    private static Log            log                         = LogFactory
58
                                                                      .getLog(ContentGenerationUtility.class);
5227 amit.gupta 59
    private static long 			ONE_DAY					  = 24*60*60*1000;  	//milliseconds in a day						 	
3929 mandeep.dh 60
    // Commandline options
61
    private static Options        options                     = null;
62
    private static final String   GENERATION_TYPE_INCREMENTAL = "INCREMENTAL";
63
    private static final String   GENERATION_TYPE_ALL         = "ALL";
64
    private static final String   GENERATION_TYPE_ONE         = "ONE";
65
    private static final String   UPDATE_TYPE_OPTION          = "u";
66
    private static final String   GENERATION_TYPE_OPTION      = "t";
67
    private static final String   ENTITY_ID_OPTION            = "e";
4098 anupam.sin 68
    private static final String   TIMESTAMP_OPTION            = "s";
3929 mandeep.dh 69
 
70
    // Default values of cmdline options
71
    private static String         UPDATE_TYPE                 = UPDATE_TYPE_CONTENT;
72
    private static String         GENERATION_TYPE             = GENERATION_TYPE_INCREMENTAL;
73
    private static String         ENTITY_ID                   = "ALL";
5664 amit.gupta 74
    private static String [] 	  DOMAINPATHS 			      = Utils.DOMAIN_NAMES_FOR_CONTENT_GENERATION.split(";");
3929 mandeep.dh 75
 
4098 anupam.sin 76
    private Date 				  timeStamp			  		  = null;
3929 mandeep.dh 77
    private CommandLine           cmd                         = null;
78
    private Map<Long, List<Item>> entityIdItemMap             = new LinkedHashMap<Long, List<Item>>();
79
    private Long                  lastGenerationTime          = 0l;
80
    private Map<Long, Entity>     entities;
7662 amit.gupta 81
    private List<Long> removeEntities = new ArrayList<Long>();
3929 mandeep.dh 82
    private List<Item>            items;
83
    private List<Source>          sources;
84
    private CatalogClient         csc;
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();
7228 amit.gupta 204
        String[] sendTo = { "rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "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
            }
7506 amit.gupta 274
 
6274 amit.gupta 275
            //ProductListGenerator.updatePriceForEntity(Long.parseLong(ENTITY_ID), items.get(0).getSellingPrice(), items.get(0).getMrp());
3929 mandeep.dh 276
        } else {
6622 rajveer 277
        	log.info("Before getting active items.");
2367 rajveer 278
            items = client.getAllItemsByStatus(status.ACTIVE);
7506 amit.gupta 279
            for (Item item : items) {
280
            	activeItems.add(item.getId());
281
            }
6622 rajveer 282
            log.info("Before getting coming items.");
5227 amit.gupta 283
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
6622 rajveer 284
            log.info("Before getting paused items.");
2367 rajveer 285
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
3929 mandeep.dh 286
            // Clean up the data from the solr directories.
6622 rajveer 287
            log.info("Before removing old resources.");
2367 rajveer 288
            removeOldResources();
7709 amit.gupta 289
            if(Calendar.getInstance().get(Calendar.AM_PM)==Calendar.AM )
7708 amit.gupta 290
            try {
291
            	//Generate prices and availability data for amazon
292
            	AmazonSCDataGenerator.generatePricesAndAvailability(items);
293
            } catch (Exception e) {
294
            	log.info("Could not generate Amazon prices and availability", e);
295
            }
2367 rajveer 296
 
297
        }
3929 mandeep.dh 298
 
7662 amit.gupta 299
/*        if (GENERATION_TYPE.equals(GENERATION_TYPE_INCREMENTAL)) {
2367 rajveer 300
        }
7662 amit.gupta 301
*/
3929 mandeep.dh 302
        populateEntityIdItemMap();
6602 amit.gupta 303
        // Generate partners and json objects for phones only
304
        if (!GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
305
        	try	{
7506 amit.gupta 306
	        	ProductListGenerator generator = new ProductListGenerator(entityIdItemMap);
307
 
308
	        	log.info("Before auto suggest json");
309
	        	synonymTitlesExporter();
310
 
311
	        	log.info("Before product list js.");
312
	        	generator.generateProductListJavascript();
313
 
6602 amit.gupta 314
        	} catch (Exception e) {
6623 rajveer 315
        		e.printStackTrace();
6602 amit.gupta 316
        	}
317
 
318
        }
2367 rajveer 319
        PriceInsertor priceInserter = new PriceInsertor();
320
 
6842 amit.gupta 321
        Map<Long,List<String>> entityTags = client.getAllEntityTags();
6871 amit.gupta 322
        Map<Long, Integer> popularityMap = getPolularityMap();
7670 amit.gupta 323
        List<Long> pausedByRiskItems = getRiskyActiveItems();
3929 mandeep.dh 324
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
325
            long entityId = entry.getKey();
326
            List<Item> items = entry.getValue();
5664 amit.gupta 327
            double minPrice = 0d;
7506 amit.gupta 328
 
329
            //Evaluating availability
330
            String availability = "Out of Stock";
331
            for(Item i: items){
7670 amit.gupta 332
            	if(i.getItemStatus().equals(status.ACTIVE)) {
333
            		if(!(i.isRisky() && pausedByRiskItems.contains(i.getId()) )){
7506 amit.gupta 334
            			availability = "In Stock";
335
            			break;
336
            		}
6602 amit.gupta 337
            	}
338
            }
5664 amit.gupta 339
            StringBuilder priceString = new StringBuilder();
6602 amit.gupta 340
            StringBuilder availabilityString = new StringBuilder();
5664 amit.gupta 341
            boolean domainOnce = true;
5669 amit.gupta 342
            boolean sourceOnce = true;
5664 amit.gupta 343
            for(String domainPath : DOMAINPATHS){
344
            	String domainName = domainPath;
345
            	String pathName = domainPath.split("\\.")[0].split(":")[0];
7662 amit.gupta 346
            	if(!removeEntities.contains(entityId)){
347
            		priceInserter.insertPriceInHtml(items, entityId, domainName, Utils.EXPORT_PATH + "html/entities-" +  pathName + "/", null);
348
            	}
7336 amit.gupta 349
            	if(domainOnce){
7662 amit.gupta 350
            		minPrice = getMinPrice(items, entityId, null);
7336 amit.gupta 351
            		priceString.append("<field name=\"F_50002\">" + minPrice + "</field>");
352
            		availabilityString.append("<field name=\"F_50028\">" + availability + "</field>");
353
            		if(entityTags.containsKey(entityId)) {
354
            			List<String> tags = entityTags.get(entityId);
355
            			for(String tag: tags){
356
            				availabilityString.append("\n<field name=\"F_50029\">" + tag + "</field>");
357
            			}
358
            		}
359
            		if(popularityMap.containsKey(entityId)) {
360
            			availabilityString.append("\n<field name=\"F_50030\">" + popularityMap.get(entityId) + "</field>");
361
            		}else {
362
            			availabilityString.append("\n<field name=\"F_50030\">" + "0" + "</field>");
363
            		}
364
            		domainOnce = false;
5664 amit.gupta 365
            	}
7336 amit.gupta 366
            	if(sources != null){
367
            		for (Source source : sources) {
7662 amit.gupta 368
						priceInserter.insertPriceInHtml(items, entityId,domainName, Utils.EXPORT_PATH + "html/entities-" + pathName + "/",source);
7336 amit.gupta 369
                        if(sourceOnce){
7662 amit.gupta 370
                        	minPrice = getMinPrice(items, entityId, source);
7336 amit.gupta 371
                        	priceString.append("<field name=\"F_50002_"
372
                                + source.getId() + "\">" + minPrice + "</field>");
373
                        }
374
            		}
375
            		sourceOnce = false;
376
            	}
2367 rajveer 377
            }
3929 mandeep.dh 378
 
379
            priceInserter.insertPriceInSolrData(entityId,
6602 amit.gupta 380
                    priceString.toString(), availabilityString.toString());
2367 rajveer 381
        }
3929 mandeep.dh 382
 
4058 rajveer 383
        priceInserter.copySolrSchemaFiles();
2367 rajveer 384
    }
385
 
7279 amit.gupta 386
	private Map<Long, Integer> getPolularityMap() {
6871 amit.gupta 387
		try {
388
			Reader reader = new FileReader(Utils.EXPORT_PATH + Utils.POPULARITY_JSON);
389
			return new Gson().fromJson(reader, new TypeToken<Map<Long, Integer>>() {}.getType());
390
		} catch (FileNotFoundException e) {
391
			log.error("Could not read popularity file");
392
			e.printStackTrace();
393
			return new HashMap<Long, Integer>();
394
		}
395
 
396
	}
7670 amit.gupta 397
	private List<Long> getRiskyActiveItems() {
398
		try {
399
			Reader reader = new FileReader(Utils.EXPORT_PATH + Utils.RISKY_PAUSED_JSON);
7673 amit.gupta 400
			return new Gson().fromJson(reader, new TypeToken<List<Long>>() {}.getType());
7670 amit.gupta 401
		} catch (FileNotFoundException e) {
402
			log.error("Could not read popularity file");
403
			e.printStackTrace();
404
			return new ArrayList<Long>();
405
		}
406
 
407
	}
6871 amit.gupta 408
 
6602 amit.gupta 409
	/**
2171 rajveer 410
     * Generates content for the specified entity embedding links to the
411
     * specified domain name.
412
     * 
3929 mandeep.dh 413
     * The method will not generate content if one of the following conditions
414
     * is met:
2171 rajveer 415
     * <ol>
416
     * <li>The entity is not ready.
417
     * <li>The category has not been updated yet. (Set to -1).
2367 rajveer 418
     * <li>The content has not been updated.
2171 rajveer 419
     * </ol>
3929 mandeep.dh 420
     * 
2367 rajveer 421
     * @throws
2171 rajveer 422
     */
3929 mandeep.dh 423
    private void generateContent() throws Exception {
424
        if (GENERATION_TYPE.equals(GENERATION_TYPE_ALL)) {
425
            entities = CreationUtils.getEntities();
2367 rajveer 426
            lastGenerationTime = new Long(0);
7506 amit.gupta 427
            items = client.getAllItemsByStatus(status.CONTENT_COMPLETE);
428
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
429
            items.addAll(client.getAllItemsByStatus(status.ACTIVE));
430
            items.addAll(client.getAllItemsByStatus(status.PAUSED));
3929 mandeep.dh 431
        } else if (GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
432
            entities = new HashMap<Long, Entity>();
433
            entities.put(Long.parseLong(ENTITY_ID),
434
                    CreationUtils.getEntity(Long.parseLong(ENTITY_ID)));
7506 amit.gupta 435
            items = client.getItemsByCatalogId(Long.parseLong(ENTITY_ID));
436
            Iterator<Item> ite = items.iterator();
437
            while(ite.hasNext()) {
438
            	Item i = ite.next();
439
            	if(!(i.getItemStatus().equals(status.ACTIVE) || i.getItemStatus().equals(status.PAUSED) 
440
            	|| i.getItemStatus().equals(status.CONTENT_COMPLETE) || i.getItemStatus().equals(status.COMING_SOON))){
441
            		ite.remove();
442
            	}
443
            }
3929 mandeep.dh 444
            lastGenerationTime = new Long(0);
445
        } else {
4098 anupam.sin 446
        	entities = CreationUtils.getEntities();
447
            //  When we read lastGenerationTime from database
448
            //  then only we should mark the 
449
            //	current time as newLastGenerationTime
450
            if(timeStamp == null) {
451
            	newLastGenerationTime = new Date().getTime();
452
            	lastGenerationTime = CreationUtils.getLastContentGenerationTime();
453
            } else {
454
            	lastGenerationTime = timeStamp.getTime();
455
            }
456
 
3929 mandeep.dh 457
            log.info("lastGenerationTime: " + lastGenerationTime);
458
            if (lastGenerationTime == null) {
2171 rajveer 459
                lastGenerationTime = new Long(0);
3929 mandeep.dh 460
            }
7506 amit.gupta 461
            items = client.getAllItemsByStatus(status.CONTENT_COMPLETE);
462
            items.addAll(client.getAllItemsByStatus(status.COMING_SOON));
4098 anupam.sin 463
        } 
3929 mandeep.dh 464
 
465
        // Filter invalid entities here
2367 rajveer 466
        List<Entity> validEntities = new ArrayList<Entity>();
7506 amit.gupta 467
        List<Long> validEntityIds = new ArrayList<Long>();
468
 
3929 mandeep.dh 469
        for (long entityID : entities.keySet()) {
470
            if (isValidEntity(entities.get(entityID))) {
471
                validEntities.add(entities.get(entityID));
7506 amit.gupta 472
                validEntityIds.add(entityID);
3929 mandeep.dh 473
            }
2171 rajveer 474
        }
7662 amit.gupta 475
 
476
        log.info("Generating synonyms");
477
        SynonymExporter sx = new SynonymExporter();
478
        sx.storeSynonyms(validEntities);
3929 mandeep.dh 479
 
480
        // Calculate comparison scores
481
        log.info("Calculating comparison scores");
2367 rajveer 482
        NewCMP cmp = new NewCMP(validEntities);
2171 rajveer 483
        Map<Long, Map<Long, Double>> slideScoresByEntity = cmp.getSlideScores();
2367 rajveer 484
        CreationUtils.storeSlideScores(slideScoresByEntity);
2658 rajveer 485
 
3516 rajveer 486
        // Fetch comparison statistics everyday and store them in BDB
7506 amit.gupta 487
        //This might be remove. 
3929 mandeep.dh 488
        log.info("Fetching comparison statistics");
3516 rajveer 489
        ComparisonStatsFetcher csf = new ComparisonStatsFetcher();
490
        csf.fetchAndStoreComparisonStats();
2726 rajveer 491
        populateEntityIdItemMap();
3929 mandeep.dh 492
 
4677 rajveer 493
 
3929 mandeep.dh 494
        log.info("Writing JSON file for special pages");
2838 mandeep.dh 495
        SpecialPageJSONConvertor bjc = new SpecialPageJSONConvertor();
3929 mandeep.dh 496
        bjc.writeToJSONFile(new File(Utils.EXPORT_JAVASCRIPT_CONTENT_PATH
497
                + "special-pages.json"));
2838 mandeep.dh 498
 
3929 mandeep.dh 499
        log.info("Generating velocity templates, images, documents etc.");
2171 rajveer 500
        NewVUI vui = new NewVUI(lastGenerationTime);
3929 mandeep.dh 501
        for (Entity entity : validEntities) {
502
            log.info("Processing Entityid: " + entity.getID());
503
            vui.generateContentForOneEntity(entity, Utils.EXPORT_VELOCITY_PATH);
2171 rajveer 504
        }
3929 mandeep.dh 505
 
5004 varun.gupt 506
 
3929 mandeep.dh 507
        if (newLastGenerationTime != 0) {
508
            CreationUtils.storeLastContentGenerationTime(newLastGenerationTime);
509
        }
510
 
511
 
512
        log.info("Generating Solr files");
2367 rajveer 513
        NewIR ir = new NewIR(validEntities);
2227 rajveer 514
        ir.exportIRData();
3929 mandeep.dh 515
        // ir.transformIrDataXMLtoSolrXML();
7506 amit.gupta 516
 
517
        if(!GENERATION_TYPE.equals(GENERATION_TYPE_ONE)) {
518
	        ir.exportIRMetaData();
519
	        ir.transformIrMetaDataXMLtoSolrSchemaXML();
520
	        ir.transformIrMetaDataXMLtoSolrCatchAllXML();
521
        }
2227 rajveer 522
 
3929 mandeep.dh 523
        for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
524
            List<Item> items = entry.getValue();
525
            for (Item item : items) {
7662 amit.gupta 526
                if (item.getItemStatus() == status.CONTENT_COMPLETE 
7506 amit.gupta 527
                		|| item.getItemStatus() == status.COMING_SOON) {
5360 amit.gupta 528
                	if(item.getStartDate() <= new Date().getTime() + ONE_DAY){
5227 amit.gupta 529
                		item.setItemStatus(status.ACTIVE);
530
                		item.setStatus_description("This item is active");
531
                	} else {
532
                		item.setItemStatus(status.COMING_SOON);
533
                		String productName = getProductName(item);
534
                		String statusDescription = productName + " is coming soon.";
535
                		if(item.getExpectedArrivalDate()>new Date().getTime() + ONE_DAY){
536
                			statusDescription = productName + " will be available by " 
537
                			+ new SimpleDateFormat("dd/MM/yy").format(new Date(item.getExpectedArrivalDate()));
538
                		}
5279 amit.gupta 539
                		//Send alert to Category team one day before expected arrival date
540
                		//So they may change the expected arrival date if they want to.
541
                		if(item.getExpectedArrivalDate() < new Date().getTime() + 2*ONE_DAY && 
542
                				item.getExpectedArrivalDate() > new Date().getTime() + ONE_DAY) {
543
                				alertItems.add(item);
544
                		}
5227 amit.gupta 545
                		item.setStatus_description(statusDescription);
546
                	}
2493 rajveer 547
                    client.updateItem(item);
5279 amit.gupta 548
            	}
3929 mandeep.dh 549
            }
2493 rajveer 550
        }
5279 amit.gupta 551
        sendAlertToCategoryTeam(alertItems);
2171 rajveer 552
    }
2367 rajveer 553
 
5279 amit.gupta 554
    private void sendAlertToCategoryTeam(List<Item> items) {
555
    	if(items!=null && items.size()!=0){
556
			GmailUtils util = new GmailUtils();
6876 amit.gupta 557
			String[] recipients = {"amit.gupta@shop2020.in", "chaitnaya.vats@shop2020.in", "khushal.bhatia@shop2020.in"};
5279 amit.gupta 558
			String from = "build@shop2020.in";
559
			String password = "cafe@nes";
560
			String subject = Utils.EXPECTED_ARRIVAL_ACHIEVED_TEMPLATE;
561
			StringBuffer message = new StringBuffer("Please check the following items:\n");
562
			List<File> emptyList = new ArrayList<File>();
563
			for( Item item : items){
564
				message.append("\t" + getProductName(item));
565
			}
566
			try {
567
				util.sendSSLMessage(recipients, subject, message.toString(), from, password, emptyList);
568
			} catch (Exception e){
569
				log.info("Could not send alert" + e);
570
			}
571
    	}
572
	}
573
 
574
	private String getProductName(Item item) {
5227 amit.gupta 575
    	String brand = item.getBrand();
576
		String modelName = item.getModelName();
577
		String modelNumber = item.getModelNumber();
578
		String product = "";
579
		if(StringUtils.isEmpty(modelName)){
580
			product = brand + " " + modelNumber;
581
		}else {
582
			product = brand + " " + modelName + " " + modelNumber;
583
		}
584
		return product;
585
	}
586
 
2171 rajveer 587
    /**
3929 mandeep.dh 588
     * Checks weather entity is valid or not. Entity will be invalid in one of
589
     * these cases:
2367 rajveer 590
     * <ol>
591
     * <li>The entity is not ready.
592
     * <li>The category has not been updated yet. (Set to -1).
593
     * <li>Content has not been updated after last content generation timestamp.
594
     * </ol>
595
     * 
596
     * @param entity
597
     * @return
598
     * @throws Exception
2171 rajveer 599
     */
3929 mandeep.dh 600
    private boolean isValidEntity(Entity entity) throws Exception {
2367 rajveer 601
        ExpandedEntity expEntity = new ExpandedEntity(entity);
602
        EntityState state = CreationUtils.getEntityState(entity.getID());
603
        long categoryID = expEntity.getCategoryID();
3929 mandeep.dh 604
 
605
        if (state.getStatus() != EntityStatus.READY || categoryID == -1) {
2367 rajveer 606
            return false;
607
        }
3929 mandeep.dh 608
        if (state.getMerkedReadyOn().getTime() < this.lastGenerationTime) {
2367 rajveer 609
            return false;
610
        }
611
        return true;
612
    }
613
 
3929 mandeep.dh 614
    private void populateEntityIdItemMap() {
2171 rajveer 615
        Date todate = new Date();
4775 mandeep.dh 616
        Utils.info("Processing " + items.size() + " items");
3929 mandeep.dh 617
        for (Item item : items) {
4778 mandeep.dh 618
            Utils.info(item.getId() + ":" + item.getItemStatus() + ":" + item.getCatalogItemId());
3929 mandeep.dh 619
            // TODO Can be removed as we are checking in calling function
620
            if (!(item.getItemStatus() == status.ACTIVE
621
                    || item.getItemStatus() == status.CONTENT_COMPLETE || item
5227 amit.gupta 622
                    .getItemStatus() == status.PAUSED || item.getItemStatus() == status.COMING_SOON)) {
2171 rajveer 623
                continue;
624
            }
4777 mandeep.dh 625
            Utils.info(item.getStartDate() + ":" + item.getSellingPrice());
5227 amit.gupta 626
 
627
			if (todate.getTime() < item.getStartDate()
628
					&& (!item.isSetExpectedArrivalDate() || todate.getTime() < item.getComingSoonStartDate()) 
629
					|| item.getSellingPrice() == 0) {
630
				continue;
631
			}
4777 mandeep.dh 632
            Utils.info(item.getId() + " Item is adding");
2367 rajveer 633
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
3929 mandeep.dh 634
            if (itemList == null) {
2171 rajveer 635
                itemList = new ArrayList<Item>();
5227 amit.gupta 636
            } 
2171 rajveer 637
            itemList.add(item);
638
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
639
        }
2367 rajveer 640
 
4775 mandeep.dh 641
        Utils.info("Processing " + entityIdItemMap.size() + " entities");
3929 mandeep.dh 642
        // Remove all items which have not been updated since last content
643
        // generation.
7662 amit.gupta 644
        if (!(UPDATE_TYPE_CONTENT.equals(UPDATE_TYPE) || lastGenerationTime == 0)) {
645
	        for (Long entityId : entityIdItemMap.keySet()) {
646
	            boolean isValidEntity = false;
647
	            // If any one of the items has been updated before current
648
	            // timestamp, than we generate content for pricing
649
	            for (Item item : entityIdItemMap.get(entityId)) {
650
	                if (item.getUpdatedOn() > lastGenerationTime) {
651
	                    isValidEntity = true;
652
	                }
653
	            }
654
	            if (!isValidEntity) {
655
	                removeEntities.add(entityId);
656
	            }
657
	        }
2171 rajveer 658
        }
7506 amit.gupta 659
 
4775 mandeep.dh 660
        Utils.info("Final valid entities to be processed: " + entityIdItemMap.size());
2171 rajveer 661
    }
5084 phani.kuma 662
 
663
    private void synonymTitlesExporter() {
664
    	SynonymExporter sx = new SynonymExporter();
665
        Map<Long, Map<String,List<String>>> synonyms = sx.getSynonyms();
5453 phani.kuma 666
        Map<String, List<String>> finalsynonyms = new HashMap<String, List<String>>();
5084 phani.kuma 667
    	for (Map.Entry<Long, List<Item>> entry : entityIdItemMap.entrySet()) {
668
            long entityId = entry.getKey();
669
	    	try{
670
	            String brand = "";
5453 phani.kuma 671
	            String originalModelName = "";
672
	            String originalModelNumber = "";
5084 phani.kuma 673
	            List<String> modelNameSynonyms =  new ArrayList<String>();
674
	            List<String> modelNumberSynonyms =  new ArrayList<String>();
675
	            List<String> titles = new ArrayList<String>();
676
	            Map<String,List<String>> synonymMap = synonyms.get(entityId);
677
	            if(synonymMap != null && !synonymMap.isEmpty()){
678
	            	if(synonymMap.get("ORIGINAL_MODEL_NAME") != null && !synonymMap.get("ORIGINAL_MODEL_NAME").isEmpty()){
679
	            		modelNameSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NAME"));
5453 phani.kuma 680
	            		originalModelName = synonymMap.get("ORIGINAL_MODEL_NAME").get(0);
5084 phani.kuma 681
	            	}
682
	            	if(synonymMap.get("MODEL_NAME") != null && !synonymMap.get("MODEL_NAME").isEmpty()){
683
	            		modelNameSynonyms.addAll(synonymMap.get("MODEL_NAME"));
684
	            	}
685
	            	if(synonymMap.get("ORIGINAL_MODEL_NUMBER") != null && !synonymMap.get("ORIGINAL_MODEL_NUMBER").isEmpty()){
686
	            		modelNumberSynonyms.addAll(synonymMap.get("ORIGINAL_MODEL_NUMBER"));
5453 phani.kuma 687
	            		originalModelNumber = synonymMap.get("ORIGINAL_MODEL_NUMBER").get(0);
5084 phani.kuma 688
	            	}
689
	            	if(synonymMap.get("MODEL_NUMBER") != null && !synonymMap.get("MODEL_NUMBER").isEmpty()){
690
	            		modelNumberSynonyms.addAll(synonymMap.get("MODEL_NUMBER"));
691
	            	}
692
	            	brand = ((synonymMap.get("ORIGINAL_BRAND") != null && !synonymMap.get("ORIGINAL_BRAND").isEmpty()) ? synonymMap.get("ORIGINAL_BRAND").get(0) : "");
693
	            }
694
	            for(String model_name: modelNameSynonyms){
695
	            	for(String model_number: modelNumberSynonyms){
696
	            		String title = brand + " " + model_name + " " + model_number;
697
	            		title = title.replaceAll("  ", " ");
698
	            		titles.add(title);
699
	            	}
700
	            }
5453 phani.kuma 701
	            String originaltitle = brand + " " + originalModelName + " " + originalModelNumber;
702
	            originaltitle = originaltitle.replaceAll("  ", " ");
703
	            originaltitle = originaltitle.trim();
704
	            if(!originaltitle.isEmpty()) {
705
	            	finalsynonyms.put(originaltitle, titles);
706
	            }
5084 phani.kuma 707
	        } catch (Exception e) {
708
				e.printStackTrace();
709
			}
710
    	}
711
 
712
    	String autosuggestFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "autosuggest.json";
713
        Gson gson = new Gson();
714
		try {
715
			DBUtils.store(gson.toJson(finalsynonyms), autosuggestFilename);
716
		} catch (Exception e) {
717
			e.printStackTrace();
718
		}
719
    }
7662 amit.gupta 720
 
721
	public double getMinPrice(List<Item> items, long catalogId, Source source) {
722
		Item minPriceItem = null;
723
		for (Item item : items) {
724
			if (minPriceItem == null
725
					|| minPriceItem.getSellingPrice() > item.getSellingPrice()) {
726
				minPriceItem = item;
727
			}
728
		}
729
		return minPriceItem.getSellingPrice();
730
	}
2171 rajveer 731
}