Subversion Repositories SmartDukaan

Rev

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