Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
21339 kshitij.so 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.eclipsesource.json.Json;
4
import com.eclipsesource.json.JsonArray;
5
import com.eclipsesource.json.JsonObject;
6
import com.eclipsesource.json.JsonValue;
7
import com.google.gson.Gson;
21356 kshitij.so 8
import com.google.gson.reflect.TypeToken;
25010 amit.gupta 9
import com.mongodb.BasicDBObject;
24163 amit.gupta 10
import com.mongodb.DBObject;
21643 ashik.ali 11
import com.spice.profitmandi.common.enumuration.SchemeType;
21339 kshitij.so 12
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
13
import com.spice.profitmandi.common.model.ProfitMandiConstants;
22289 amit.gupta 14
import com.spice.profitmandi.common.model.UserInfo;
27030 amit.gupta 15
import com.spice.profitmandi.common.solr.SolrService;
21643 ashik.ali 16
import com.spice.profitmandi.common.web.client.RestClient;
22319 amit.gupta 17
import com.spice.profitmandi.common.web.util.ResponseSender;
30686 amit.gupta 18
import com.spice.profitmandi.dao.entity.catalog.*;
31507 tejbeer 19
import com.spice.profitmandi.dao.entity.dtr.WebListing;
30595 tejbeer 20
import com.spice.profitmandi.dao.entity.dtr.WebOffer;
31612 tejbeer 21
import com.spice.profitmandi.dao.entity.dtr.WebProductListing;
31625 tejbeer 22
import com.spice.profitmandi.dao.entity.fofo.CatalogFavourite;
27090 amit.gupta 23
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
26847 tejbeer 24
import com.spice.profitmandi.dao.entity.fofo.SuggestedPo;
26846 tejbeer 25
import com.spice.profitmandi.dao.entity.fofo.SuggestedPoDetail;
30669 amit.gupta 26
import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;
27032 amit.gupta 27
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
31572 tejbeer 28
import com.spice.profitmandi.dao.enumuration.dtr.WebListingSource;
31507 tejbeer 29
import com.spice.profitmandi.dao.enumuration.dtr.WebListingType;
31954 amit.gupta 30
import com.spice.profitmandi.dao.model.AmountModel;
30188 amit.gupta 31
import com.spice.profitmandi.dao.model.CreateOfferRequest;
22361 amit.gupta 32
import com.spice.profitmandi.dao.model.UserCart;
30686 amit.gupta 33
import com.spice.profitmandi.dao.repository.catalog.*;
27030 amit.gupta 34
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
22333 amit.gupta 35
import com.spice.profitmandi.dao.repository.dtr.Mongo;
22361 amit.gupta 36
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
31547 tejbeer 37
import com.spice.profitmandi.dao.repository.dtr.WebListingRepository;
30595 tejbeer 38
import com.spice.profitmandi.dao.repository.dtr.WebOfferRepository;
31547 tejbeer 39
import com.spice.profitmandi.dao.repository.dtr.WebProductListingRepository;
31625 tejbeer 40
import com.spice.profitmandi.dao.repository.fofo.CatalogFavouriteRepository;
26846 tejbeer 41
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoDetailRepository;
26847 tejbeer 42
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoRepository;
30669 amit.gupta 43
import com.spice.profitmandi.dao.repository.inventory.SaholicCISTableRepository;
23798 amit.gupta 44
import com.spice.profitmandi.service.authentication.RoleManager;
31507 tejbeer 45
import com.spice.profitmandi.service.catalog.BrandsService;
30686 amit.gupta 46
import com.spice.profitmandi.service.inventory.*;
30123 amit.gupta 47
import com.spice.profitmandi.service.pricecircular.PriceCircularItemModel;
31954 amit.gupta 48
import com.spice.profitmandi.service.pricecircular.PriceCircularItemModelNew;
30123 amit.gupta 49
import com.spice.profitmandi.service.pricecircular.PriceCircularModel;
50
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
22287 amit.gupta 51
import com.spice.profitmandi.service.pricing.PricingService;
26695 amit.gupta 52
import com.spice.profitmandi.service.scheme.SchemeService;
21356 kshitij.so 53
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 54
import com.spice.profitmandi.web.res.DealObjectResponse;
55
import com.spice.profitmandi.web.res.DealsResponse;
56
import io.swagger.annotations.ApiImplicitParam;
57
import io.swagger.annotations.ApiImplicitParams;
58
import io.swagger.annotations.ApiOperation;
30686 amit.gupta 59
import org.apache.commons.lang3.StringUtils;
60
import org.apache.http.conn.HttpHostConnectException;
61
import org.apache.logging.log4j.LogManager;
62
import org.apache.logging.log4j.Logger;
63
import org.json.JSONArray;
64
import org.json.JSONObject;
65
import org.springframework.beans.factory.annotation.Autowired;
66
import org.springframework.beans.factory.annotation.Value;
31954 amit.gupta 67
import org.springframework.cglib.core.Local;
30686 amit.gupta 68
import org.springframework.http.HttpStatus;
69
import org.springframework.http.MediaType;
70
import org.springframework.http.ResponseEntity;
71
import org.springframework.stereotype.Controller;
72
import org.springframework.transaction.annotation.Transactional;
73
import org.springframework.web.bind.annotation.PathVariable;
74
import org.springframework.web.bind.annotation.RequestMapping;
75
import org.springframework.web.bind.annotation.RequestMethod;
76
import org.springframework.web.bind.annotation.RequestParam;
21339 kshitij.so 77
 
30686 amit.gupta 78
import javax.servlet.http.HttpServletRequest;
31625 tejbeer 79
 
31954 amit.gupta 80
import java.time.LocalDate;
31625 tejbeer 81
import java.time.LocalDateTime;
30686 amit.gupta 82
import java.util.*;
83
import java.util.concurrent.atomic.AtomicInteger;
84
import java.util.stream.Collectors;
85
 
21339 kshitij.so 86
@Controller
22319 amit.gupta 87
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 88
public class DealsController {
89
 
23568 govind 90
	private static final Logger logger = LogManager.getLogger(DealsController.class);
31547 tejbeer 91
	private static final List<Integer> TAG_IDS = Arrays.asList(4);
21339 kshitij.so 92
 
93
	@Value("${python.api.host}")
94
	private String host;
23816 amit.gupta 95
 
26889 amit.gupta 96
	@Value("${new.solr.url}")
97
	private String solrUrl;
98
 
21339 kshitij.so 99
	@Value("${python.api.port}")
100
	private int port;
23816 amit.gupta 101
 
26889 amit.gupta 102
	@Autowired
103
	RestClient restClient;
27051 amit.gupta 104
 
27030 amit.gupta 105
	@Autowired
106
	SolrService solrService;
26889 amit.gupta 107
 
26924 amit.gupta 108
	@Autowired
109
	InventoryService inventoryService;
110
 
23816 amit.gupta 111
	// This is now unused as we are not supporting multiple companies.
23300 amit.gupta 112
	@Value("${gadgetCops.invoice.cc}")
23816 amit.gupta 113
	private String[] ccGadgetCopInvoiceTo;
22319 amit.gupta 114
 
115
	@Autowired
116
	private PricingService pricingService;
23816 amit.gupta 117
 
22273 amit.gupta 118
	@Autowired
25010 amit.gupta 119
	private CategoryRepository categoryRepository;
120
 
121
	@Autowired
26695 amit.gupta 122
	private SchemeService schemeService;
123
 
124
	@Autowired
26889 amit.gupta 125
	private SaholicInventoryService saholicInventoryService;
126
 
127
	@Autowired
22333 amit.gupta 128
	private Mongo mongoClient;
25879 amit.gupta 129
 
25875 amit.gupta 130
	@Autowired
131
	private ItemBucketService itemBucketService;
23816 amit.gupta 132
 
22333 amit.gupta 133
	@Autowired
22361 amit.gupta 134
	private UserAccountRepository userAccountRepository;
27051 amit.gupta 135
 
27030 amit.gupta 136
	@Autowired
137
	private FofoStoreRepository fofoStoreRepository;
23816 amit.gupta 138
 
22989 amit.gupta 139
	@Autowired
22931 ashik.ali 140
	private ResponseSender<?> responseSender;
23816 amit.gupta 141
 
22554 amit.gupta 142
	@Autowired
23814 amit.gupta 143
	private TagListingRepository tagListingRepository;
23816 amit.gupta 144
 
23814 amit.gupta 145
	@Autowired
23426 amit.gupta 146
	private ItemRepository itemRepository;
30123 amit.gupta 147
	@Autowired
148
	private PriceCircularService priceCircularService;
23816 amit.gupta 149
 
23786 amit.gupta 150
	@Autowired
23798 amit.gupta 151
	private RoleManager roleManagerService;
23816 amit.gupta 152
 
26846 tejbeer 153
	@Autowired
154
	private SuggestedPoDetailRepository monthlyPoDetailRepository;
155
 
26847 tejbeer 156
	@Autowired
157
	private SuggestedPoRepository suggestedPoRepository;
158
 
30595 tejbeer 159
	@Autowired
160
	private WebOfferRepository webOfferRepository;
161
 
30683 tejbeer 162
	@Autowired
163
	private ComboModelRepository comboModelRepository;
164
 
165
	@Autowired
166
	private ComboMappedModelRepository comboMappedModelRepository;
167
 
31507 tejbeer 168
	@Autowired
169
	private BrandsService brandsService;
31547 tejbeer 170
 
171
	@Autowired
172
	private WebListingRepository webListingRepository;
173
 
174
	@Autowired
175
	private WebProductListingRepository webProductListingRepository;
176
 
31625 tejbeer 177
	@Autowired
178
	private CatalogFavouriteRepository catalogFavouriteRepository;
179
 
22336 amit.gupta 180
	List<String> filterableParams = Arrays.asList("brand");
24949 amit.gupta 181
 
25876 amit.gupta 182
	@RequestMapping(value = "/fofo/buckets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25879 amit.gupta 183
	public ResponseEntity<?> getBuckets(HttpServletRequest request) throws ProfitMandiBusinessException {
25875 amit.gupta 184
		logger.info("Request " + request.getParameterMap());
185
		return responseSender.ok(itemBucketService.getBuckets(Optional.of(true)));
186
	}
25879 amit.gupta 187
 
188
	@RequestMapping(value = "/fofo/bucket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25880 amit.gupta 189
	public ResponseEntity<?> getBucketDetails(HttpServletRequest request, @RequestParam int id)
25879 amit.gupta 190
			throws ProfitMandiBusinessException {
25880 amit.gupta 191
		List<ItemQuantityPojo> iqPojo = itemBucketService.getBucketDetails(id);
25968 amit.gupta 192
		Map<Integer, Integer> itemIdsQtyMap = iqPojo.stream()
193
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
194
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream()
195
				.map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
25879 amit.gupta 196
		RestClient rc = new RestClient();
197
		Map<String, String> params = new HashMap<>();
198
		List<String> mandatoryQ = new ArrayList<>();
25968 amit.gupta 199
		mandatoryQ.add(
200
				String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
25959 amit.gupta 201
		params.put("start", "0");
202
		params.put("rows", "100");
25879 amit.gupta 203
		params.put("q", StringUtils.join(mandatoryQ, " "));
204
		params.put("fl", "*, [child parentFilter=id:catalog*]");
205
 
206
		params.put("wt", "json");
207
		String response = null;
208
		try {
26889 amit.gupta 209
			response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
25879 amit.gupta 210
		} catch (HttpHostConnectException e) {
211
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
212
		}
213
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
214
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
25968 amit.gupta 215
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
26051 amit.gupta 216
 
26589 amit.gupta 217
		Bucket bucket = itemBucketService.getBuckets(Optional.of(true)).stream().filter(x -> x.getId() == id)
218
				.collect(Collectors.toList()).get(0);
25882 amit.gupta 219
		bucket.setFofoCatalogResponses(dealResponse);
220
		return responseSender.ok(bucket);
25879 amit.gupta 221
	}
222
 
26846 tejbeer 223
	@RequestMapping(value = "/fofo/suggestedPo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
224
	public ResponseEntity<?> getSuggestedPo(HttpServletRequest request, @RequestParam int id)
225
			throws ProfitMandiBusinessException {
226
 
227
		List<SuggestedPoDetail> mpd = monthlyPoDetailRepository.selectByPoId(id);
228
		Map<Integer, Integer> itemIdsQtyMap = mpd.stream()
229
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
230
 
231
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream()
232
				.map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
233
		RestClient rc = new RestClient();
234
		Map<String, String> params = new HashMap<>();
235
		List<String> mandatoryQ = new ArrayList<>();
236
		mandatoryQ.add(
237
				String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
238
		params.put("start", "0");
239
		params.put("rows", "100");
240
		params.put("q", StringUtils.join(mandatoryQ, " "));
241
		params.put("fl", "*, [child parentFilter=id:catalog*]");
242
 
243
		params.put("wt", "json");
244
		String response = null;
245
		try {
26889 amit.gupta 246
			response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
26846 tejbeer 247
		} catch (HttpHostConnectException e) {
248
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
249
		}
250
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
251
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
252
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
253
 
254
		return responseSender.ok(dealResponse);
255
	}
256
 
26847 tejbeer 257
	@RequestMapping(value = "/suggestedPo/status", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26848 tejbeer 258
	@ApiImplicitParams({
31507 tejbeer 259
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
26848 tejbeer 260
	@ApiOperation(value = "")
26847 tejbeer 261
	public ResponseEntity<?> changeSuggestedPoStatus(HttpServletRequest request, @RequestParam int id)
262
			throws ProfitMandiBusinessException {
263
		SuggestedPo suggestedPo = suggestedPoRepository.selectById(id);
264
		suggestedPo.setStatus("closed");
265
 
266
		return responseSender.ok(true);
267
	}
268
 
31625 tejbeer 269
	@RequestMapping(value = "/fofo/fovourites", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
31629 tejbeer 270
	public ResponseEntity<?> getFavourites(HttpServletRequest request) throws Exception {
31625 tejbeer 271
 
31629 tejbeer 272
		int userId = (int) request.getAttribute("userId");
273
		UserCart uc = userAccountRepository.getUserCart(userId);
274
		int fofoId = uc.getUserId();
31670 tejbeer 275
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
31625 tejbeer 276
		Set<Integer> catalogIds = catalogFavouriteRepository.selectBypartnerId(fofoId).stream()
31628 tejbeer 277
				.map(x -> x.getCatalogId()).collect(Collectors.toSet());
31670 tejbeer 278
		if (!catalogIds.isEmpty()) {
31625 tejbeer 279
 
31670 tejbeer 280
			RestClient rc = new RestClient();
281
			Map<String, String> params = new HashMap<>();
282
			List<String> mandatoryQ = new ArrayList<>();
283
			mandatoryQ.add(String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}",
284
					StringUtils.join(catalogIds, " ")));
285
			params.put("start", "0");
286
			params.put("rows", "100");
287
			params.put("q", StringUtils.join(mandatoryQ, " "));
288
			params.put("fl", "*, [child parentFilter=id:catalog*]");
289
 
290
			params.put("wt", "json");
291
			String response = null;
292
			try {
293
				response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
294
			} catch (HttpHostConnectException e) {
295
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
296
			}
297
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
298
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
299
			dealResponse = getCatalogResponse(docs, false, fofoId);
31625 tejbeer 300
		}
301
		return responseSender.ok(dealResponse);
302
	}
303
 
304
	@RequestMapping(value = "/favourites/manage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
305
	@ApiImplicitParams({
306
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
307
	@ApiOperation(value = "")
308
	public ResponseEntity<?> mangeFavourites(HttpServletRequest request, @RequestParam int catalogId)
309
			throws ProfitMandiBusinessException {
310
 
311
		int userId = (int) request.getAttribute("userId");
312
		UserCart uc = userAccountRepository.getUserCart(userId);
313
		int fofoId = uc.getUserId();
314
 
315
		CatalogFavourite catalogFavourite = catalogFavouriteRepository.selectBypartnerAndCatalogId(fofoId, catalogId);
316
 
317
		if (catalogFavourite == null) {
318
			catalogFavourite = new CatalogFavourite();
31628 tejbeer 319
			catalogFavourite.setCatalogId(catalogId);
31625 tejbeer 320
			catalogFavourite.setFofoId(fofoId);
321
			catalogFavourite.setCreatedTimestamp(LocalDateTime.now());
322
			catalogFavouriteRepository.persist(catalogFavourite);
323
 
324
		}
325
 
326
		else {
327
			catalogFavouriteRepository.deleteByPartnerAndCatalogId(fofoId, catalogId);
328
		}
329
		return responseSender.ok(true);
330
	}
331
 
23816 amit.gupta 332
	private String getCommaSeparateTags(int userId) {
22361 amit.gupta 333
		UserCart uc = userAccountRepository.getUserCart(userId);
334
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
22287 amit.gupta 335
		List<String> strTagIds = new ArrayList<>();
336
		for (Integer tagId : tagIds) {
337
			strTagIds.add(String.valueOf(tagId));
22273 amit.gupta 338
		}
22287 amit.gupta 339
		return String.join(",", strTagIds);
22273 amit.gupta 340
	}
341
 
22319 amit.gupta 342
	@ApiImplicitParams({
31507 tejbeer 343
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22319 amit.gupta 344
	@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24091 tejbeer 345
	public ResponseEntity<?> getFofo(HttpServletRequest request,
31507 tejbeer 346
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
347
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
348
			@RequestParam(value = "sort", required = false) String sort,
349
			@RequestParam(value = "brand", required = false) String brand,
350
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
351
			@RequestParam(value = "q", required = false) String queryTerm,
31548 tejbeer 352
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal,
353
			@RequestParam(value = "endPoint", required = false) String endPoint) throws Throwable {
22328 amit.gupta 354
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
22319 amit.gupta 355
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
27090 amit.gupta 356
		FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
28262 amit.gupta 357
		sort = "w" + fs.getWarehouseId() + "_i desc";
31548 tejbeer 358
 
359
		logger.info("endPoint {}", endPoint);
31552 tejbeer 360
 
31554 tejbeer 361
		if (endPoint != null && !endPoint.trim().isEmpty()) {
31552 tejbeer 362
			WebListing webListing = webListingRepository.selectByUrl(endPoint);
31557 tejbeer 363
			dealResponse = this.getDealResponses(userInfo, webListing, offset, limit);
31552 tejbeer 364
 
365
		} else {
366
 
31548 tejbeer 367
			dealResponse = this.getCatalogResponse(
368
					solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, hotDeal),
369
					hotDeal, userInfo.getRetailerId());
370
		}
28101 amit.gupta 371
		logger.info("log me");
26889 amit.gupta 372
		return responseSender.ok(dealResponse);
373
	}
25015 amit.gupta 374
 
22319 amit.gupta 375
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 376
	@ApiImplicitParams({
31507 tejbeer 377
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 378
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 379
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
31507 tejbeer 380
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
381
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
382
			@RequestParam(value = "direction", required = false) String direction,
383
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
22319 amit.gupta 384
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 385
		String response = null;
22319 amit.gupta 386
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 387
 
22319 amit.gupta 388
		String uri = "/deals/" + userId;
23532 amit.gupta 389
		RestClient rc = new RestClient();
22272 amit.gupta 390
		Map<String, String> params = new HashMap<>();
391
		params.put("offset", offset);
392
		params.put("limit", limit);
393
		params.put("categoryId", categoryId);
394
		params.put("direction", direction);
395
		params.put("sort", sort);
396
		params.put("source", "online");
397
		params.put("filterData", filterData);
23816 amit.gupta 398
		/*
399
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
400
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
401
		 */
22272 amit.gupta 402
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 403
		try {
404
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
405
		} catch (HttpHostConnectException e) {
406
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
407
		}
22931 ashik.ali 408
 
22272 amit.gupta 409
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 410
		for (JsonValue j : result_json) {
23816 amit.gupta 411
			// logger.info("res " + j.asArray());
22272 amit.gupta 412
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 413
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 414
				innerObject.add(toDealObject(jsonObject.asObject()));
415
			}
22319 amit.gupta 416
			if (innerObject.size() > 0) {
22272 amit.gupta 417
				responseObject.add(innerObject);
418
			}
419
		}
23022 ashik.ali 420
		return responseSender.ok(responseObject);
22272 amit.gupta 421
	}
422
 
22319 amit.gupta 423
	private Object toDealObject(JsonObject jsonObject) {
424
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 425
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
426
		}
427
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
428
	}
22319 amit.gupta 429
 
430
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 431
	@ApiImplicitParams({
31507 tejbeer 432
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 433
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 434
	public ResponseEntity<?> getBrands(HttpServletRequest request,
31507 tejbeer 435
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 436
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 437
		String response = null;
22319 amit.gupta 438
		// TODO: move to properties
21356 kshitij.so 439
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 440
		RestClient rc = new RestClient();
21356 kshitij.so 441
		Map<String, String> params = new HashMap<>();
442
		params.put("category_id", category_id);
21358 kshitij.so 443
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 444
		try {
445
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
446
		} catch (HttpHostConnectException e) {
447
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
448
		}
23816 amit.gupta 449
 
22319 amit.gupta 450
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
451
		}.getType());
23022 ashik.ali 452
 
453
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 454
	}
22319 amit.gupta 455
 
456
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 457
	@ApiImplicitParams({
31507 tejbeer 458
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 459
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 460
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
461
			throws ProfitMandiBusinessException {
21445 kshitij.so 462
		String response = null;
22319 amit.gupta 463
		// TODO: move to properties
464
		String uri = "getDealById/" + id;
465
		System.out.println("Unit deal " + uri);
23532 amit.gupta 466
		RestClient rc = new RestClient();
21445 kshitij.so 467
		Map<String, String> params = new HashMap<>();
468
		DealsResponse dealsResponse = null;
23532 amit.gupta 469
		try {
470
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
471
		} catch (HttpHostConnectException e) {
472
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
473
		}
23816 amit.gupta 474
 
21445 kshitij.so 475
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 476
		if (!result_json.isEmpty()) {
21445 kshitij.so 477
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 478
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 479
			while (iter.hasNext()) {
22952 amit.gupta 480
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 481
				if (ai.getAvailability() <= 0)
22952 amit.gupta 482
					iter.remove();
483
			}
21445 kshitij.so 484
		}
22952 amit.gupta 485
		return responseSender.ok(dealsResponse);
21445 kshitij.so 486
	}
23816 amit.gupta 487
 
24091 tejbeer 488
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
489
	@ApiImplicitParams({
31507 tejbeer 490
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
24091 tejbeer 491
	@ApiOperation(value = "Get unit deal object")
492
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
27030 amit.gupta 493
			throws Exception {
24091 tejbeer 494
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
495
		List<Integer> tagIds = Arrays.asList(4);
496
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
497
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
498
			String categoryId = "(3 OR 6)";
499
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
500
			RestClient rc = new RestClient();
501
			Map<String, String> params = new HashMap<>();
502
			List<String> mandatoryQ = new ArrayList<>();
503
			String catalogString = "catalog" + id;
504
 
24149 amit.gupta 505
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
506
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
507
 
24091 tejbeer 508
			params.put("q", StringUtils.join(mandatoryQ, " "));
509
			params.put("fl", "*, [child parentFilter=id:catalog*]");
510
			params.put("sort", "rank_i asc, create_s desc");
511
			params.put("wt", "json");
512
			String response = null;
513
			try {
26575 amit.gupta 514
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
24091 tejbeer 515
			} catch (HttpHostConnectException e) {
516
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
517
			}
518
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
519
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26889 amit.gupta 520
			dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
24091 tejbeer 521
		} else {
522
			return responseSender.badRequest(
523
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
524
		}
525
		return responseSender.ok(dealResponse.get(0));
526
	}
527
 
22333 amit.gupta 528
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24949 amit.gupta 529
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
31507 tejbeer 530
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 531
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25543 amit.gupta 532
		logger.info("userInfo [{}]", userInfo);
25879 amit.gupta 533
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
534
				categoryId);
24163 amit.gupta 535
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 536
	}
25879 amit.gupta 537
 
31507 tejbeer 538
	@RequestMapping(value = "/fofo/brandCatalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
539
	public ResponseEntity<?> getBrands(HttpServletRequest request,
540
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
541
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
542
		logger.info("userInfo [{}]", userInfo);
543
 
544
		List<BrandCatalog> brandsDisplay = brandsService.getBrands(userInfo.getRetailerId(), userInfo.getEmail(),
545
				categoryId);
546
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
547
	}
548
 
25813 amit.gupta 549
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
550
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
551
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
552
		logger.info("userInfo [{}]", userInfo);
26889 amit.gupta 553
		List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
554
		return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
25813 amit.gupta 555
	}
23816 amit.gupta 556
 
25011 amit.gupta 557
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 558
		List<DBObject> subCategories = new ArrayList<>();
559
		RestClient rc = new RestClient();
560
		Map<String, String> params = new HashMap<>();
561
		params.put("q", "categoryId_i:6");
562
		params.put("group", "true");
563
		params.put("group.field", "subCategoryId_i");
564
		params.put("wt", "json");
25126 amit.gupta 565
		params.put("rows", "50");
25014 amit.gupta 566
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 567
		String response = null;
568
		try {
26575 amit.gupta 569
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
25010 amit.gupta 570
		} catch (HttpHostConnectException e) {
571
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
572
		}
573
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
574
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
575
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 576
		for (int i = 0; i < groups.length(); i++) {
577
			JSONObject groupObject = groups.getJSONObject(i);
578
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 579
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 580
			categoryIds.add(subCategoryId);
25010 amit.gupta 581
		}
25015 amit.gupta 582
 
25010 amit.gupta 583
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 584
		AtomicInteger i = new AtomicInteger(0);
585
		categories.forEach(x -> {
25011 amit.gupta 586
			DBObject dbObject = new BasicDBObject();
587
			dbObject.put("name", x.getLabel());
588
			dbObject.put("subCategoryId", x.getId());
589
			dbObject.put("rank", i.incrementAndGet());
590
			dbObject.put("categoryId", 6);
26441 tejbeer 591
			dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
25011 amit.gupta 592
			subCategories.add(dbObject);
25010 amit.gupta 593
		});
25015 amit.gupta 594
 
25011 amit.gupta 595
		return subCategories;
25015 amit.gupta 596
 
25010 amit.gupta 597
	}
598
 
22446 amit.gupta 599
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 600
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 601
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 602
	}
23816 amit.gupta 603
 
23793 tejbeer 604
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
605
	public ResponseEntity<?> getSubcategoriesToDisplay() {
606
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
607
	}
23816 amit.gupta 608
 
22406 amit.gupta 609
	@ApiImplicitParams({
31507 tejbeer 610
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 611
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 612
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 613
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
614
		String uri = sb.append(skus).toString();
23532 amit.gupta 615
		RestClient rc = new RestClient();
616
		String response;
617
		try {
618
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 619
		} catch (HttpHostConnectException e) {
23532 amit.gupta 620
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
621
		}
22406 amit.gupta 622
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 623
		List<Object> responseObject = new ArrayList<>();
624
		for (JsonValue j : result_json) {
23816 amit.gupta 625
			// logger.info("res " + j.asArray());
22407 amit.gupta 626
			List<Object> innerObject = new ArrayList<>();
627
			for (JsonValue jsonObject : j.asArray()) {
628
				innerObject.add(toDealObject(jsonObject.asObject()));
629
			}
630
			if (innerObject.size() > 0) {
631
				responseObject.add(innerObject);
632
			}
633
		}
22408 amit.gupta 634
		return responseSender.ok(responseObject);
22401 amit.gupta 635
	}
21339 kshitij.so 636
 
31547 tejbeer 637
	@RequestMapping(value = "/partner/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
638
	public ResponseEntity<?> getPartnersListing(HttpServletRequest request) throws Exception {
639
		List<WebListing> webListings = webListingRepository.selectAllWebListingByType(Optional.of(true),
31572 tejbeer 640
				WebListingSource.partner);
31547 tejbeer 641
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
642
		for (WebListing webListing : webListings) {
31642 tejbeer 643
 
31649 tejbeer 644
			webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing, "0", "20"));
31547 tejbeer 645
		}
646
		return responseSender.ok(webListings);
647
	}
648
 
31557 tejbeer 649
	private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, WebListing webListing, String offset,
650
			String limit) throws Exception {
31572 tejbeer 651
 
31547 tejbeer 652
		RestClient rc = new RestClient();
653
		Map<String, String> params = new HashMap<>();
654
		List<String> mandatoryQ = new ArrayList<>();
31757 tejbeer 655
 
31670 tejbeer 656
		FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
657
 
658
		params.put("sort", "w" + fs.getWarehouseId() + "_i desc");
659
 
31612 tejbeer 660
		List<Integer> webProducts = null;
31578 tejbeer 661
		if (webListing.getType().equals(WebListingType.solr)) {
31576 tejbeer 662
			logger.info("solrtype {}", webListing.getSolrQuery());
31757 tejbeer 663
			mandatoryQ.add(String.format("+{!parent which=\"" + webListing.getSolrQuery() + "\"} AND active_b:true AND show_default_b:true"));
31572 tejbeer 664
		} else {
31576 tejbeer 665
			logger.info("solrtype2 {}", webListing.getSolrQuery());
666
 
31612 tejbeer 667
			webProducts = webProductListingRepository
31572 tejbeer 668
					.selectAllByWebListingId(webListing.getId(), Integer.parseInt(offset), Integer.parseInt(limit))
669
					.stream().filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
31675 tejbeer 670
 
31572 tejbeer 671
			if (webProducts.size() == 0) {
672
				return new ArrayList<>();
673
			}
674
 
31709 tejbeer 675
			mandatoryQ.add(String.format(
31757 tejbeer 676
					"+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} AND active_b:true AND show_default_b:true"));
31572 tejbeer 677
 
678
		}
31547 tejbeer 679
		params.put("q", StringUtils.join(mandatoryQ, " "));
31581 tejbeer 680
		params.put("fl", "*, [child parentFilter=id:catalog* childFilter=active_b:true ]");
31642 tejbeer 681
 
31557 tejbeer 682
		params.put("start", String.valueOf(offset));
683
		params.put("rows", String.valueOf(limit));
31547 tejbeer 684
		params.put("wt", "json");
685
		String response = null;
686
		try {
31612 tejbeer 687
			response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
31547 tejbeer 688
		} catch (HttpHostConnectException e) {
689
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
690
		}
691
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
692
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
693
		List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
31612 tejbeer 694
 
31671 tejbeer 695
		if (webProducts != null && webListing.getUrl().equals("new-launches")) {
696
			List<Integer> webProductsFinal = webProducts;
697
			dealResponse = dealResponse.stream()
698
					.sorted(Comparator.comparing(x -> webProductsFinal.indexOf(x.getCatalogId())))
699
					.collect(Collectors.toList());
700
 
701
		}
702
 
31547 tejbeer 703
		return dealResponse;
704
	}
705
 
30669 amit.gupta 706
	@Autowired
707
	private SaholicCISTableRepository saholicCISTableRepository;
708
 
27053 amit.gupta 709
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId) throws Exception {
24091 tejbeer 710
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
711
		List<Integer> tagIds = Arrays.asList(4);
26924 amit.gupta 712
		List<Integer> itemIds = new ArrayList<>();
24091 tejbeer 713
		if (docs.length() > 0) {
714
			for (int i = 0; i < docs.length(); i++) {
715
				JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 716
				if (doc.has("_childDocuments_")) {
26515 amit.gupta 717
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
718
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
719
						int itemId = childItem.getInt("itemId_i");
26924 amit.gupta 720
						itemIds.add(itemId);
26515 amit.gupta 721
					}
24091 tejbeer 722
				}
723
			}
26924 amit.gupta 724
			if (itemIds.size() == 0) {
26573 amit.gupta 725
				return dealResponse;
726
			}
24091 tejbeer 727
		}
27053 amit.gupta 728
		// get warehouse Id
27030 amit.gupta 729
		int warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();
27053 amit.gupta 730
		Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems()
731
				.get(warehouseId);
30123 amit.gupta 732
		List<Integer> catalogIds = new ArrayList<>();
733
		for (int i = 0; i < docs.length(); i++) {
734
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
735
			JSONObject doc = docs.getJSONObject(i);
736
			catalogIds.add(doc.getInt("catalogId_i"));
737
		}
30188 amit.gupta 738
		List<CreateOfferRequest> allSchemOffers = null;
31954 amit.gupta 739
		Map<Integer, PriceCircularItemModelNew> priceCircularItemModelMap = new HashMap<>();
30156 amit.gupta 740
		if (catalogIds.size() > 0) {
31954 amit.gupta 741
			PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());
30188 amit.gupta 742
			allSchemOffers = priceCircularModel.getOffers();
27053 amit.gupta 743
 
31954 amit.gupta 744
			List<PriceCircularItemModelNew> priceCircularItemModelNews = priceCircularModel.getPriceCircularItemModelNews();
745
			if (priceCircularItemModelNews != null) {
746
				priceCircularItemModelMap = priceCircularItemModelNews.stream()
30595 tejbeer 747
						.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
30156 amit.gupta 748
			}
30123 amit.gupta 749
		}
30188 amit.gupta 750
 
31629 tejbeer 751
		List<CatalogFavourite> catalogFavourites = catalogFavouriteRepository.selectBypartnerId(fofoId);
752
		List<Integer> catalogFavouriteIds = new ArrayList<>();
753
		if (!catalogFavourites.isEmpty()) {
754
			catalogFavouriteIds = catalogFavourites.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
755
		}
756
 
757
		if (!catalogFavourites.isEmpty()) {
758
			catalogFavourites.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
759
		}
760
 
24091 tejbeer 761
		for (int i = 0; i < docs.length(); i++) {
762
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
763
			JSONObject doc = docs.getJSONObject(i);
30188 amit.gupta 764
			FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
765
			fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
766
			fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
767
			fofoCatalogResponse.setTitle(doc.getString("title_s"));
30595 tejbeer 768
 
31629 tejbeer 769
			if (catalogFavouriteIds.contains(fofoCatalogResponse.getCatalogId())) {
770
				fofoCatalogResponse.setFavourite(true);
771
			}
772
 
30595 tejbeer 773
			List<WebOffer> webOffers = webOfferRepository.selectAllActiveOffers()
774
					.get(fofoCatalogResponse.getCatalogId());
30683 tejbeer 775
 
30617 tejbeer 776
			logger.info("webOffers {}", webOffers);
30595 tejbeer 777
			if (webOffers != null && webOffers.size() > 0) {
30597 tejbeer 778
				fofoCatalogResponse.setWebOffers(webOffers);
31612 tejbeer 779
				fofoCatalogResponse.setOffers(webOffers.stream().map(x -> x.getTitle()).collect(Collectors.toList()));
780
 
30595 tejbeer 781
			}
30683 tejbeer 782
 
783
			List<ComboModel> comboModels = comboModelRepository.selectByWarehouseId(warehouseId).stream()
784
					.filter(x -> x.getCatalogId() == fofoCatalogResponse.getCatalogId()).collect(Collectors.toList());
785
 
786
			for (ComboModel comboModel : comboModels) {
787
 
788
				List<ComboMappedModel> mappedModels = comboMappedModelRepository.selectByComboId(comboModel.getId());
789
 
790
				comboModel.setComboMappedModels(mappedModels);
791
 
792
			}
793
 
794
			if (comboModels != null && comboModels.size() > 0) {
795
				fofoCatalogResponse.setComboModels(comboModels);
796
			}
797
 
24117 amit.gupta 798
			try {
30188 amit.gupta 799
				fofoCatalogResponse.setFeature(doc.getString("feature_s"));
24149 amit.gupta 800
			} catch (Exception e) {
30188 amit.gupta 801
				fofoCatalogResponse.setFeature(null);
802
				logger.info("Could not find Feature_s for {}", fofoCatalogResponse.getCatalogId());
24117 amit.gupta 803
			}
31612 tejbeer 804
 
30188 amit.gupta 805
			fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
31612 tejbeer 806
			logger.info("labelss {}", doc.has("label_ss"));
807
 
808
			if (doc.has("label_ss")) {
809
				logger.info("label {}", doc.getJSONArray("label_ss"));
810
 
811
				JSONArray arr = doc.getJSONArray("label_ss");
31709 tejbeer 812
				Set<String> labels = new HashSet<String>();
31635 tejbeer 813
				for (int j = 0; j < arr.length(); j++) {
31612 tejbeer 814
					labels.add(arr.getString(j));
815
				}
816
 
31709 tejbeer 817
				fofoCatalogResponse.setLabels(new ArrayList<>(labels));
31612 tejbeer 818
 
819
			}
820
 
26589 amit.gupta 821
			if (doc.has("_childDocuments_")) {
27035 amit.gupta 822
				String modelColorClass = "grey";
27042 amit.gupta 823
				FofoAvailabilityInfo fdiAnyColour = null;
31507 tejbeer 824
				// Iterating itemIds
26515 amit.gupta 825
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
31954 amit.gupta 826
					PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap
30595 tejbeer 827
							.get(fofoCatalogResponse.getCatalogId());
26515 amit.gupta 828
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
829
					int itemId = childItem.getInt("itemId_i");
830
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
31507 tejbeer 831
					if (!fofoAvailabilityInfoMap.containsKey(itemId)) {
26515 amit.gupta 832
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
31507 tejbeer 833
						List<SaholicCISTable> currentAvailability = saholicCISTableRepository
834
								.selectByItemWarehouse(itemId, warehouseId);
27869 amit.gupta 835
						List<SaholicPOItem> poItemAvailability = null;
28262 amit.gupta 836
						if (poItemAvailabilityMap != null) {
27869 amit.gupta 837
							poItemAvailability = poItemAvailabilityMap.get(itemId);
838
						}
32037 amit.gupta 839
						fdi.setNlc((float)priceCircularItemModel.getNetNlc());
30686 amit.gupta 840
 
841
						for (SaholicCISTable saholicCISTable : currentAvailability) {
842
							saholicCISTable.setWarehouseName(
843
									ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
27062 amit.gupta 844
						}
30693 amit.gupta 845
 
846
						Map<Integer, SaholicCISTable> map = currentAvailability.stream()
30686 amit.gupta 847
								.collect(Collectors.toMap(SaholicCISTable::getWarehouseFrom, x -> x));
28262 amit.gupta 848
						if (poItemAvailability != null) {
30686 amit.gupta 849
							for (SaholicPOItem saholicPOItem : poItemAvailability) {
850
								if (map.containsKey(saholicPOItem.getWarehouseFrom())) {
851
									map.get(saholicPOItem.getWarehouseFrom())
852
											.setPopendingQty(saholicPOItem.getUnfulfilledQty());
853
								} else {
30669 amit.gupta 854
									SaholicCISTable saholicCISTable = new SaholicCISTable();
855
									saholicCISTable.setAvailability(0);
856
									saholicCISTable.setReserved(0);
857
									saholicCISTable.setItemId(itemId);
30692 amit.gupta 858
									saholicCISTable.setWarehouseId(warehouseId);
30669 amit.gupta 859
									saholicCISTable.setPopendingQty(saholicPOItem.getUnfulfilledQty());
860
									saholicCISTable.setWarehouseFrom(saholicPOItem.getWarehouseFrom());
31507 tejbeer 861
									saholicCISTable.setWarehouseName(
862
											ProfitMandiConstants.WAREHOUSE_MAP.get(saholicPOItem.getWarehouseFrom()));
30669 amit.gupta 863
									map.put(saholicPOItem.getWarehouseFrom(), saholicCISTable);
27053 amit.gupta 864
								}
865
							}
866
						}
30669 amit.gupta 867
						fdi.setSaholicCISTableList(new ArrayList<>(map.values()));
27042 amit.gupta 868
						String poColor = "grey";
27032 amit.gupta 869
						boolean active = false;
27053 amit.gupta 870
						if (currentAvailability != null && currentAvailability.stream()
30669 amit.gupta 871
								.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
27053 amit.gupta 872
							poColor = "green";
873
							modelColorClass = "green";
874
						} else if (poItemAvailability != null && poItemAvailability.stream()
875
								.collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
876
							if (currentAvailability != null && poItemAvailability.stream()
877
									.collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty))
878
									+ currentAvailability.stream()
31507 tejbeer 879
											.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
27042 amit.gupta 880
								poColor = "grey";
27032 amit.gupta 881
							} else {
27040 amit.gupta 882
								poColor = "yellow";
27053 amit.gupta 883
								if (modelColorClass != "green") {
27035 amit.gupta 884
									modelColorClass = poColor;
885
								}
27032 amit.gupta 886
							}
27031 amit.gupta 887
						}
27032 amit.gupta 888
						fdi.setColorClass(poColor);
26889 amit.gupta 889
						fdi.setSellingPrice(sellingPrice);
27031 amit.gupta 890
						fdi.setActive(active);
26889 amit.gupta 891
						fdi.setMrp(childItem.getDouble("mrp_f"));
26515 amit.gupta 892
						fdi.setMop((float) childItem.getDouble("mop_f"));
893
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
27042 amit.gupta 894
						if (fdi.getColor().equalsIgnoreCase("any colour")) {
27053 amit.gupta 895
							fdiAnyColour = fdi;
27042 amit.gupta 896
						}
26515 amit.gupta 897
						fdi.setTagId(childItem.getInt("tagId_i"));
898
						fdi.setItem_id(itemId);
30595 tejbeer 899
						Float cashBack = schemeService.getCatalogSchemeCashBack()
900
								.get(fofoCatalogResponse.getCatalogId());
26846 tejbeer 901
						cashBack = cashBack == null ? 0 : cashBack;
26696 amit.gupta 902
						fdi.setCashback(cashBack);
26897 amit.gupta 903
						fdi.setMinBuyQuantity(1);
28268 amit.gupta 904
						if (hotDeal) {
905
							if (currentAvailability != null) {
906
								fdi.setAvailability(currentAvailability.stream()
30669 amit.gupta 907
										.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));
28268 amit.gupta 908
							} else {
909
								fdi.setAvailability(0);
910
							}
911
						} else {
30595 tejbeer 912
							// Lets consider that its out of stock
28268 amit.gupta 913
							fdi.setAvailability(100);
914
							Item item = null;
30135 amit.gupta 915
							try {
28268 amit.gupta 916
								item = itemRepository.selectById(itemId);
30135 amit.gupta 917
							} catch (Exception e) {
28268 amit.gupta 918
								e.printStackTrace();
919
								continue;
920
							}
30711 amit.gupta 921
							// In case its tampered glass moq should be
28268 amit.gupta 922
							if (item.getCategoryId() == 10020) {
923
								fdi.setMinBuyQuantity(5);
924
							}
24091 tejbeer 925
						}
26515 amit.gupta 926
						fdi.setQuantityStep(1);
927
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
928
						fofoAvailabilityInfoMap.put(itemId, fdi);
24091 tejbeer 929
					}
930
				}
27053 amit.gupta 931
				if (fdiAnyColour != null) {
30444 amit.gupta 932
					fdiAnyColour.setColorClass(modelColorClass);
27042 amit.gupta 933
				}
24091 tejbeer 934
			}
935
			if (fofoAvailabilityInfoMap.values().size() > 0) {
27053 amit.gupta 936
				List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values().stream()
937
						.sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed())
938
						.collect(Collectors.toList());
30188 amit.gupta 939
				fofoCatalogResponse.setItems(availabilityList);
940
				if (priceCircularItemModelMap.containsKey(fofoCatalogResponse.getCatalogId())) {
31954 amit.gupta 941
					PriceCircularItemModelNew priceCircularItemModel = priceCircularItemModelMap
30595 tejbeer 942
							.get(fofoCatalogResponse.getCatalogId());
30193 amit.gupta 943
					if (priceCircularItemModel.getSlabPayouts() != null) {
944
						List<CreateOfferRequest> schemeOffers = new ArrayList<>();
31954 amit.gupta 945
						List<Map<Integer, AmountModel>> slabPayouts = priceCircularItemModel.getSlabPayouts();
946
						Iterator<Map<Integer, AmountModel>> iterator = slabPayouts.iterator();
30196 amit.gupta 947
						int iteratorCount = 0;
948
						while (iterator.hasNext()) {
31954 amit.gupta 949
							Map<Integer, AmountModel> slabPayoutMap = iterator.next();
30196 amit.gupta 950
							if (slabPayoutMap != null) {
951
								schemeOffers.add(allSchemOffers.get(iteratorCount));
30193 amit.gupta 952
							} else {
30196 amit.gupta 953
								iterator.remove();
30193 amit.gupta 954
							}
30198 amit.gupta 955
							iteratorCount++;
30188 amit.gupta 956
						}
30193 amit.gupta 957
						fofoCatalogResponse.setSchemeOffers(schemeOffers);
958
					}
30188 amit.gupta 959
					fofoCatalogResponse.setPriceCircularItemModel(priceCircularItemModel);
960
				}
961
				dealResponse.add(fofoCatalogResponse);
24091 tejbeer 962
			}
27053 amit.gupta 963
		}
964
		return dealResponse;
24091 tejbeer 965
 
966
	}
967
 
25968 amit.gupta 968
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter,
31507 tejbeer 969
			boolean hotDeal) throws ProfitMandiBusinessException {
25879 amit.gupta 970
		Map<Integer, TagListing> itemTagListingMap = null;
971
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
972
		List<Integer> tagIds = Arrays.asList(4);
26589 amit.gupta 973
 
25968 amit.gupta 974
		itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds))
975
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
25880 amit.gupta 976
 
25879 amit.gupta 977
		for (int i = 0; i < docs.length(); i++) {
978
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
979
			JSONObject doc = docs.getJSONObject(i);
25880 amit.gupta 980
 
25879 amit.gupta 981
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
982
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
983
				int itemId = childItem.getInt("itemId_i");
984
				TagListing tl = itemTagListingMap.get(itemId);
26589 amit.gupta 985
				if (tl == null) {
25968 amit.gupta 986
					continue;
987
				}
25879 amit.gupta 988
				if (hotDeal) {
989
					if (!tl.isHotDeals()) {
990
						continue;
991
					}
992
				}
993
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
994
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
995
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
996
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
997
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
998
					}
999
				} else {
1000
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
1001
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
1002
					fdi.setMop((float) childItem.getDouble("mop_f"));
26665 amit.gupta 1003
					fdi.setMop((float) tl.getMrp());
25879 amit.gupta 1004
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
1005
					fdi.setTagId(childItem.getInt("tagId_i"));
1006
					fdi.setItem_id(itemId);
1007
					Item item = itemRepository.selectById(itemId);
1008
					// In case its tampered glass moq should be 5
1009
					if (item.getCategoryId() == 10020) {
1010
						fdi.setMinBuyQuantity(10);
1011
					} else {
1012
						fdi.setMinBuyQuantity(1);
1013
					}
26050 amit.gupta 1014
					fdi.setAvailability(itemFilter.get(itemId));
25879 amit.gupta 1015
					fdi.setQuantityStep(1);
1016
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
1017
					fofoAvailabilityInfoMap.put(itemId, fdi);
1018
				}
1019
			}
1020
			if (fofoAvailabilityInfoMap.values().size() > 0) {
25880 amit.gupta 1021
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
25879 amit.gupta 1022
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
1023
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
1024
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
1025
					ffdr.setTitle(doc.getString("title_s"));
1026
					try {
1027
						ffdr.setFeature(doc.getString("feature_s"));
1028
					} catch (Exception e) {
1029
						ffdr.setFeature(null);
1030
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
1031
					}
1032
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
1033
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
1034
					dealResponse.add(ffdr);
1035
				}
1036
			}
1037
		}
1038
		return dealResponse;
25880 amit.gupta 1039
 
25879 amit.gupta 1040
	}
30683 tejbeer 1041
 
1042
	@RequestMapping(value = "/combo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1043
	public ResponseEntity<?> getBanners(@RequestParam int catalogId, @RequestParam int warehouseId) {
1044
		List<ComboModel> comboModels = comboModelRepository.selectByCatalogIdAndWarehouseId(catalogId, warehouseId);
1045
		return responseSender.ok(comboModels);
1046
	}
25967 amit.gupta 1047
}