Subversion Repositories SmartDukaan

Rev

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