Subversion Repositories SmartDukaan

Rev

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

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