Subversion Repositories SmartDukaan

Rev

Rev 31551 | Rev 31553 | 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);
31552 tejbeer 284
 
285
		if (endPoint != null && !endPoint.trim().isEmpty()) {
286
			WebListing webListing = webListingRepository.selectByUrl(endPoint);
287
			dealResponse = this.getDealResponses(userInfo, webListing);
288
 
289
		} else {
290
 
31548 tejbeer 291
			dealResponse = this.getCatalogResponse(
292
					solrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, hotDeal),
293
					hotDeal, userInfo.getRetailerId());
294
		}
28101 amit.gupta 295
		logger.info("log me");
26889 amit.gupta 296
		return responseSender.ok(dealResponse);
297
	}
25015 amit.gupta 298
 
22319 amit.gupta 299
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 300
	@ApiImplicitParams({
31507 tejbeer 301
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 302
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 303
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
31507 tejbeer 304
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
305
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
306
			@RequestParam(value = "direction", required = false) String direction,
307
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
22319 amit.gupta 308
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 309
		String response = null;
22319 amit.gupta 310
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 311
 
22319 amit.gupta 312
		String uri = "/deals/" + userId;
23532 amit.gupta 313
		RestClient rc = new RestClient();
22272 amit.gupta 314
		Map<String, String> params = new HashMap<>();
315
		params.put("offset", offset);
316
		params.put("limit", limit);
317
		params.put("categoryId", categoryId);
318
		params.put("direction", direction);
319
		params.put("sort", sort);
320
		params.put("source", "online");
321
		params.put("filterData", filterData);
23816 amit.gupta 322
		/*
323
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
324
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
325
		 */
22272 amit.gupta 326
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 327
		try {
328
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
329
		} catch (HttpHostConnectException e) {
330
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
331
		}
22931 ashik.ali 332
 
22272 amit.gupta 333
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 334
		for (JsonValue j : result_json) {
23816 amit.gupta 335
			// logger.info("res " + j.asArray());
22272 amit.gupta 336
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 337
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 338
				innerObject.add(toDealObject(jsonObject.asObject()));
339
			}
22319 amit.gupta 340
			if (innerObject.size() > 0) {
22272 amit.gupta 341
				responseObject.add(innerObject);
342
			}
343
		}
23022 ashik.ali 344
		return responseSender.ok(responseObject);
22272 amit.gupta 345
	}
346
 
22319 amit.gupta 347
	private Object toDealObject(JsonObject jsonObject) {
348
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 349
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
350
		}
351
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
352
	}
22319 amit.gupta 353
 
354
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 355
	@ApiImplicitParams({
31507 tejbeer 356
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 357
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 358
	public ResponseEntity<?> getBrands(HttpServletRequest request,
31507 tejbeer 359
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 360
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 361
		String response = null;
22319 amit.gupta 362
		// TODO: move to properties
21356 kshitij.so 363
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 364
		RestClient rc = new RestClient();
21356 kshitij.so 365
		Map<String, String> params = new HashMap<>();
366
		params.put("category_id", category_id);
21358 kshitij.so 367
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 368
		try {
369
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
370
		} catch (HttpHostConnectException e) {
371
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
372
		}
23816 amit.gupta 373
 
22319 amit.gupta 374
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
375
		}.getType());
23022 ashik.ali 376
 
377
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 378
	}
22319 amit.gupta 379
 
380
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 381
	@ApiImplicitParams({
31507 tejbeer 382
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 383
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 384
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
385
			throws ProfitMandiBusinessException {
21445 kshitij.so 386
		String response = null;
22319 amit.gupta 387
		// TODO: move to properties
388
		String uri = "getDealById/" + id;
389
		System.out.println("Unit deal " + uri);
23532 amit.gupta 390
		RestClient rc = new RestClient();
21445 kshitij.so 391
		Map<String, String> params = new HashMap<>();
392
		DealsResponse dealsResponse = null;
23532 amit.gupta 393
		try {
394
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
395
		} catch (HttpHostConnectException e) {
396
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
397
		}
23816 amit.gupta 398
 
21445 kshitij.so 399
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 400
		if (!result_json.isEmpty()) {
21445 kshitij.so 401
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 402
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 403
			while (iter.hasNext()) {
22952 amit.gupta 404
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 405
				if (ai.getAvailability() <= 0)
22952 amit.gupta 406
					iter.remove();
407
			}
21445 kshitij.so 408
		}
22952 amit.gupta 409
		return responseSender.ok(dealsResponse);
21445 kshitij.so 410
	}
23816 amit.gupta 411
 
24091 tejbeer 412
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
413
	@ApiImplicitParams({
31507 tejbeer 414
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
24091 tejbeer 415
	@ApiOperation(value = "Get unit deal object")
416
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
27030 amit.gupta 417
			throws Exception {
24091 tejbeer 418
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
419
		List<Integer> tagIds = Arrays.asList(4);
420
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
421
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
422
			String categoryId = "(3 OR 6)";
423
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
424
			RestClient rc = new RestClient();
425
			Map<String, String> params = new HashMap<>();
426
			List<String> mandatoryQ = new ArrayList<>();
427
			String catalogString = "catalog" + id;
428
 
24149 amit.gupta 429
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
430
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
431
 
24091 tejbeer 432
			params.put("q", StringUtils.join(mandatoryQ, " "));
433
			params.put("fl", "*, [child parentFilter=id:catalog*]");
434
			params.put("sort", "rank_i asc, create_s desc");
435
			params.put("wt", "json");
436
			String response = null;
437
			try {
26575 amit.gupta 438
				response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
24091 tejbeer 439
			} catch (HttpHostConnectException e) {
440
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
441
			}
442
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
443
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26889 amit.gupta 444
			dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
24091 tejbeer 445
		} else {
446
			return responseSender.badRequest(
447
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
448
		}
449
		return responseSender.ok(dealResponse.get(0));
450
	}
451
 
22333 amit.gupta 452
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24949 amit.gupta 453
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
31507 tejbeer 454
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 455
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25543 amit.gupta 456
		logger.info("userInfo [{}]", userInfo);
25879 amit.gupta 457
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
458
				categoryId);
24163 amit.gupta 459
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 460
	}
25879 amit.gupta 461
 
31507 tejbeer 462
	@RequestMapping(value = "/fofo/brandCatalog", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
463
	public ResponseEntity<?> getBrands(HttpServletRequest request,
464
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
465
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
466
		logger.info("userInfo [{}]", userInfo);
467
 
468
		List<BrandCatalog> brandsDisplay = brandsService.getBrands(userInfo.getRetailerId(), userInfo.getEmail(),
469
				categoryId);
470
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
471
	}
472
 
25813 amit.gupta 473
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
474
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
475
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
476
		logger.info("userInfo [{}]", userInfo);
26889 amit.gupta 477
		List<DBObject> subCategoriesDisplay = this.getSubCategoriesToDisplay();
478
		return new ResponseEntity<>(subCategoriesDisplay, HttpStatus.OK);
25813 amit.gupta 479
	}
23816 amit.gupta 480
 
25011 amit.gupta 481
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 482
		List<DBObject> subCategories = new ArrayList<>();
483
		RestClient rc = new RestClient();
484
		Map<String, String> params = new HashMap<>();
485
		params.put("q", "categoryId_i:6");
486
		params.put("group", "true");
487
		params.put("group.field", "subCategoryId_i");
488
		params.put("wt", "json");
25126 amit.gupta 489
		params.put("rows", "50");
25014 amit.gupta 490
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 491
		String response = null;
492
		try {
26575 amit.gupta 493
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
25010 amit.gupta 494
		} catch (HttpHostConnectException e) {
495
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
496
		}
497
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
498
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
499
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 500
		for (int i = 0; i < groups.length(); i++) {
501
			JSONObject groupObject = groups.getJSONObject(i);
502
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 503
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 504
			categoryIds.add(subCategoryId);
25010 amit.gupta 505
		}
25015 amit.gupta 506
 
25010 amit.gupta 507
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 508
		AtomicInteger i = new AtomicInteger(0);
509
		categories.forEach(x -> {
25011 amit.gupta 510
			DBObject dbObject = new BasicDBObject();
511
			dbObject.put("name", x.getLabel());
512
			dbObject.put("subCategoryId", x.getId());
513
			dbObject.put("rank", i.incrementAndGet());
514
			dbObject.put("categoryId", 6);
26441 tejbeer 515
			dbObject.put("url", "https://images.smartdukaan.com/uploads/campaigns/" + x.getId() + ".png");
25011 amit.gupta 516
			subCategories.add(dbObject);
25010 amit.gupta 517
		});
25015 amit.gupta 518
 
25011 amit.gupta 519
		return subCategories;
25015 amit.gupta 520
 
25010 amit.gupta 521
	}
522
 
22446 amit.gupta 523
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 524
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 525
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 526
	}
23816 amit.gupta 527
 
23793 tejbeer 528
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
529
	public ResponseEntity<?> getSubcategoriesToDisplay() {
530
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
531
	}
23816 amit.gupta 532
 
22406 amit.gupta 533
	@ApiImplicitParams({
31507 tejbeer 534
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 535
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 536
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 537
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
538
		String uri = sb.append(skus).toString();
23532 amit.gupta 539
		RestClient rc = new RestClient();
540
		String response;
541
		try {
542
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 543
		} catch (HttpHostConnectException e) {
23532 amit.gupta 544
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
545
		}
22406 amit.gupta 546
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 547
		List<Object> responseObject = new ArrayList<>();
548
		for (JsonValue j : result_json) {
23816 amit.gupta 549
			// logger.info("res " + j.asArray());
22407 amit.gupta 550
			List<Object> innerObject = new ArrayList<>();
551
			for (JsonValue jsonObject : j.asArray()) {
552
				innerObject.add(toDealObject(jsonObject.asObject()));
553
			}
554
			if (innerObject.size() > 0) {
555
				responseObject.add(innerObject);
556
			}
557
		}
22408 amit.gupta 558
		return responseSender.ok(responseObject);
22401 amit.gupta 559
	}
21339 kshitij.so 560
 
31547 tejbeer 561
	@RequestMapping(value = "/partner/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
562
	public ResponseEntity<?> getPartnersListing(HttpServletRequest request) throws Exception {
563
		List<WebListing> webListings = webListingRepository.selectAllWebListingByType(Optional.of(true),
564
				WebListingType.partner);
565
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
566
		for (WebListing webListing : webListings) {
567
			webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing));
568
		}
569
		return responseSender.ok(webListings);
570
	}
571
 
31548 tejbeer 572
	private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, WebListing webListing) throws Exception {
31547 tejbeer 573
		List<Integer> webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId()).stream()
574
				.filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
575
		if (webProducts.size() == 0) {
576
			return new ArrayList<>();
577
		}
578
		RestClient rc = new RestClient();
579
		Map<String, String> params = new HashMap<>();
580
		List<String> mandatoryQ = new ArrayList<>();
581
		mandatoryQ.add(String.format(
582
				"+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} tagId_i:(%s)",
583
				StringUtils.join(TAG_IDS, " ")));
584
		params.put("q", StringUtils.join(mandatoryQ, " "));
585
		params.put("fl", "*, [child parentFilter=id:catalog*]");
586
		// params.put("sort", "create_s desc");
587
		params.put("start", String.valueOf(0));
588
		params.put("rows", String.valueOf(100));
589
		params.put("wt", "json");
590
		String response = null;
591
		try {
592
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
593
		} catch (HttpHostConnectException e) {
594
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
595
		}
596
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
597
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
598
		List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
599
		return dealResponse;
600
	}
601
 
30669 amit.gupta 602
	@Autowired
603
	private SaholicCISTableRepository saholicCISTableRepository;
604
 
27053 amit.gupta 605
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId) throws Exception {
24091 tejbeer 606
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
607
		List<Integer> tagIds = Arrays.asList(4);
26924 amit.gupta 608
		List<Integer> itemIds = new ArrayList<>();
24091 tejbeer 609
		if (docs.length() > 0) {
610
			for (int i = 0; i < docs.length(); i++) {
611
				JSONObject doc = docs.getJSONObject(i);
26589 amit.gupta 612
				if (doc.has("_childDocuments_")) {
26515 amit.gupta 613
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
614
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
615
						int itemId = childItem.getInt("itemId_i");
26924 amit.gupta 616
						itemIds.add(itemId);
26515 amit.gupta 617
					}
24091 tejbeer 618
				}
619
			}
26924 amit.gupta 620
			if (itemIds.size() == 0) {
26573 amit.gupta 621
				return dealResponse;
622
			}
24091 tejbeer 623
		}
27053 amit.gupta 624
		// get warehouse Id
27030 amit.gupta 625
		int warehouseId = fofoStoreRepository.selectByRetailerId(fofoId).getWarehouseId();
27053 amit.gupta 626
		Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = saholicInventoryService.getSaholicPOItems()
627
				.get(warehouseId);
30123 amit.gupta 628
		List<Integer> catalogIds = new ArrayList<>();
629
		for (int i = 0; i < docs.length(); i++) {
630
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
631
			JSONObject doc = docs.getJSONObject(i);
632
			catalogIds.add(doc.getInt("catalogId_i"));
633
		}
30188 amit.gupta 634
		List<CreateOfferRequest> allSchemOffers = null;
30156 amit.gupta 635
		Map<Integer, PriceCircularItemModel> priceCircularItemModelMap = new HashMap<>();
636
		if (catalogIds.size() > 0) {
637
			PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds);
30188 amit.gupta 638
			allSchemOffers = priceCircularModel.getOffers();
27053 amit.gupta 639
 
30156 amit.gupta 640
			List<PriceCircularItemModel> priceCircularItemModels = priceCircularModel.getPriceCircularItemModels();
641
			if (priceCircularItemModels != null) {
30595 tejbeer 642
				priceCircularItemModelMap = priceCircularItemModels.stream()
643
						.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x));
30156 amit.gupta 644
			}
30123 amit.gupta 645
		}
30188 amit.gupta 646
 
24091 tejbeer 647
		for (int i = 0; i < docs.length(); i++) {
648
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
649
			JSONObject doc = docs.getJSONObject(i);
30188 amit.gupta 650
			FofoCatalogResponse fofoCatalogResponse = new FofoCatalogResponse();
651
			fofoCatalogResponse.setCatalogId(doc.getInt("catalogId_i"));
652
			fofoCatalogResponse.setImageUrl(doc.getString("imageUrl_s"));
653
			fofoCatalogResponse.setTitle(doc.getString("title_s"));
30595 tejbeer 654
 
655
			List<WebOffer> webOffers = webOfferRepository.selectAllActiveOffers()
656
					.get(fofoCatalogResponse.getCatalogId());
30683 tejbeer 657
 
30617 tejbeer 658
			logger.info("webOffers {}", webOffers);
30595 tejbeer 659
			if (webOffers != null && webOffers.size() > 0) {
30597 tejbeer 660
				fofoCatalogResponse.setWebOffers(webOffers);
30595 tejbeer 661
			}
30683 tejbeer 662
 
663
			List<ComboModel> comboModels = comboModelRepository.selectByWarehouseId(warehouseId).stream()
664
					.filter(x -> x.getCatalogId() == fofoCatalogResponse.getCatalogId()).collect(Collectors.toList());
665
 
666
			for (ComboModel comboModel : comboModels) {
667
 
668
				List<ComboMappedModel> mappedModels = comboMappedModelRepository.selectByComboId(comboModel.getId());
669
 
670
				comboModel.setComboMappedModels(mappedModels);
671
 
672
			}
673
 
674
			if (comboModels != null && comboModels.size() > 0) {
675
				fofoCatalogResponse.setComboModels(comboModels);
676
			}
677
 
24117 amit.gupta 678
			try {
30188 amit.gupta 679
				fofoCatalogResponse.setFeature(doc.getString("feature_s"));
24149 amit.gupta 680
			} catch (Exception e) {
30188 amit.gupta 681
				fofoCatalogResponse.setFeature(null);
682
				logger.info("Could not find Feature_s for {}", fofoCatalogResponse.getCatalogId());
24117 amit.gupta 683
			}
30188 amit.gupta 684
			fofoCatalogResponse.setBrand(doc.getJSONArray("brand_ss").getString(0));
26589 amit.gupta 685
			if (doc.has("_childDocuments_")) {
27035 amit.gupta 686
				String modelColorClass = "grey";
27042 amit.gupta 687
				FofoAvailabilityInfo fdiAnyColour = null;
31507 tejbeer 688
				// Iterating itemIds
26515 amit.gupta 689
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
30595 tejbeer 690
					PriceCircularItemModel priceCircularItemModel = priceCircularItemModelMap
691
							.get(fofoCatalogResponse.getCatalogId());
26515 amit.gupta 692
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
693
					int itemId = childItem.getInt("itemId_i");
694
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
31507 tejbeer 695
					if (!fofoAvailabilityInfoMap.containsKey(itemId)) {
26515 amit.gupta 696
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
31507 tejbeer 697
						List<SaholicCISTable> currentAvailability = saholicCISTableRepository
698
								.selectByItemWarehouse(itemId, warehouseId);
27869 amit.gupta 699
						List<SaholicPOItem> poItemAvailability = null;
28262 amit.gupta 700
						if (poItemAvailabilityMap != null) {
27869 amit.gupta 701
							poItemAvailability = poItemAvailabilityMap.get(itemId);
702
						}
30175 amit.gupta 703
						fdi.setNlc(priceCircularItemModel == null ? 0 : priceCircularItemModel.getNetPrice());
30686 amit.gupta 704
 
705
						for (SaholicCISTable saholicCISTable : currentAvailability) {
706
							saholicCISTable.setWarehouseName(
707
									ProfitMandiConstants.WAREHOUSE_MAP.get(saholicCISTable.getWarehouseFrom()));
27062 amit.gupta 708
						}
30693 amit.gupta 709
 
710
						Map<Integer, SaholicCISTable> map = currentAvailability.stream()
30686 amit.gupta 711
								.collect(Collectors.toMap(SaholicCISTable::getWarehouseFrom, x -> x));
28262 amit.gupta 712
						if (poItemAvailability != null) {
30686 amit.gupta 713
							for (SaholicPOItem saholicPOItem : poItemAvailability) {
714
								if (map.containsKey(saholicPOItem.getWarehouseFrom())) {
715
									map.get(saholicPOItem.getWarehouseFrom())
716
											.setPopendingQty(saholicPOItem.getUnfulfilledQty());
717
								} else {
30669 amit.gupta 718
									SaholicCISTable saholicCISTable = new SaholicCISTable();
719
									saholicCISTable.setAvailability(0);
720
									saholicCISTable.setReserved(0);
721
									saholicCISTable.setItemId(itemId);
30692 amit.gupta 722
									saholicCISTable.setWarehouseId(warehouseId);
30669 amit.gupta 723
									saholicCISTable.setPopendingQty(saholicPOItem.getUnfulfilledQty());
724
									saholicCISTable.setWarehouseFrom(saholicPOItem.getWarehouseFrom());
31507 tejbeer 725
									saholicCISTable.setWarehouseName(
726
											ProfitMandiConstants.WAREHOUSE_MAP.get(saholicPOItem.getWarehouseFrom()));
30669 amit.gupta 727
									map.put(saholicPOItem.getWarehouseFrom(), saholicCISTable);
27053 amit.gupta 728
								}
729
							}
730
						}
30669 amit.gupta 731
						fdi.setSaholicCISTableList(new ArrayList<>(map.values()));
27042 amit.gupta 732
						String poColor = "grey";
27032 amit.gupta 733
						boolean active = false;
27053 amit.gupta 734
						if (currentAvailability != null && currentAvailability.stream()
30669 amit.gupta 735
								.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) > 0) {
27053 amit.gupta 736
							poColor = "green";
737
							modelColorClass = "green";
738
						} else if (poItemAvailability != null && poItemAvailability.stream()
739
								.collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty)) > 0) {
740
							if (currentAvailability != null && poItemAvailability.stream()
741
									.collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty))
742
									+ currentAvailability.stream()
31507 tejbeer 743
											.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)) <= 0) {
27042 amit.gupta 744
								poColor = "grey";
27032 amit.gupta 745
							} else {
27040 amit.gupta 746
								poColor = "yellow";
27053 amit.gupta 747
								if (modelColorClass != "green") {
27035 amit.gupta 748
									modelColorClass = poColor;
749
								}
27032 amit.gupta 750
							}
27031 amit.gupta 751
						}
27032 amit.gupta 752
						fdi.setColorClass(poColor);
26889 amit.gupta 753
						fdi.setSellingPrice(sellingPrice);
27031 amit.gupta 754
						fdi.setActive(active);
26889 amit.gupta 755
						fdi.setMrp(childItem.getDouble("mrp_f"));
26515 amit.gupta 756
						fdi.setMop((float) childItem.getDouble("mop_f"));
757
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
27042 amit.gupta 758
						if (fdi.getColor().equalsIgnoreCase("any colour")) {
27053 amit.gupta 759
							fdiAnyColour = fdi;
27042 amit.gupta 760
						}
26515 amit.gupta 761
						fdi.setTagId(childItem.getInt("tagId_i"));
762
						fdi.setItem_id(itemId);
30595 tejbeer 763
						Float cashBack = schemeService.getCatalogSchemeCashBack()
764
								.get(fofoCatalogResponse.getCatalogId());
26846 tejbeer 765
						cashBack = cashBack == null ? 0 : cashBack;
26696 amit.gupta 766
						fdi.setCashback(cashBack);
26897 amit.gupta 767
						fdi.setMinBuyQuantity(1);
28268 amit.gupta 768
						if (hotDeal) {
769
							if (currentAvailability != null) {
770
								fdi.setAvailability(currentAvailability.stream()
30669 amit.gupta 771
										.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability)));
28268 amit.gupta 772
							} else {
773
								fdi.setAvailability(0);
774
							}
775
						} else {
30595 tejbeer 776
							// Lets consider that its out of stock
28268 amit.gupta 777
							fdi.setAvailability(100);
778
							Item item = null;
30135 amit.gupta 779
							try {
28268 amit.gupta 780
								item = itemRepository.selectById(itemId);
30135 amit.gupta 781
							} catch (Exception e) {
28268 amit.gupta 782
								e.printStackTrace();
783
								continue;
784
							}
30711 amit.gupta 785
							// In case its tampered glass moq should be
28268 amit.gupta 786
							if (item.getCategoryId() == 10020) {
787
								fdi.setMinBuyQuantity(5);
788
							}
24091 tejbeer 789
						}
26515 amit.gupta 790
						fdi.setQuantityStep(1);
791
						fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
792
						fofoAvailabilityInfoMap.put(itemId, fdi);
24091 tejbeer 793
					}
794
				}
27053 amit.gupta 795
				if (fdiAnyColour != null) {
30444 amit.gupta 796
					fdiAnyColour.setColorClass(modelColorClass);
27042 amit.gupta 797
				}
24091 tejbeer 798
			}
799
			if (fofoAvailabilityInfoMap.values().size() > 0) {
27053 amit.gupta 800
				List<FofoAvailabilityInfo> availabilityList = fofoAvailabilityInfoMap.values().stream()
801
						.sorted(Comparator.comparing(FofoAvailabilityInfo::getAvailability).reversed())
802
						.collect(Collectors.toList());
30188 amit.gupta 803
				fofoCatalogResponse.setItems(availabilityList);
804
				if (priceCircularItemModelMap.containsKey(fofoCatalogResponse.getCatalogId())) {
30595 tejbeer 805
					PriceCircularItemModel priceCircularItemModel = priceCircularItemModelMap
806
							.get(fofoCatalogResponse.getCatalogId());
30193 amit.gupta 807
					if (priceCircularItemModel.getSlabPayouts() != null) {
808
						List<CreateOfferRequest> schemeOffers = new ArrayList<>();
30196 amit.gupta 809
						List<Map<Integer, Long>> slabPayouts = priceCircularItemModel.getSlabPayouts();
810
						Iterator<Map<Integer, Long>> iterator = slabPayouts.iterator();
811
						int iteratorCount = 0;
812
						while (iterator.hasNext()) {
813
							Map<Integer, Long> slabPayoutMap = iterator.next();
814
							if (slabPayoutMap != null) {
815
								schemeOffers.add(allSchemOffers.get(iteratorCount));
30193 amit.gupta 816
							} else {
30196 amit.gupta 817
								iterator.remove();
30193 amit.gupta 818
							}
30198 amit.gupta 819
							iteratorCount++;
30188 amit.gupta 820
						}
30193 amit.gupta 821
						fofoCatalogResponse.setSchemeOffers(schemeOffers);
822
					}
30188 amit.gupta 823
					fofoCatalogResponse.setPriceCircularItemModel(priceCircularItemModel);
824
				}
825
				dealResponse.add(fofoCatalogResponse);
24091 tejbeer 826
			}
27053 amit.gupta 827
		}
828
		return dealResponse;
24091 tejbeer 829
 
830
	}
831
 
25968 amit.gupta 832
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, Map<Integer, Integer> itemFilter,
31507 tejbeer 833
			boolean hotDeal) throws ProfitMandiBusinessException {
25879 amit.gupta 834
		Map<Integer, TagListing> itemTagListingMap = null;
835
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
836
		List<Integer> tagIds = Arrays.asList(4);
26589 amit.gupta 837
 
25968 amit.gupta 838
		itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemFilter.keySet(), new HashSet<>(tagIds))
839
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
25880 amit.gupta 840
 
25879 amit.gupta 841
		for (int i = 0; i < docs.length(); i++) {
842
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
843
			JSONObject doc = docs.getJSONObject(i);
25880 amit.gupta 844
 
25879 amit.gupta 845
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
846
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
847
				int itemId = childItem.getInt("itemId_i");
848
				TagListing tl = itemTagListingMap.get(itemId);
26589 amit.gupta 849
				if (tl == null) {
25968 amit.gupta 850
					continue;
851
				}
25879 amit.gupta 852
				if (hotDeal) {
853
					if (!tl.isHotDeals()) {
854
						continue;
855
					}
856
				}
857
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
858
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
859
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
860
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
861
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
862
					}
863
				} else {
864
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
865
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
866
					fdi.setMop((float) childItem.getDouble("mop_f"));
26665 amit.gupta 867
					fdi.setMop((float) tl.getMrp());
25879 amit.gupta 868
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
869
					fdi.setTagId(childItem.getInt("tagId_i"));
870
					fdi.setItem_id(itemId);
871
					Item item = itemRepository.selectById(itemId);
872
					// In case its tampered glass moq should be 5
873
					if (item.getCategoryId() == 10020) {
874
						fdi.setMinBuyQuantity(10);
875
					} else {
876
						fdi.setMinBuyQuantity(1);
877
					}
26050 amit.gupta 878
					fdi.setAvailability(itemFilter.get(itemId));
25879 amit.gupta 879
					fdi.setQuantityStep(1);
880
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
881
					fofoAvailabilityInfoMap.put(itemId, fdi);
882
				}
883
			}
884
			if (fofoAvailabilityInfoMap.values().size() > 0) {
25880 amit.gupta 885
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
25879 amit.gupta 886
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
887
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
888
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
889
					ffdr.setTitle(doc.getString("title_s"));
890
					try {
891
						ffdr.setFeature(doc.getString("feature_s"));
892
					} catch (Exception e) {
893
						ffdr.setFeature(null);
894
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
895
					}
896
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
897
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
898
					dealResponse.add(ffdr);
899
				}
900
			}
901
		}
902
		return dealResponse;
25880 amit.gupta 903
 
25879 amit.gupta 904
	}
30683 tejbeer 905
 
906
	@RequestMapping(value = "/combo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
907
	public ResponseEntity<?> getBanners(@RequestParam int catalogId, @RequestParam int warehouseId) {
908
		List<ComboModel> comboModels = comboModelRepository.selectByCatalogIdAndWarehouseId(catalogId, warehouseId);
909
		return responseSender.ok(comboModels);
910
	}
25967 amit.gupta 911
}