Subversion Repositories SmartDukaan

Rev

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

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