Subversion Repositories SmartDukaan

Rev

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