Subversion Repositories SmartDukaan

Rev

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