Subversion Repositories SmartDukaan

Rev

Rev 26847 | Rev 26883 | 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 java.util.ArrayList;
22336 amit.gupta 4
import java.util.Arrays;
21339 kshitij.so 5
import java.util.HashMap;
23814 amit.gupta 6
import java.util.HashSet;
22952 amit.gupta 7
import java.util.Iterator;
21339 kshitij.so 8
import java.util.List;
9
import java.util.Map;
25875 amit.gupta 10
import java.util.Optional;
25959 amit.gupta 11
import java.util.Set;
25010 amit.gupta 12
import java.util.concurrent.atomic.AtomicInteger;
23814 amit.gupta 13
import java.util.stream.Collectors;
21339 kshitij.so 14
 
15
import javax.servlet.http.HttpServletRequest;
16
 
22319 amit.gupta 17
import org.apache.commons.lang3.StringUtils;
23532 amit.gupta 18
import org.apache.http.conn.HttpHostConnectException;
23786 amit.gupta 19
import org.apache.logging.log4j.LogManager;
20
import org.apache.logging.log4j.Logger;
22319 amit.gupta 21
import org.json.JSONArray;
22
import org.json.JSONObject;
22273 amit.gupta 23
import org.springframework.beans.factory.annotation.Autowired;
21339 kshitij.so 24
import org.springframework.beans.factory.annotation.Value;
25
import org.springframework.http.HttpStatus;
26
import org.springframework.http.MediaType;
27
import org.springframework.http.ResponseEntity;
28
import org.springframework.stereotype.Controller;
22286 amit.gupta 29
import org.springframework.transaction.annotation.Transactional;
21339 kshitij.so 30
import org.springframework.web.bind.annotation.PathVariable;
31
import org.springframework.web.bind.annotation.RequestMapping;
32
import org.springframework.web.bind.annotation.RequestMethod;
33
import org.springframework.web.bind.annotation.RequestParam;
34
 
35
import com.eclipsesource.json.Json;
36
import com.eclipsesource.json.JsonArray;
37
import com.eclipsesource.json.JsonObject;
38
import com.eclipsesource.json.JsonValue;
39
import com.google.gson.Gson;
21356 kshitij.so 40
import com.google.gson.reflect.TypeToken;
25010 amit.gupta 41
import com.mongodb.BasicDBObject;
24163 amit.gupta 42
import com.mongodb.DBObject;
21643 ashik.ali 43
import com.spice.profitmandi.common.enumuration.SchemeType;
21339 kshitij.so 44
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
45
import com.spice.profitmandi.common.model.ProfitMandiConstants;
22289 amit.gupta 46
import com.spice.profitmandi.common.model.UserInfo;
21643 ashik.ali 47
import com.spice.profitmandi.common.web.client.RestClient;
22319 amit.gupta 48
import com.spice.profitmandi.common.web.util.ResponseSender;
25010 amit.gupta 49
import com.spice.profitmandi.dao.entity.catalog.Category;
23426 amit.gupta 50
import com.spice.profitmandi.dao.entity.catalog.Item;
23814 amit.gupta 51
import com.spice.profitmandi.dao.entity.catalog.TagListing;
26847 tejbeer 52
import com.spice.profitmandi.dao.entity.fofo.SuggestedPo;
26846 tejbeer 53
import com.spice.profitmandi.dao.entity.fofo.SuggestedPoDetail;
23861 amit.gupta 54
import com.spice.profitmandi.dao.entity.inventory.ItemAvailabilityCache;
22361 amit.gupta 55
import com.spice.profitmandi.dao.model.UserCart;
25010 amit.gupta 56
import com.spice.profitmandi.dao.repository.catalog.CategoryRepository;
23426 amit.gupta 57
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23814 amit.gupta 58
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
22333 amit.gupta 59
import com.spice.profitmandi.dao.repository.dtr.Mongo;
22361 amit.gupta 60
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
26846 tejbeer 61
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoDetailRepository;
26847 tejbeer 62
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoRepository;
22989 amit.gupta 63
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
23798 amit.gupta 64
import com.spice.profitmandi.service.authentication.RoleManager;
25880 amit.gupta 65
import com.spice.profitmandi.service.inventory.AvailabilityInfo;
25882 amit.gupta 66
import com.spice.profitmandi.service.inventory.Bucket;
25880 amit.gupta 67
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
68
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
25875 amit.gupta 69
import com.spice.profitmandi.service.inventory.ItemBucketService;
25879 amit.gupta 70
import com.spice.profitmandi.service.inventory.ItemQuantityPojo;
22287 amit.gupta 71
import com.spice.profitmandi.service.pricing.PricingService;
26695 amit.gupta 72
import com.spice.profitmandi.service.scheme.SchemeService;
21356 kshitij.so 73
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 74
import com.spice.profitmandi.web.res.DealObjectResponse;
75
import com.spice.profitmandi.web.res.DealsResponse;
76
 
77
import io.swagger.annotations.ApiImplicitParam;
78
import io.swagger.annotations.ApiImplicitParams;
79
import io.swagger.annotations.ApiOperation;
80
 
81
@Controller
22319 amit.gupta 82
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 83
public class DealsController {
84
 
23568 govind 85
	private static final Logger logger = LogManager.getLogger(DealsController.class);
21339 kshitij.so 86
 
87
	@Value("${python.api.host}")
88
	private String host;
23816 amit.gupta 89
 
21339 kshitij.so 90
	@Value("${python.api.port}")
91
	private int port;
23816 amit.gupta 92
 
93
	// This is now unused as we are not supporting multiple companies.
23300 amit.gupta 94
	@Value("${gadgetCops.invoice.cc}")
23816 amit.gupta 95
	private String[] ccGadgetCopInvoiceTo;
22319 amit.gupta 96
 
97
	@Autowired
98
	private PricingService pricingService;
23816 amit.gupta 99
 
22273 amit.gupta 100
	@Autowired
25010 amit.gupta 101
	private CategoryRepository categoryRepository;
102
 
103
	@Autowired
26695 amit.gupta 104
	private SchemeService schemeService;
105
 
106
	@Autowired
22333 amit.gupta 107
	private Mongo mongoClient;
25879 amit.gupta 108
 
25875 amit.gupta 109
	@Autowired
110
	private ItemBucketService itemBucketService;
23816 amit.gupta 111
 
22333 amit.gupta 112
	@Autowired
22361 amit.gupta 113
	private UserAccountRepository userAccountRepository;
23816 amit.gupta 114
 
22989 amit.gupta 115
	@Autowired
22931 ashik.ali 116
	private ResponseSender<?> responseSender;
23816 amit.gupta 117
 
22554 amit.gupta 118
	@Autowired
25010 amit.gupta 119
	private CategoryRepository repository;
120
 
121
	@Autowired
23814 amit.gupta 122
	private TagListingRepository tagListingRepository;
23816 amit.gupta 123
 
23814 amit.gupta 124
	@Autowired
23426 amit.gupta 125
	private ItemRepository itemRepository;
23816 amit.gupta 126
 
23786 amit.gupta 127
	@Autowired
23861 amit.gupta 128
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
129
 
130
	@Autowired
23798 amit.gupta 131
	private RoleManager roleManagerService;
23816 amit.gupta 132
 
26846 tejbeer 133
	@Autowired
134
	private SuggestedPoDetailRepository monthlyPoDetailRepository;
135
 
26847 tejbeer 136
	@Autowired
137
	private SuggestedPoRepository suggestedPoRepository;
138
 
22336 amit.gupta 139
	List<String> filterableParams = Arrays.asList("brand");
24949 amit.gupta 140
 
25876 amit.gupta 141
	@RequestMapping(value = "/fofo/buckets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25879 amit.gupta 142
	public ResponseEntity<?> getBuckets(HttpServletRequest request) throws ProfitMandiBusinessException {
25875 amit.gupta 143
		logger.info("Request " + request.getParameterMap());
144
		return responseSender.ok(itemBucketService.getBuckets(Optional.of(true)));
145
	}
25879 amit.gupta 146
 
147
	@RequestMapping(value = "/fofo/bucket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25880 amit.gupta 148
	public ResponseEntity<?> getBucketDetails(HttpServletRequest request, @RequestParam int id)
25879 amit.gupta 149
			throws ProfitMandiBusinessException {
25880 amit.gupta 150
		List<ItemQuantityPojo> iqPojo = itemBucketService.getBucketDetails(id);
25968 amit.gupta 151
		Map<Integer, Integer> itemIdsQtyMap = iqPojo.stream()
152
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
153
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream()
154
				.map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
25879 amit.gupta 155
		RestClient rc = new RestClient();
156
		Map<String, String> params = new HashMap<>();
157
		List<String> mandatoryQ = new ArrayList<>();
25968 amit.gupta 158
		mandatoryQ.add(
159
				String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
25959 amit.gupta 160
		params.put("start", "0");
161
		params.put("rows", "100");
25879 amit.gupta 162
		params.put("q", StringUtils.join(mandatoryQ, " "));
163
		params.put("fl", "*, [child parentFilter=id:catalog*]");
164
 
165
		params.put("wt", "json");
166
		String response = null;
167
		try {
26573 amit.gupta 168
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
25879 amit.gupta 169
		} catch (HttpHostConnectException e) {
170
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
171
		}
172
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
173
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
25968 amit.gupta 174
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
26051 amit.gupta 175
 
26589 amit.gupta 176
		Bucket bucket = itemBucketService.getBuckets(Optional.of(true)).stream().filter(x -> x.getId() == id)
177
				.collect(Collectors.toList()).get(0);
25882 amit.gupta 178
		bucket.setFofoCatalogResponses(dealResponse);
179
		return responseSender.ok(bucket);
25879 amit.gupta 180
	}
181
 
26846 tejbeer 182
	@RequestMapping(value = "/fofo/suggestedPo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
183
	public ResponseEntity<?> getSuggestedPo(HttpServletRequest request, @RequestParam int id)
184
			throws ProfitMandiBusinessException {
185
 
186
		List<SuggestedPoDetail> mpd = monthlyPoDetailRepository.selectByPoId(id);
187
		Map<Integer, Integer> itemIdsQtyMap = mpd.stream()
188
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
189
 
190
		Set<Integer> catalogIds = itemRepository.selectByIds(itemIdsQtyMap.keySet()).stream()
191
				.map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
192
		RestClient rc = new RestClient();
193
		Map<String, String> params = new HashMap<>();
194
		List<String> mandatoryQ = new ArrayList<>();
195
		mandatoryQ.add(
196
				String.format("+catalogId_i:(%s) +{!parent which=\"id:catalog*\"}", StringUtils.join(catalogIds, " ")));
197
		params.put("start", "0");
198
		params.put("rows", "100");
199
		params.put("q", StringUtils.join(mandatoryQ, " "));
200
		params.put("fl", "*, [child parentFilter=id:catalog*]");
201
 
202
		params.put("wt", "json");
203
		String response = null;
204
		try {
205
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
206
		} catch (HttpHostConnectException e) {
207
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
208
		}
209
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
210
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
211
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, itemIdsQtyMap, false);
212
 
213
		return responseSender.ok(dealResponse);
214
	}
215
 
26847 tejbeer 216
	@RequestMapping(value = "/suggestedPo/status", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26848 tejbeer 217
	@ApiImplicitParams({
218
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
219
	@ApiOperation(value = "")
26847 tejbeer 220
	public ResponseEntity<?> changeSuggestedPoStatus(HttpServletRequest request, @RequestParam int id)
221
			throws ProfitMandiBusinessException {
222
		SuggestedPo suggestedPo = suggestedPoRepository.selectById(id);
223
		suggestedPo.setStatus("closed");
224
 
225
		return responseSender.ok(true);
226
	}
227
 
23816 amit.gupta 228
	private String getCommaSeparateTags(int userId) {
22361 amit.gupta 229
		UserCart uc = userAccountRepository.getUserCart(userId);
230
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
22287 amit.gupta 231
		List<String> strTagIds = new ArrayList<>();
232
		for (Integer tagId : tagIds) {
233
			strTagIds.add(String.valueOf(tagId));
22273 amit.gupta 234
		}
22287 amit.gupta 235
		return String.join(",", strTagIds);
22273 amit.gupta 236
	}
237
 
22319 amit.gupta 238
	@ApiImplicitParams({
239
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
240
	@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24091 tejbeer 241
	public ResponseEntity<?> getFofo(HttpServletRequest request,
26758 amit.gupta 242
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
22319 amit.gupta 243
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
23816 amit.gupta 244
			@RequestParam(value = "sort", required = false) String sort,
245
			@RequestParam(value = "brand", required = false) String brand,
25011 amit.gupta 246
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
24946 amit.gupta 247
			@RequestParam(value = "q", required = false) String queryTerm,
24091 tejbeer 248
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
22328 amit.gupta 249
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
22319 amit.gupta 250
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
23786 amit.gupta 251
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
25879 amit.gupta 252
			// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
25389 tejbeer 253
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
23816 amit.gupta 254
			RestClient rc = new RestClient();
22319 amit.gupta 255
			Map<String, String> params = new HashMap<>();
22336 amit.gupta 256
			List<String> mandatoryQ = new ArrayList<>();
24974 amit.gupta 257
			if (queryTerm != null && !queryTerm.equals("null")) {
24975 amit.gupta 258
				mandatoryQ.add(String.format("+(%s)", queryTerm));
259
			} else {
260
				queryTerm = null;
24971 amit.gupta 261
			}
25015 amit.gupta 262
			if (subCategoryId != 0) {
24949 amit.gupta 263
				mandatoryQ
264
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
24875 amit.gupta 265
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
23814 amit.gupta 266
			} else if (hotDeal) {
23816 amit.gupta 267
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
268
						StringUtils.join(tagIds, " ")));
25015 amit.gupta 269
 
270
			} else if (StringUtils.isNotBlank(brand)) {
271
				mandatoryQ.add(
272
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
273
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
274
 
22347 amit.gupta 275
			} else {
26789 amit.gupta 276
				mandatoryQ
26846 tejbeer 277
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
278
								categoryId, categoryId, StringUtils.join(tagIds, " ")));
22336 amit.gupta 279
			}
23816 amit.gupta 280
			params.put("q", StringUtils.join(mandatoryQ, " "));
22319 amit.gupta 281
			params.put("fl", "*, [child parentFilter=id:catalog*]");
24995 amit.gupta 282
			if (queryTerm == null) {
24975 amit.gupta 283
				params.put("sort", "create_s desc");
284
			}
22319 amit.gupta 285
			params.put("start", String.valueOf(offset));
286
			params.put("rows", String.valueOf(limit));
287
			params.put("wt", "json");
23532 amit.gupta 288
			String response = null;
289
			try {
26575 amit.gupta 290
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
23532 amit.gupta 291
			} catch (HttpHostConnectException e) {
292
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
293
			}
22319 amit.gupta 294
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
295
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 296
			dealResponse = getCatalogResponse(docs, hotDeal);
26589 amit.gupta 297
			/*
298
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
299
			 * dealResponse.stream() .filter(x ->
300
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
301
			 * ; }
302
			 */
303
		} else {
304
			return responseSender.badRequest(
305
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
306
		}
307
		return responseSender.ok(dealResponse);
308
	}
309
 
310
	@ApiImplicitParams({
311
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
312
	@RequestMapping(value = "/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
313
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
26758 amit.gupta 314
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
26589 amit.gupta 315
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
316
			@RequestParam(value = "sort", required = false) String sort,
317
			@RequestParam(value = "brand", required = false) String brand,
318
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
319
			@RequestParam(value = "q", required = false) String queryTerm,
320
			@RequestParam(value = " ", required = false, defaultValue = "true") boolean partnerStockOnly)
321
			throws Throwable {
322
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
323
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
324
		UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
26846 tejbeer 325
 
26589 amit.gupta 326
		logger.info("Retiler Id ==> {}", uc.getUserId());
327
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
26846 tejbeer 328
			if (partnerStockOnly) {
329
 
24168 amit.gupta 330
			}
26589 amit.gupta 331
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
332
			RestClient rc = new RestClient();
333
			Map<String, String> params = new HashMap<>();
334
			List<String> mandatoryQ = new ArrayList<>();
335
			if (queryTerm != null && !queryTerm.equals("null")) {
336
				mandatoryQ.add(String.format("+(%s)", queryTerm));
337
			} else {
338
				queryTerm = null;
339
			}
340
			if (subCategoryId != 0) {
341
				mandatoryQ
342
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
343
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
344
			} else if (StringUtils.isNotBlank(brand)) {
345
				mandatoryQ.add(
346
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
347
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
348
 
349
			} else {
350
				mandatoryQ.add(
351
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
352
			}
353
			params.put("q", StringUtils.join(mandatoryQ, " "));
354
			params.put("fl", "*, [child parentFilter=id:catalog*]");
355
			if (queryTerm == null) {
356
				params.put("sort", "create_s desc");
357
			}
358
			params.put("start", String.valueOf(offset));
359
			params.put("rows", String.valueOf(limit));
360
			params.put("wt", "json");
361
			String response = null;
362
			try {
363
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
364
			} catch (HttpHostConnectException e) {
365
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
366
			}
367
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
368
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
369
			dealResponse = getCatalogResponse(docs, false);
370
			/*
371
			 * if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
372
			 * dealResponse.stream() .filter(x ->
373
			 * Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()))
374
			 * ; }
375
			 */
22319 amit.gupta 376
		} else {
23816 amit.gupta 377
			return responseSender.badRequest(
378
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
22319 amit.gupta 379
		}
380
		return responseSender.ok(dealResponse);
381
	}
22273 amit.gupta 382
 
22319 amit.gupta 383
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 384
	@ApiImplicitParams({
22319 amit.gupta 385
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 386
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 387
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
388
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
389
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
390
			@RequestParam(value = "direction", required = false) String direction,
391
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
392
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 393
		String response = null;
22319 amit.gupta 394
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 395
 
22319 amit.gupta 396
		String uri = "/deals/" + userId;
23532 amit.gupta 397
		RestClient rc = new RestClient();
22272 amit.gupta 398
		Map<String, String> params = new HashMap<>();
399
		params.put("offset", offset);
400
		params.put("limit", limit);
401
		params.put("categoryId", categoryId);
402
		params.put("direction", direction);
403
		params.put("sort", sort);
404
		params.put("source", "online");
405
		params.put("filterData", filterData);
23816 amit.gupta 406
		/*
407
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
408
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
409
		 */
22272 amit.gupta 410
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 411
		try {
412
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
413
		} catch (HttpHostConnectException e) {
414
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
415
		}
22931 ashik.ali 416
 
22272 amit.gupta 417
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 418
		for (JsonValue j : result_json) {
23816 amit.gupta 419
			// logger.info("res " + j.asArray());
22272 amit.gupta 420
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 421
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 422
				innerObject.add(toDealObject(jsonObject.asObject()));
423
			}
22319 amit.gupta 424
			if (innerObject.size() > 0) {
22272 amit.gupta 425
				responseObject.add(innerObject);
426
			}
427
		}
23022 ashik.ali 428
		return responseSender.ok(responseObject);
22272 amit.gupta 429
	}
430
 
22319 amit.gupta 431
	private Object toDealObject(JsonObject jsonObject) {
432
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 433
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
434
		}
435
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
436
	}
22319 amit.gupta 437
 
438
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 439
	@ApiImplicitParams({
22319 amit.gupta 440
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 441
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 442
	public ResponseEntity<?> getBrands(HttpServletRequest request,
23816 amit.gupta 443
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 444
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 445
		String response = null;
22319 amit.gupta 446
		// TODO: move to properties
21356 kshitij.so 447
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 448
		RestClient rc = new RestClient();
21356 kshitij.so 449
		Map<String, String> params = new HashMap<>();
450
		params.put("category_id", category_id);
21358 kshitij.so 451
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 452
		try {
453
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
454
		} catch (HttpHostConnectException e) {
455
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
456
		}
23816 amit.gupta 457
 
22319 amit.gupta 458
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
459
		}.getType());
23022 ashik.ali 460
 
461
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 462
	}
22319 amit.gupta 463
 
464
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 465
	@ApiImplicitParams({
22319 amit.gupta 466
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 467
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 468
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
469
			throws ProfitMandiBusinessException {
21445 kshitij.so 470
		String response = null;
22319 amit.gupta 471
		// TODO: move to properties
472
		String uri = "getDealById/" + id;
473
		System.out.println("Unit deal " + uri);
23532 amit.gupta 474
		RestClient rc = new RestClient();
21445 kshitij.so 475
		Map<String, String> params = new HashMap<>();
476
		DealsResponse dealsResponse = null;
23532 amit.gupta 477
		try {
478
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
479
		} catch (HttpHostConnectException e) {
480
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
481
		}
23816 amit.gupta 482
 
21445 kshitij.so 483
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 484
		if (!result_json.isEmpty()) {
21445 kshitij.so 485
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 486
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 487
			while (iter.hasNext()) {
22952 amit.gupta 488
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 489
				if (ai.getAvailability() <= 0)
22952 amit.gupta 490
					iter.remove();
491
			}
21445 kshitij.so 492
		}
22952 amit.gupta 493
		return responseSender.ok(dealsResponse);
21445 kshitij.so 494
	}
23816 amit.gupta 495
 
24091 tejbeer 496
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
497
	@ApiImplicitParams({
498
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
499
	@ApiOperation(value = "Get unit deal object")
500
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
501
			throws ProfitMandiBusinessException {
502
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
503
		List<Integer> tagIds = Arrays.asList(4);
504
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
505
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
506
			String categoryId = "(3 OR 6)";
507
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
508
			RestClient rc = new RestClient();
509
			Map<String, String> params = new HashMap<>();
510
			List<String> mandatoryQ = new ArrayList<>();
511
			String catalogString = "catalog" + id;
512
 
24149 amit.gupta 513
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
514
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
515
 
24091 tejbeer 516
			params.put("q", StringUtils.join(mandatoryQ, " "));
517
			params.put("fl", "*, [child parentFilter=id:catalog*]");
518
			params.put("sort", "rank_i asc, create_s desc");
519
			params.put("wt", "json");
520
			String response = null;
521
			try {
26575 amit.gupta 522
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
24091 tejbeer 523
			} catch (HttpHostConnectException e) {
524
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
525
			}
526
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
527
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 528
			dealResponse = getCatalogResponse(docs, false);
24091 tejbeer 529
		} else {
530
			return responseSender.badRequest(
531
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
532
		}
533
		return responseSender.ok(dealResponse.get(0));
534
	}
535
 
22333 amit.gupta 536
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24949 amit.gupta 537
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
25010 amit.gupta 538
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 539
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25543 amit.gupta 540
		logger.info("userInfo [{}]", userInfo);
25879 amit.gupta 541
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
542
				categoryId);
24163 amit.gupta 543
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 544
	}
25879 amit.gupta 545
 
25813 amit.gupta 546
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
547
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
548
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
549
		logger.info("userInfo [{}]", userInfo);
550
		List<DBObject> subCateogriesDisplay = this.getSubCategoriesToDisplay();
551
		return new ResponseEntity<>(subCateogriesDisplay, HttpStatus.OK);
552
	}
23816 amit.gupta 553
 
25011 amit.gupta 554
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 555
		List<DBObject> subCategories = new ArrayList<>();
556
		RestClient rc = new RestClient();
557
		Map<String, String> params = new HashMap<>();
558
		params.put("q", "categoryId_i:6");
559
		params.put("group", "true");
560
		params.put("group.field", "subCategoryId_i");
561
		params.put("wt", "json");
25126 amit.gupta 562
		params.put("rows", "50");
25014 amit.gupta 563
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 564
		String response = null;
565
		try {
26575 amit.gupta 566
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
25010 amit.gupta 567
		} catch (HttpHostConnectException e) {
568
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
569
		}
570
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
571
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
572
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 573
		for (int i = 0; i < groups.length(); i++) {
574
			JSONObject groupObject = groups.getJSONObject(i);
575
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 576
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 577
			categoryIds.add(subCategoryId);
25010 amit.gupta 578
		}
25015 amit.gupta 579
 
25010 amit.gupta 580
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 581
		AtomicInteger i = new AtomicInteger(0);
582
		categories.forEach(x -> {
25011 amit.gupta 583
			DBObject dbObject = new BasicDBObject();
584
			dbObject.put("name", x.getLabel());
585
			dbObject.put("subCategoryId", x.getId());
586
			dbObject.put("rank", i.incrementAndGet());
587
			dbObject.put("categoryId", 6);
26441 tejbeer 588
			dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
25011 amit.gupta 589
			subCategories.add(dbObject);
25010 amit.gupta 590
		});
25015 amit.gupta 591
 
25011 amit.gupta 592
		return subCategories;
25015 amit.gupta 593
 
25010 amit.gupta 594
	}
595
 
22446 amit.gupta 596
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 597
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 598
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 599
	}
23816 amit.gupta 600
 
23793 tejbeer 601
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
602
	public ResponseEntity<?> getSubcategoriesToDisplay() {
603
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
604
	}
23816 amit.gupta 605
 
22406 amit.gupta 606
	@ApiImplicitParams({
23816 amit.gupta 607
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 608
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 609
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 610
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
611
		String uri = sb.append(skus).toString();
23532 amit.gupta 612
		RestClient rc = new RestClient();
613
		String response;
614
		try {
615
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 616
		} catch (HttpHostConnectException e) {
23532 amit.gupta 617
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
618
		}
22406 amit.gupta 619
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 620
		List<Object> responseObject = new ArrayList<>();
621
		for (JsonValue j : result_json) {
23816 amit.gupta 622
			// logger.info("res " + j.asArray());
22407 amit.gupta 623
			List<Object> innerObject = new ArrayList<>();
624
			for (JsonValue jsonObject : j.asArray()) {
625
				innerObject.add(toDealObject(jsonObject.asObject()));
626
			}
627
			if (innerObject.size() > 0) {
628
				responseObject.add(innerObject);
629
			}
630
		}
22408 amit.gupta 631
		return responseSender.ok(responseObject);
22401 amit.gupta 632
	}
21339 kshitij.so 633
 
24149 amit.gupta 634
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
635
			throws ProfitMandiBusinessException {
24091 tejbeer 636
		Map<Integer, TagListing> itemTagListingMap = null;
637
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
638
		List<Integer> tagIds = Arrays.asList(4);
639
		if (docs.length() > 0) {
640
			HashSet<Integer> itemsSet = new HashSet<>();
641
			for (int i = 0; i < docs.length(); i++) {
642
				JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 643
				if (doc.has("_childDocuments_")) {
26515 amit.gupta 644
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
645
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
646
						int itemId = childItem.getInt("itemId_i");
647
						itemsSet.add(itemId);
648
					}
24091 tejbeer 649
				}
650
			}
26589 amit.gupta 651
			if (itemsSet.size() == 0) {
26573 amit.gupta 652
				return dealResponse;
653
			}
24091 tejbeer 654
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
655
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
656
		}
657
 
658
		for (int i = 0; i < docs.length(); i++) {
659
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
660
			JSONObject doc = docs.getJSONObject(i);
661
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
662
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
663
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
664
			ffdr.setTitle(doc.getString("title_s"));
24117 amit.gupta 665
			try {
666
				ffdr.setFeature(doc.getString("feature_s"));
24149 amit.gupta 667
			} catch (Exception e) {
24117 amit.gupta 668
				ffdr.setFeature(null);
24149 amit.gupta 669
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
24117 amit.gupta 670
			}
24091 tejbeer 671
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
26589 amit.gupta 672
			if (doc.has("_childDocuments_")) {
26515 amit.gupta 673
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
674
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
675
					int itemId = childItem.getInt("itemId_i");
676
					TagListing tl = itemTagListingMap.get(itemId);
677
					if (tl == null) {
678
						logger.warn("Could not find item id {}", itemId);
24091 tejbeer 679
						continue;
680
					}
26515 amit.gupta 681
					if (hotDeal) {
682
						if (!tl.isHotDeals()) {
683
							continue;
684
						}
24091 tejbeer 685
					}
26515 amit.gupta 686
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
687
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
688
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
689
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
690
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
691
						}
24091 tejbeer 692
					} else {
26515 amit.gupta 693
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
694
						fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
26846 tejbeer 695
						fdi.setMrp((double) tl.getMrp());
26515 amit.gupta 696
						fdi.setMop((float) childItem.getDouble("mop_f"));
697
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
698
						fdi.setTagId(childItem.getInt("tagId_i"));
699
						fdi.setItem_id(itemId);
26696 amit.gupta 700
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
26846 tejbeer 701
						cashBack = cashBack == null ? 0 : cashBack;
26696 amit.gupta 702
						fdi.setCashback(cashBack);
26515 amit.gupta 703
						Item item = itemRepository.selectById(itemId);
704
						// In case its tampered glass moq should be 5
705
						if (item.getCategoryId() == 10020) {
706
							fdi.setMinBuyQuantity(10);
707
						} else {
708
							fdi.setMinBuyQuantity(1);
24091 tejbeer 709
						}
26515 amit.gupta 710
						if (hotDeal || !tl.isActive()) {
26589 amit.gupta 711
 
26515 amit.gupta 712
							int totalAvailability = 0; // Using item availability
713
							// cache for now but can be
714
							// changed to
715
							// use caching later.
716
							try {
717
								ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
718
								totalAvailability = iac.getTotalAvailability();
719
								fdi.setAvailability(totalAvailability);
720
							} catch (Exception e) {
721
								continue;
722
							}
723
							if (totalAvailability <= 0) {
724
								continue;
725
							}
726
						} else {
727
							// For accessories item availability should at be ordered for Rs.1000
728
							fdi.setAvailability(100);
24091 tejbeer 729
						}
26515 amit.gupta 730
						fdi.setQuantityStep(1);
731
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
732
						fofoAvailabilityInfoMap.put(itemId, fdi);
24091 tejbeer 733
					}
734
				}
735
			}
736
			if (fofoAvailabilityInfoMap.values().size() > 0) {
737
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
738
				dealResponse.add(ffdr);
739
			}
740
		}
741
		return dealResponse;
742
 
743
	}
744
 
25968 amit.gupta 745
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter,
746
			boolean hotDeal) throws ProfitMandiBusinessException {
25879 amit.gupta 747
		Map<Integer, TagListing> itemTagListingMap = null;
748
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
749
		List<Integer> tagIds = Arrays.asList(4);
26589 amit.gupta 750
 
25968 amit.gupta 751
		itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds))
752
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
25880 amit.gupta 753
 
25879 amit.gupta 754
		for (int i = 0; i < docs.length(); i++) {
755
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
756
			JSONObject doc = docs.getJSONObject(i);
25880 amit.gupta 757
 
25879 amit.gupta 758
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
759
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
760
				int itemId = childItem.getInt("itemId_i");
761
				TagListing tl = itemTagListingMap.get(itemId);
26589 amit.gupta 762
				if (tl == null) {
25968 amit.gupta 763
					continue;
764
				}
25879 amit.gupta 765
				if (hotDeal) {
766
					if (!tl.isHotDeals()) {
767
						continue;
768
					}
769
				}
770
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
771
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
772
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
773
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
774
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
775
					}
776
				} else {
777
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
778
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
779
					fdi.setMop((float) childItem.getDouble("mop_f"));
26665 amit.gupta 780
					fdi.setMop((float) tl.getMrp());
25879 amit.gupta 781
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
782
					fdi.setTagId(childItem.getInt("tagId_i"));
783
					fdi.setItem_id(itemId);
784
					Item item = itemRepository.selectById(itemId);
785
					// In case its tampered glass moq should be 5
786
					if (item.getCategoryId() == 10020) {
787
						fdi.setMinBuyQuantity(10);
788
					} else {
789
						fdi.setMinBuyQuantity(1);
790
					}
26050 amit.gupta 791
					fdi.setAvailability(itemFilter.get(itemId));
25879 amit.gupta 792
					fdi.setQuantityStep(1);
793
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
794
					fofoAvailabilityInfoMap.put(itemId, fdi);
795
				}
796
			}
797
			if (fofoAvailabilityInfoMap.values().size() > 0) {
25880 amit.gupta 798
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
25879 amit.gupta 799
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
800
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
801
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
802
					ffdr.setTitle(doc.getString("title_s"));
803
					try {
804
						ffdr.setFeature(doc.getString("feature_s"));
805
					} catch (Exception e) {
806
						ffdr.setFeature(null);
807
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
808
					}
809
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
810
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
811
					dealResponse.add(ffdr);
812
				}
813
			}
814
		}
815
		return dealResponse;
25880 amit.gupta 816
 
25879 amit.gupta 817
	}
25967 amit.gupta 818
}