Subversion Repositories SmartDukaan

Rev

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