Subversion Repositories SmartDukaan

Rev

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