Subversion Repositories SmartDukaan

Rev

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

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