Subversion Repositories SmartDukaan

Rev

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