Subversion Repositories SmartDukaan

Rev

Rev 37217 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
25380 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.google.gson.Gson;
30080 amit.gupta 4
import com.jcraft.jsch.*;
25380 amit.gupta 5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
6
import com.spice.profitmandi.common.solr.SolrService;
35583 ranu 7
import com.spice.profitmandi.dao.entity.auth.AuthUser;
37208 amit 8
import com.spice.profitmandi.dao.entity.catalog.Catalog;
25380 amit.gupta 9
import com.spice.profitmandi.dao.entity.catalog.Item;
36404 amit 10
import com.spice.profitmandi.dao.entity.catalog.MonitorType;
35549 ranu 11
import com.spice.profitmandi.dao.entity.cs.Bulletin;
33443 ranu 12
import com.spice.profitmandi.dao.entity.cs.PartnerRegion;
13
import com.spice.profitmandi.dao.entity.cs.Region;
28264 tejbeer 14
import com.spice.profitmandi.dao.entity.dtr.DocumentUrl;
33443 ranu 15
import com.spice.profitmandi.dao.entity.fofo.PrintResource;
16
import com.spice.profitmandi.dao.entity.fofo.PrintResourceRegion;
17
import com.spice.profitmandi.dao.entity.user.User;
35487 ranu 18
import com.spice.profitmandi.dao.enumuration.inventory.CatalogMovingEnum;
33443 ranu 19
import com.spice.profitmandi.dao.model.*;
20
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
37184 ranu 21
import com.spice.profitmandi.dao.repository.catalog.*;
35549 ranu 22
import com.spice.profitmandi.dao.repository.cs.BulletinRepository;
33443 ranu 23
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
24
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
28264 tejbeer 25
import com.spice.profitmandi.dao.repository.dtr.DocumentUrlRepository;
25380 amit.gupta 26
import com.spice.profitmandi.dao.repository.dtr.Mongo;
33443 ranu 27
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRegionRepository;
28
import com.spice.profitmandi.dao.repository.fofo.PrintResourceRepository;
29
import com.spice.profitmandi.dao.repository.user.UserRepository;
37216 amit 30
import com.spice.profitmandi.service.catalog.CategorySpecDerivationService;
37214 amit 31
import com.spice.profitmandi.service.catalog.CategorySpecUtil;
32952 amit.gupta 32
import com.spice.profitmandi.service.catalog.ItemLoaderService;
25380 amit.gupta 33
import com.spice.profitmandi.web.model.EntityMediaPojo;
33443 ranu 34
import com.spice.profitmandi.web.model.LoginDetails;
35
import com.spice.profitmandi.web.util.CookiesProcessor;
25380 amit.gupta 36
import com.spice.profitmandi.web.util.MVCResponseSender;
30080 amit.gupta 37
import org.apache.commons.csv.CSVFormat;
38
import org.apache.commons.csv.CSVParser;
39
import org.apache.commons.csv.CSVRecord;
40
import org.apache.commons.lang3.StringUtils;
41
import org.apache.logging.log4j.LogManager;
42
import org.apache.logging.log4j.Logger;
31330 tejbeer 43
import org.json.JSONArray;
44
import org.json.JSONObject;
30080 amit.gupta 45
import org.springframework.beans.factory.annotation.Autowired;
35346 ranu 46
import org.springframework.http.ResponseEntity;
30080 amit.gupta 47
import org.springframework.stereotype.Controller;
35487 ranu 48
import org.springframework.transaction.annotation.Transactional;
30080 amit.gupta 49
import org.springframework.ui.Model;
50
import org.springframework.web.bind.annotation.*;
51
import org.springframework.web.multipart.MultipartFile;
25380 amit.gupta 52
 
30080 amit.gupta 53
import javax.servlet.http.HttpServletRequest;
54
import javax.xml.bind.DatatypeConverter;
55
import java.io.*;
56
import java.sql.Timestamp;
57
import java.time.LocalDate;
58
import java.time.LocalDateTime;
59
import java.time.ZoneOffset;
60
import java.util.*;
61
import java.util.stream.Collectors;
62
 
35458 amit 63
@Transactional(rollbackFor = Throwable.class)
25380 amit.gupta 64
@Controller
65
public class ContentController {
66
	@Autowired
67
	MVCResponseSender mvcResponseSender;
68
 
69
	@Autowired
70
	Mongo mongoClient;
71
 
72
	@Autowired
73
	SolrService solrService;
74
 
75
	@Autowired
76
	ItemRepository itemRepository;
77
 
28264 tejbeer 78
	@Autowired
79
	DocumentUrlRepository documentUrlRepository;
80
 
31330 tejbeer 81
	@Autowired
82
	FocusedModelRepository focusedModelRepository;
33443 ranu 83
 
84
	@Autowired
85
	PrintResourceRepository printResourceRepository;
86
	@Autowired
87
	AuthRepository authRepository;
88
	@Autowired
89
	RegionRepository regionRepository;
90
	@Autowired
91
	PrintResourceRegionRepository printResourceRegionRepository;
92
	@Autowired
93
	PartnerRegionRepository partnerRegionRepository;
33973 tejus.loha 94
	@Autowired
95
	SuperCatalogRepository superCatalogRepository;
35487 ranu 96
	@Autowired
97
	CatalogRepository catalogRepository;
35549 ranu 98
	@Autowired
36404 amit 99
	CatalogMonitorTypeRepository catalogMonitorTypeRepository;
100
	@Autowired
37214 amit 101
	CategorySpecDefinitionRepository categorySpecDefinitionRepository;
102
	@Autowired
35549 ranu 103
	BulletinRepository bulletinRepository;
25380 amit.gupta 104
	private Gson gson = new Gson();
105
 
106
	public static final int Entity_Id = 0;
107
	public static final int Title = 1;
108
	public static final int KeySpec1 = 2;
109
	public static final int KeySpec2 = 3;
110
	public static final int KeySpec3 = 4;
111
	public static final int KeySpec4 = 5;
112
	public static final int Warranty = 6;
113
	public static final int Package_Contents = 7;
37214 amit 114
	// new-layout template only: SpecValue1..5 at 8-12, detailed specs from 13.
115
	// Legacy templates (no SpecValue header at col 8) keep detailed specs at 8.
116
	public static final int SpecValue1 = 8;
117
	public static final int SPEC_VALUE_COUNT = 5;
118
	public static final int DetailedSpecsLegacyStart = 8;
119
	public static final int DetailedSpecsSpecLayoutStart = 13;
28264 tejbeer 120
	private static final String IMAGE_REMOTE_DIR = "/var/www/dtrdashboard/uploads/campaigns/";
121
	private static final String IMAGE_STATIC_SERVER_URL = "https://images.smartdukaan.com/uploads/campaigns";
25380 amit.gupta 122
 
29900 amit.gupta 123
	private static final String REMOTE_DIR = "/var/www/static.saholic.com/images/media/";
31330 tejbeer 124
	// private static final String REMOTE_DIR = "/tmp";
25986 amit.gupta 125
	private static final String STATIC_SERVER_URL = "https://static%d.smartdukaan.com/images/media/";
25380 amit.gupta 126
 
127
	private static final String THUMBNAIL = "thumbnail";
128
	private static final String ICON = "icon";
129
	private static final String DEFAULT = "default";
130
	private static final String NONE = "";
25409 amit.gupta 131
 
25400 amit.gupta 132
	private static final Logger LOGGER = LogManager.getLogger(ContentController.class);
25380 amit.gupta 133
 
134
	private String getFileName(int entityId, String description, String extension) {
135
		List<Item> items = itemRepository.selectAllByCatalogItemId(entityId);
25409 amit.gupta 136
		String imageString = getMediaPrefix(items.get(0).getItemDescriptionNoColor() + " " + description) + "-"
25380 amit.gupta 137
				+ LocalDateTime.now().toEpochSecond(ZoneOffset.ofHoursMinutes(5, 30));
25413 amit.gupta 138
		return imageString + "." + extension;
25380 amit.gupta 139
	}
140
 
35529 ranu 141
	@PostMapping(value = "/content/upload")
35525 ranu 142
	public String uploadContent(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
143
			throws Exception {
144
		List<ContentPojo> contentPojos = readFile(file);
35529 ranu 145
		if (contentPojos.size() < 1) {
146
			throw new RuntimeException("please check your file first ...may be content are wrong");
147
		}
35525 ranu 148
		for (ContentPojo contentPojo : contentPojos) {
149
			mongoClient.persistEntity(contentPojo);
150
		}
151
		//List<SuperCatalog> superCatalog = superCatalogRepository.selectAll();
152
 
153
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
154
		return "response";
25380 amit.gupta 155
	}
156
 
32952 amit.gupta 157
	@Autowired
158
	ItemLoaderService itemLoaderService;
159
	@PostMapping(value = "/catalog/upload")
160
	public String uploadCatalog(HttpServletRequest request, @RequestPart("file") MultipartFile file, Model model)
161
			throws Exception {
162
		itemLoaderService.parse(file);
163
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
164
		return "response";
165
	}
166
 
37216 amit 167
	@Autowired
168
	CategorySpecDerivationService categorySpecDerivationService;
169
 
170
	// one-time backfill trigger; safe to re-run (skips docs that already have specs)
171
	@PostMapping(value = "/content/specs/derive")
37217 amit 172
	public String deriveCategorySpecs(@RequestParam("categoryId") int categoryId, Model model) throws Exception {
37216 amit 173
		int updated = categorySpecDerivationService.deriveForCategory(categoryId);
174
		model.addAttribute("response1", mvcResponseSender.createResponseString(true) + " updated=" + updated);
175
		return "response";
176
	}
177
 
25380 amit.gupta 178
	@PostMapping(value = "/content/media/upload")
179
	public String uploadMediaContent(HttpServletRequest request, @RequestBody EntityMediaPojo entityMediaPojo,
180
			Model model) throws Exception {
181
		ContentPojo contentPojo = mongoClient.getEntityById(entityMediaPojo.getEntityId());
182
		Map<String, InputStream> fileStreamsMap = getStreamFileMap(contentPojo, entityMediaPojo);
25400 amit.gupta 183
		LOGGER.info("fileStreamsMap {}, " + fileStreamsMap.keySet());
29900 amit.gupta 184
		uploadContentFiles(fileStreamsMap, entityMediaPojo.getEntityId());
25380 amit.gupta 185
		mongoClient.persistEntity(contentPojo);
31238 amit.gupta 186
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
25380 amit.gupta 187
		return "response";
188
	}
189
 
35346 ranu 190
	@PostMapping(value = "/content/video/upload")
191
	public String uploadVideoUrls(HttpServletRequest request,
192
								  @RequestPart("file") MultipartFile file,
193
								  Model model) throws Exception {
194
 
195
		List<VideoUrlPojo> videoRows = readVideoFile(file);
196
 
197
		LOGGER.info("Received {} video rows", videoRows.size());
198
 
199
		// group by catalogId
200
		Map<Integer, List<VideoUrlPojo>> videoCatalogMap =
201
				videoRows.stream().collect(Collectors.groupingBy(VideoUrlPojo::getCatalogId));
202
 
35348 ranu 203
		LOGGER.info("videoCatalogMap {}", videoCatalogMap);
204
 
35346 ranu 205
		for (Map.Entry<Integer, List<VideoUrlPojo>> entry : videoCatalogMap.entrySet()) {
206
 
207
			int catalogId = entry.getKey();
35348 ranu 208
 
209
			LOGGER.info("catalogId {}", catalogId);
210
 
35346 ranu 211
			List<VideoUrlPojo> rowsForCatalog = entry.getValue();
212
 
213
			ContentPojo content = mongoClient.getEntityById(catalogId);
214
 
215
			if (content == null) {
216
				LOGGER.warn("No content found for catalogId {}", catalogId);
217
				continue;
218
			}
219
 
220
			updateVideoUrls(content, rowsForCatalog);
221
 
222
			mongoClient.persistEntity(content);
223
 
224
			LOGGER.info("Updated video URLs for catalogId {}", catalogId);
225
		}
226
 
227
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
228
		return "response";
229
	}
230
 
231
 
232
	private void updateVideoUrls(ContentPojo content, List<VideoUrlPojo> rows) {
233
 
234
		if (content.getVideoUrls() == null) {
235
			content.setVideoUrls(new ArrayList<>());
236
		}
237
 
238
		List<VideoUrlsContentPojo> existing = content.getVideoUrls();
239
 
240
		for (VideoUrlPojo row : rows) {
241
			VideoUrlsContentPojo newUrl = new VideoUrlsContentPojo(row.getUrl());
242
 
243
			// add only if not duplicate
244
			if (!existing.contains(newUrl)) {
245
				existing.add(newUrl);
246
			}
247
		}
248
 
249
		content.setVideoUrls(existing);
250
 
251
		LOGGER.info("Final video list = {}", existing);
252
	}
253
 
254
 
255
 
256
 
28264 tejbeer 257
	@PostMapping(value = "/image/media/upload")
258
	public String uploadImageMediaContent(HttpServletRequest request, @RequestBody MediaPojo mediaPojo, Model model)
259
			throws Exception {
260
 
261
		LOGGER.info("mediaPojo" + mediaPojo);
262
		Map<String, InputStream> fileStreamsMap = new HashMap<>();
263
		String extension;
264
		String base64String = mediaPojo.getImageData();
265
		String[] strings = base64String.split(",");
266
		switch (strings[0]) {// check image's extension
267
		case "data:image/jpeg;base64":
268
			extension = "jpeg";
269
			break;
270
		case "data:image/png;base64":
271
			extension = "png";
272
			break;
32304 amit.gupta 273
			case "data:image/webp;base64":
32305 amit.gupta 274
				extension = "webp";
32304 amit.gupta 275
				break;
28264 tejbeer 276
		default:// should write cases for more images types
32304 amit.gupta 277
			extension = "jpg";
28264 tejbeer 278
			break;
279
		}
280
		LOGGER.info("After switch statement = {}", extension);
281
		// convert base64 string to binary data
282
		byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
283
		Timestamp tm = new Timestamp(System.currentTimeMillis());
28320 tejbeer 284
		String urlTitle = mediaPojo.getTitle().toLowerCase();
285
		String fileName = urlTitle.replace(' ', '-') + tm.getTime() + "." + extension;
28264 tejbeer 286
		LOGGER.info("After switch statement Filename = {}", fileName);
287
		mediaPojo.setImageData(null);
288
		mediaPojo.setUrl(IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName);
289
		fileStreamsMap.put(fileName, new ByteArrayInputStream(data));
290
		LOGGER.info("fileStreamsMap" + fileStreamsMap);
291
 
292
		uploadFile(fileStreamsMap);
293
 
294
		DocumentUrl du = new DocumentUrl();
295
		du.setTitle(mediaPojo.getTitle());
296
		du.setUrl(mediaPojo.getUrl());
297
		du.setCreatedTimestamp(LocalDateTime.now());
298
		documentUrlRepository.persist(du);
299
 
300
		model.addAttribute("documents", du);
301
		return "image-url";
302
	}
303
 
304
	private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
305
			throws SftpException, FileNotFoundException {
306
 
307
		channelSftp.cd(destinationPath);
308
		String folderName = "image" + LocalDate.now();
309
 
310
		channelSftp.cd(destinationPath);
311
		SftpATTRS attrs = null;
312
 
313
		// check if the directory is already existing
314
		try {
315
			attrs = channelSftp.stat(folderName);
316
		} catch (Exception e) {
317
			System.out.println(destinationPath + "/" + "image" + LocalDate.now() + " not found");
318
		}
319
 
320
		// else create a directory
321
		if (attrs == null) {
322
			channelSftp.mkdir(folderName);
323
			channelSftp.chmod(0755, ".");
324
		}
325
		channelSftp.cd(folderName);
326
 
327
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
328
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
329
		}
330
 
331
	}
332
 
333
	@GetMapping(value = "/search/image/media")
334
	public String getImage(HttpServletRequest request, Model model, @RequestParam String title) throws Exception {
335
		List<DocumentUrl> documents = documentUrlRepository.selectBySearch(title);
336
 
337
		model.addAttribute("documents", documents);
338
		return "image-url";
339
 
340
	}
341
 
25380 amit.gupta 342
	@GetMapping(value = "/content/media")
343
	public String getMediaContent(HttpServletRequest request, Model model, @RequestParam int entityId)
344
			throws Exception {
345
		ContentPojo contentPojo = mongoClient.getEntityById(entityId);
25409 amit.gupta 346
		if (contentPojo == null) {
25380 amit.gupta 347
			throw new Exception("Please add content first");
348
		}
349
		EntityMediaPojo empojo = getEntityMediaPojo(contentPojo);
31238 amit.gupta 350
		model.addAttribute("response1", mvcResponseSender.createResponseString(empojo));
25380 amit.gupta 351
		return "response";
352
	}
28264 tejbeer 353
 
27185 amit.gupta 354
	@GetMapping(value = "/catalog-item")
28264 tejbeer 355
	public String catalogItem(HttpServletRequest request, Model model) throws Exception {
27185 amit.gupta 356
		return "catalog-item";
357
	}
25380 amit.gupta 358
 
359
	private EntityMediaPojo getEntityMediaPojo(ContentPojo contentPojo) {
360
		EntityMediaPojo ep = new EntityMediaPojo();
361
		int defaultIndex = 0;
25409 amit.gupta 362
		if (contentPojo.getImages() == null) {
25380 amit.gupta 363
			ep.setMediaPojos(new ArrayList<>());
364
		} else {
365
			ep.setMediaPojos(contentPojo.getImages());
366
			for (MediaPojo mediaPojo : contentPojo.getImages()) {
25409 amit.gupta 367
				if (mediaPojo.getUrl() == null)
368
					continue;
369
 
25380 amit.gupta 370
				if (!mediaPojo.getUrl().equals(contentPojo.getDefaultImageUrl())) {
371
					defaultIndex++;
372
				}
373
			}
374
		}
375
		ep.setDefaultImageIndex(defaultIndex);
376
		return ep;
377
	}
378
 
37184 ranu 379
	/**
380
	 * Band-aid for URL '+' decode issue: when the front-end sends `brand=Ai+` the servlet
381
	 * decodes the plus as a space and we receive "Ai " with a trailing space, missing the
382
	 * real "Ai+" brand. Restore trailing whitespace back to "+" so lookups match.
383
	 * Front-end should URL-encode with %2B (encodeURIComponent) — this is a temporary
384
	 * safety net until the mobile team ships that fix.
385
	 */
386
	private List<String> normalizeBrandNames(List<String> brands) {
387
		if (brands == null || brands.isEmpty()) return brands;
388
		return brands.stream()
389
				.map(b -> (b != null && b.endsWith(" ")) ? b.replaceAll("\\s+$", "") + "+" : b)
390
				.collect(Collectors.toList());
391
	}
392
 
25380 amit.gupta 393
	@GetMapping(value = "/entity")
28264 tejbeer 394
	public String searchEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
31330 tejbeer 395
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
37620 amit 396
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "false") boolean activeOnly,
31330 tejbeer 397
			Model model) throws Exception {
37184 ranu 398
		brands = normalizeBrandNames(brands);
31330 tejbeer 399
		model.addAttribute("response1", solrService.getContent(query, categoryId > 0 ? Arrays.asList(categoryId) : null,
37620 amit 400
				brands, limit, activeOnly));
25380 amit.gupta 401
		return "response";
402
	}
403
 
31330 tejbeer 404
	@GetMapping(value = "/focusedEntity")
405
	public String focusedEntity(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
406
			@RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
407
			@RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
408
			Model model) throws Exception {
409
 
37184 ranu 410
		brands = normalizeBrandNames(brands);
31330 tejbeer 411
		List<Integer> catalogIds = focusedModelRepository.selectAll().stream().map(x -> x.getCatalogId())
412
				.collect(Collectors.toList());
413
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
414
				limit, activeOnly);
415
 
416
		Iterator<Object> jsonIterator = docA.iterator();
417
		while (jsonIterator.hasNext()) {
418
			JSONObject i = (JSONObject) jsonIterator.next();
419
 
420
			if (!catalogIds.contains(i.get("catalogId_i"))) {
421
				jsonIterator.remove();
422
			}
423
 
424
		}
425
 
426
		model.addAttribute("response1", docA.toString());
427
 
428
		return "response";
429
	}
430
 
35487 ranu 431
	@GetMapping(value = "/statusWiseCatalogs")
432
	public String statusWiseCatalogs(HttpServletRequest request, @RequestParam(defaultValue = "null") String query,
433
									 @RequestParam(defaultValue = "0") int categoryId, @RequestParam(defaultValue = "") List<String> brands,
434
									 @RequestParam(defaultValue = "30") int limit, @RequestParam(defaultValue = "true") boolean activeOnly,
435
									 Model model) throws Exception {
436
 
37184 ranu 437
		brands = normalizeBrandNames(brands);
35487 ranu 438
		List<CatalogMovingEnum> catalogMovingEnums = Arrays.asList(CatalogMovingEnum.HID, CatalogMovingEnum.FASTMOVING, CatalogMovingEnum.RUNNING);
439
 
440
		List<Integer> catalogIds = catalogRepository.selectAllStatusAndBrandWise(brands, catalogMovingEnums);
441
 
442
		JSONArray docA = solrService.getContentDocs(query, categoryId > 0 ? Arrays.asList(categoryId) : null, brands,
443
				limit, activeOnly);
444
 
36404 amit 445
		Map<Integer, MonitorType> monitorTypeByCatalogId = catalogMonitorTypeRepository.selectAllAsMap();
446
 
35487 ranu 447
		Iterator<Object> jsonIterator = docA.iterator();
448
		while (jsonIterator.hasNext()) {
449
			JSONObject i = (JSONObject) jsonIterator.next();
450
 
36404 amit 451
			Object cidObj = i.get("catalogId_i");
452
			if (!catalogIds.contains(cidObj)) {
35487 ranu 453
				jsonIterator.remove();
36404 amit 454
				continue;
35487 ranu 455
			}
456
 
36404 amit 457
			if (cidObj instanceof Number) {
458
				MonitorType mt = monitorTypeByCatalogId.get(((Number) cidObj).intValue());
459
				if (mt != null) i.put("monitor_type", mt.dbValue());
460
			}
35487 ranu 461
		}
462
 
463
		model.addAttribute("response1", docA.toString());
464
 
465
		return "response";
466
	}
467
 
25380 amit.gupta 468
	@GetMapping(value = "/content/index")
469
	public String index(HttpServletRequest request, Model model) throws Exception {
33973 tejus.loha 470
 
25380 amit.gupta 471
		return "content";
472
	}
473
 
474
	private List<ContentPojo> readFile(MultipartFile file) throws Exception {
475
		CSVParser parser = new CSVParser(new InputStreamReader(file.getInputStream()), CSVFormat.DEFAULT);
476
		List<CSVRecord> records = parser.getRecords();
477
		if (records.size() < 2) {
478
			parser.close();
479
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records Found");
480
		}
37214 amit 481
		// header decides the layout: SpecValue columns present at 8-12 or not
482
		CSVRecord header = records.get(0);
483
		boolean specLayout = header.size() > SpecValue1 && header.get(SpecValue1) != null
484
				&& header.get(SpecValue1).trim().toUpperCase().startsWith("SPECVALUE");
25380 amit.gupta 485
		// Remove header
486
		records.remove(0);
487
		List<ContentPojo> returnList = new ArrayList<ContentPojo>();
488
		for (CSVRecord record : records) {
25430 amit.gupta 489
			ContentPojo cp = null;
490
			Long entityId = Long.parseLong(record.get(Entity_Id));
25380 amit.gupta 491
			try {
25430 amit.gupta 492
				cp = mongoClient.getEntityById(entityId);
493
			} catch (Exception e) {
494
			}
495
			try {
496
				if (cp == null) {
497
					cp = new ContentPojo(entityId);
498
				}
25380 amit.gupta 499
				cp.setWarranty(record.get(Warranty));
500
				cp.setKeySpecs(Arrays
501
						.asList(record.get(KeySpec1), record.get(KeySpec2), record.get(KeySpec3), record.get(KeySpec4))
25429 amit.gupta 502
						.stream().filter(x -> x != null && !x.equals("")).collect(Collectors.toList()));
25380 amit.gupta 503
				cp.setPackageContents(Arrays.asList(record.get(Package_Contents).split(",")));
37214 amit 504
				cp.setDetailedSpecs(getDetailedSpecs(record,
505
						specLayout ? DetailedSpecsSpecLayoutStart : DetailedSpecsLegacyStart));
37208 amit 506
				if (cp.getCategoryId() == null) {
507
					Catalog catalog = catalogRepository.selectCatalogById(Math.toIntExact(entityId));
508
					if (catalog != null) {
509
						cp.setCategoryId(catalog.getCategoryId());
510
					}
511
				}
37214 amit 512
				if (specLayout) {
513
					List<String> specValues = new ArrayList<>();
514
					for (int col = SpecValue1; col < SpecValue1 + SPEC_VALUE_COUNT; col++) {
515
						specValues.add(record.size() > col ? record.get(col) : "");
516
					}
517
					boolean anyValue = specValues.stream().anyMatch(v -> v != null && !v.trim().isEmpty());
518
					if (anyValue) {
519
						if (cp.getCategoryId() == null) {
520
							throw new ProfitMandiBusinessException("CatalogId", String.valueOf(entityId),
521
									"Spec values supplied but catalog/category unknown");
522
						}
523
						cp.setCategorySpecs(CategorySpecUtil.pairValues(
524
								categorySpecDefinitionRepository.selectActiveByCategoryId(cp.getCategoryId()),
525
								specValues));
526
					}
527
					// all-blank spec columns: leave existing categorySpecs untouched
528
				}
25380 amit.gupta 529
				returnList.add(cp);
37214 amit 530
			} catch (ProfitMandiBusinessException e) {
531
				parser.close();
532
				throw new ProfitMandiBusinessException(e.getRejectedType(), e.getRejectedValue(),
533
						e.getCode() + " at row " + record.getRecordNumber());
25380 amit.gupta 534
			} catch (Exception e) {
535
				continue;
536
			}
537
		}
538
		parser.close();
539
		return returnList;
540
	}
541
 
35346 ranu 542
 
543
	private List<VideoUrlPojo> readVideoFile(MultipartFile file) throws Exception {
544
 
545
		CSVParser parser = new CSVParser(
546
				new InputStreamReader(file.getInputStream()),
547
				CSVFormat.DEFAULT
548
		);
549
 
550
		List<CSVRecord> records = parser.getRecords();
551
 
552
		if (records.size() < 2) {
553
			parser.close();
554
			throw new ProfitMandiBusinessException("Uploaded File", "", "No records found");
555
		}
556
 
557
		// Remove header
558
		records.remove(0);
559
 
560
		List<VideoUrlPojo> returnList = new ArrayList<>();
561
 
562
		for (CSVRecord record : records) {
563
 
564
			try {
565
				// Must match CSV column order
35348 ranu 566
				Long catalogId = Long.parseLong(record.get(1));
567
				String url = record.get(2);
35346 ranu 568
 
569
				VideoUrlPojo row = new VideoUrlPojo();
570
				row.setCatalogId(Math.toIntExact(catalogId));
571
				row.setUrl(url);
572
 
573
				returnList.add(row);
574
 
575
			} catch (Exception e) {
576
				// skip bad rows, same as your style
577
				continue;
578
			}
579
		}
580
 
581
		parser.close();
582
		return returnList;
583
	}
584
 
585
 
37214 amit 586
	private List<SpecificationGroup> getDetailedSpecs(CSVRecord record, int startIndex) throws Exception {
25380 amit.gupta 587
		List<SpecificationGroup> specificationGroups = new ArrayList<>();
37214 amit 588
		int currentIndex = startIndex;
25380 amit.gupta 589
		while (StringUtils.isNotEmpty(record.get(currentIndex))) {
590
			int start = currentIndex;
591
			List<Specification> specifications = new ArrayList<>();
592
			int begin = 0;
593
			while (begin < 5) {
594
				int specKeyIndex = (begin * 2) + 1;
595
				int specValueIndex = (begin * 2) + 2;
596
 
597
				if (StringUtils.isNotEmpty(record.get(currentIndex + specKeyIndex))
598
						&& StringUtils.isNotEmpty(record.get(currentIndex + specValueIndex))) {
599
					Specification specification = new Specification(record.get(currentIndex + specKeyIndex),
600
							Arrays.asList(record.get(currentIndex + specValueIndex)));
601
					specifications.add(specification);
602
				}
603
				begin++;
604
			}
605
			SpecificationGroup specificationGroup = new SpecificationGroup(record.get(start), specifications);
606
			specificationGroups.add(specificationGroup);
25392 amit.gupta 607
			currentIndex += 11;
25380 amit.gupta 608
		}
609
 
610
		return specificationGroups;
611
	}
612
 
613
	private ChannelSftp setupJsch() throws JSchException {
614
		JSch jsch = new JSch();
33463 amit.gupta 615
		Session jschSession = jsch.getSession("root", "172.105.58.16");
31330 tejbeer 616
		// Session jschSession = jsch.getSession("root", "173.255.254.24");
617
		LOGGER.info("getClass().getResource(\"id_rsa\") {}",
618
				getClass().getClassLoader().getResource("id_rsa").getPath());
29881 amit.gupta 619
		jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
31330 tejbeer 620
		// jschSession.setPassword("spic@2015static0");
25396 amit.gupta 621
		jschSession.setConfig("StrictHostKeyChecking", "no");
25380 amit.gupta 622
		jschSession.connect();
623
		return (ChannelSftp) jschSession.openChannel("sftp");
624
	}
625
 
29900 amit.gupta 626
	private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
25380 amit.gupta 627
		ChannelSftp channelSftp = setupJsch();
628
		channelSftp.connect();
29900 amit.gupta 629
		this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
630
		channelSftp.exit();
631
	}
632
 
633
	private void uploadContentFiles(Map<String, InputStream> fileStreamsMap, int entityId) throws Exception {
634
		ChannelSftp channelSftp = setupJsch();
635
		channelSftp.connect();
25380 amit.gupta 636
		this.folderUpload(channelSftp, fileStreamsMap, REMOTE_DIR, entityId + "");
637
		channelSftp.exit();
638
	}
639
 
640
	private void recursiveFolderUpload(ChannelSftp channelSftp, String sourcePath, String destinationPath)
641
			throws SftpException, FileNotFoundException {
642
 
643
		File sourceFile = new File(sourcePath);
644
		if (sourceFile.isFile()) {
645
 
646
			// copy if it is a file
647
			channelSftp.cd(destinationPath);
648
			if (!sourceFile.getName().startsWith("."))
649
				channelSftp.put(new FileInputStream(sourceFile), sourceFile.getName(), ChannelSftp.OVERWRITE);
650
 
651
		} else {
652
 
653
			System.out.println("inside else " + sourceFile.getName());
654
			File[] files = sourceFile.listFiles();
655
 
656
			if (files != null && !sourceFile.getName().startsWith(".")) {
657
 
658
				channelSftp.cd(destinationPath);
659
				SftpATTRS attrs = null;
660
 
661
				// check if the directory is already existing
662
				try {
663
					attrs = channelSftp.stat(destinationPath + "/" + sourceFile.getName());
664
				} catch (Exception e) {
665
					System.out.println(destinationPath + "/" + sourceFile.getName() + " not found");
666
				}
667
 
668
				// else create a directory
669
				if (attrs != null) {
670
					System.out.println("Directory exists IsDir=" + attrs.isDir());
671
				} else {
672
					System.out.println("Creating dir " + sourceFile.getName());
673
					channelSftp.mkdir(sourceFile.getName());
674
				}
675
 
676
				for (File f : files) {
677
					recursiveFolderUpload(channelSftp, f.getAbsolutePath(),
678
							destinationPath + "/" + sourceFile.getName());
679
				}
680
 
681
			}
682
		}
683
 
684
	}
685
 
686
	private void folderUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath,
687
			String folderName) throws SftpException, FileNotFoundException {
688
 
689
		channelSftp.cd(destinationPath);
690
		SftpATTRS attrs = null;
691
 
692
		// check if the directory is already existing
693
		try {
694
			attrs = channelSftp.stat(folderName);
695
		} catch (Exception e) {
696
			System.out.println(destinationPath + "/" + folderName + " not found");
697
		}
698
 
699
		// else create a directory
25413 amit.gupta 700
		if (attrs == null) {
701
			channelSftp.mkdir(folderName);
702
			channelSftp.chmod(0755, ".");
25380 amit.gupta 703
		}
704
		channelSftp.cd(folderName);
25413 amit.gupta 705
		channelSftp.rm("*");
25380 amit.gupta 706
 
707
		for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
708
			channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
709
		}
710
 
711
	}
712
 
713
	private Map<String, InputStream> getStreamFileMap(ContentPojo contentPojo, EntityMediaPojo entityMediaPojo) {
714
		Map<String, InputStream> map = new HashMap<>();
25401 amit.gupta 715
		LOGGER.info("entityMediaPojo.getMediaPojos() -[{}]", entityMediaPojo.getMediaPojos());
25404 amit.gupta 716
		for (int i = 0; i < entityMediaPojo.getMediaPojos().size(); i++) {
25380 amit.gupta 717
			MediaPojo mediaPojo = entityMediaPojo.getMediaPojos().get(i);
718
			String extension;
719
			String base64String = mediaPojo.getImageData();
720
			String[] strings = base64String.split(",");
721
			switch (strings[0]) {// check image's extension
722
			case "data:image/jpeg;base64":
723
				extension = "jpeg";
724
				break;
725
			case "data:image/png;base64":
726
				extension = "png";
727
				break;
728
			default:// should write cases for more images types
729
				extension = "jpg";
730
				break;
731
			}
25402 amit.gupta 732
			LOGGER.info("After switch statement = {}", extension);
25380 amit.gupta 733
			// convert base64 string to binary data
734
			byte[] data = DatatypeConverter.parseBase64Binary(strings[1]);
735
			String fileName = getFileName(entityMediaPojo.getEntityId(), mediaPojo.getTitle(), extension);
25402 amit.gupta 736
			LOGGER.info("After switch statement Filename = {}", fileName);
25380 amit.gupta 737
			mediaPojo.setImageData(null);
25430 amit.gupta 738
			String staticServerUrl = String.format(STATIC_SERVER_URL, entityMediaPojo.getEntityId() % 3);
25414 amit.gupta 739
			mediaPojo.setUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + fileName);
25380 amit.gupta 740
			map.put(fileName, new ByteArrayInputStream(data));
741
			if (i == entityMediaPojo.getDefaultImageIndex()) {
742
				String defaultFileName = getFileName(entityMediaPojo.getEntityId(), DEFAULT, extension);
743
				map.put(defaultFileName, new ByteArrayInputStream(data));
25414 amit.gupta 744
				contentPojo.setDefaultImageUrl(staticServerUrl + entityMediaPojo.getEntityId() + "/" + defaultFileName);
25380 amit.gupta 745
			}
746
		}
747
		contentPojo.setImages(entityMediaPojo.getMediaPojos());
748
 
749
		return map;
750
	}
751
 
25409 amit.gupta 752
	private String getMediaPrefix(String productName) {
753
		String mediaPrefix = productName.toLowerCase().replace(' ', '-');
754
		mediaPrefix = mediaPrefix.replaceAll("/", "-");
755
		mediaPrefix = mediaPrefix.replaceAll("-+", "-");
756
		return mediaPrefix;
757
	}
758
 
28264 tejbeer 759
	@GetMapping(value = "/urlGeneration")
760
	public String urlGeneration(HttpServletRequest request, Model model) throws Exception {
761
		return "url-generation";
762
	}
33443 ranu 763
	@Autowired
764
	UserRepository userRepository;
765
	@Autowired
766
	private CookiesProcessor cookiesProcessor;
767
 
768
	@GetMapping(value = "/printResources")
769
	public String printResources(HttpServletRequest request, Model model) throws Exception {
770
		List<Region> regionList = regionRepository.selectAll();
771
		model.addAttribute("regionList", regionList);
772
		return "print-resource";
773
	}
774
 
775
	@RequestMapping(value = "/postPrintResource", method = RequestMethod.POST)
776
	public String postPrintResource(HttpServletRequest request, @RequestBody PrintResourceModel printResourceModel,
777
									Model model) throws Exception {
778
		LOGGER.info("printResourceModel {}", printResourceModel);
779
		PrintResource printResource = new PrintResource();
780
		printResource.setTitle(printResourceModel.getTitle());
781
		printResource.setStartDate(printResourceModel.getStartDate().atStartOfDay());
782
		if (printResourceModel.getEndDate() != null) {
783
			printResource.setEndDate(printResourceModel.getEndDate().atStartOfDay());
784
		} else {
785
			printResource.setEndDate(null);
786
		}
787
 
788
		printResource.setCreateTimestamp(LocalDateTime.now());
789
		printResource.setImgUrl(printResourceModel.getImgUrl());
33501 ranu 790
		printResource.setThumbnailUrl(printResourceModel.getThumbnailUrl());
33443 ranu 791
		printResourceRepository.persist(printResource);
792
 
793
		PrintResourceRegion printResourceRegion = new PrintResourceRegion();
794
		int regionId = Integer.parseInt(printResourceModel.getRegion());
795
		printResourceRegion.setRegionId(regionId);
796
		printResourceRegion.setResourceId(printResource.getId());
797
		printResourceRegionRepository.persist(printResourceRegion);
798
 
799
 
800
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
801
 
802
		return "response";
803
	}
804
 
805
	@RequestMapping(value = "/changeEndDate", method = RequestMethod.POST)
806
	public String changeEndDate(HttpServletRequest request, @RequestParam LocalDate date, @RequestParam int resourceId,
807
								Model model) throws Exception {
808
 
809
		PrintResource printResource = printResourceRepository.selectById(resourceId);
810
		printResource.setEndDate(date.atStartOfDay());
811
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
812
		return "response";
813
	}
814
 
815
	@GetMapping(value = "/partnerPrintResources")
816
	public String partnerPrintResources(HttpServletRequest request, Model model) throws Exception {
817
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
818
		int fofoId = loginDetails.getFofoId();
819
		User user = userRepository.selectById(fofoId);
820
		List<PartnerRegion> partnerRegion = partnerRegionRepository.selectByfofoId(user.getId());
821
		LocalDateTime currentDate = LocalDateTime.now();
822
		List<PrintResource> printResources = printResourceRepository.selectPrintResourcesByFofoRegion(partnerRegion.get(0).getRegionId(), currentDate);
823
		LOGGER.info("printresourcesList {}", printResources);
824
		model.addAttribute("printResources", printResources);
825
		return "partner_print_resource";
826
	}
827
 
828
	@GetMapping(value = "/allPrintResources")
829
	public String allPrintResources(HttpServletRequest request, Model model) throws Exception {
830
		LocalDateTime currentDate = LocalDateTime.now();
831
		List<PrintResource> printResources = printResourceRepository.selectAllPrintResources(currentDate);
832
		model.addAttribute("printResources", printResources);
833
		return "all-print-resource";
834
	}
835
 
35346 ranu 836
	@GetMapping("/content/video/check/{catalogId}")
837
	public ResponseEntity<?> checkVideo(@PathVariable int catalogId) throws Exception {
838
		ContentPojo cp = mongoClient.getEntityById(catalogId);
839
 
840
		LOGGER.info("Video Url {}", cp.getVideoUrls());
841
		return ResponseEntity.ok(cp.getVideoUrls());
842
	}
843
 
844
 
35549 ranu 845
	@GetMapping(value = "/bulletin")
846
	public String bulletin(HttpServletRequest request, Model model) throws Exception {
847
		List<Region> regionList = regionRepository.selectAll();
848
		model.addAttribute("regionList", regionList);
849
		return "post-bulletin";
850
	}
851
 
852
 
853
	@RequestMapping(value = "/bulletinPost", method = RequestMethod.POST)
854
	public String bulletinPost(HttpServletRequest request, @RequestBody BulletinPostModel bulletinPostModel,
855
							   Model model) throws Exception {
35583 ranu 856
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
857
		String email = loginDetails.getEmailId();
858
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
35549 ranu 859
		LOGGER.info("bulletinPostModel {}", bulletinPostModel);
860
		Bulletin bulletin = new Bulletin();
861
		bulletin.setRegionId(bulletinPostModel.getRegionId());
862
		bulletin.setDescription(bulletinPostModel.getDescription());
863
		bulletin.setDocumentIds(bulletinPostModel.getDocumentIds());
864
		bulletin.setCreatedAt(LocalDateTime.now());
35583 ranu 865
		bulletin.setCreatedBy(authUser.getFullName());
35549 ranu 866
		bulletinRepository.persist(bulletin);
867
 
868
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
869
 
870
		return "response";
871
	}
872
 
873
 
874
 
875
 
25380 amit.gupta 876
}