Subversion Repositories SmartDukaan

Rev

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

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