Subversion Repositories SmartDukaan

Rev

Rev 25882 | Rev 25886 | 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;
21339 kshitij.so 5
import java.util.HashMap;
23814 amit.gupta 6
import java.util.HashSet;
22952 amit.gupta 7
import java.util.Iterator;
21339 kshitij.so 8
import java.util.List;
9
import java.util.Map;
25875 amit.gupta 10
import java.util.Optional;
25010 amit.gupta 11
import java.util.concurrent.atomic.AtomicInteger;
23814 amit.gupta 12
import java.util.stream.Collectors;
21339 kshitij.so 13
 
14
import javax.servlet.http.HttpServletRequest;
15
 
22319 amit.gupta 16
import org.apache.commons.lang3.StringUtils;
23532 amit.gupta 17
import org.apache.http.conn.HttpHostConnectException;
23786 amit.gupta 18
import org.apache.logging.log4j.LogManager;
19
import org.apache.logging.log4j.Logger;
22319 amit.gupta 20
import org.json.JSONArray;
21
import org.json.JSONObject;
22273 amit.gupta 22
import org.springframework.beans.factory.annotation.Autowired;
21339 kshitij.so 23
import org.springframework.beans.factory.annotation.Value;
24
import org.springframework.http.HttpStatus;
25
import org.springframework.http.MediaType;
26
import org.springframework.http.ResponseEntity;
27
import org.springframework.stereotype.Controller;
22286 amit.gupta 28
import org.springframework.transaction.annotation.Transactional;
21339 kshitij.so 29
import org.springframework.web.bind.annotation.PathVariable;
30
import org.springframework.web.bind.annotation.RequestMapping;
31
import org.springframework.web.bind.annotation.RequestMethod;
32
import org.springframework.web.bind.annotation.RequestParam;
33
 
34
import com.eclipsesource.json.Json;
35
import com.eclipsesource.json.JsonArray;
36
import com.eclipsesource.json.JsonObject;
37
import com.eclipsesource.json.JsonValue;
38
import com.google.gson.Gson;
21356 kshitij.so 39
import com.google.gson.reflect.TypeToken;
25010 amit.gupta 40
import com.mongodb.BasicDBObject;
24163 amit.gupta 41
import com.mongodb.DBObject;
21643 ashik.ali 42
import com.spice.profitmandi.common.enumuration.SchemeType;
21339 kshitij.so 43
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
44
import com.spice.profitmandi.common.model.ProfitMandiConstants;
22289 amit.gupta 45
import com.spice.profitmandi.common.model.UserInfo;
21643 ashik.ali 46
import com.spice.profitmandi.common.web.client.RestClient;
22319 amit.gupta 47
import com.spice.profitmandi.common.web.util.ResponseSender;
25010 amit.gupta 48
import com.spice.profitmandi.dao.entity.catalog.Category;
23426 amit.gupta 49
import com.spice.profitmandi.dao.entity.catalog.Item;
23814 amit.gupta 50
import com.spice.profitmandi.dao.entity.catalog.TagListing;
23861 amit.gupta 51
import com.spice.profitmandi.dao.entity.inventory.ItemAvailabilityCache;
22361 amit.gupta 52
import com.spice.profitmandi.dao.model.UserCart;
25010 amit.gupta 53
import com.spice.profitmandi.dao.repository.catalog.CategoryRepository;
23426 amit.gupta 54
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23814 amit.gupta 55
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
22333 amit.gupta 56
import com.spice.profitmandi.dao.repository.dtr.Mongo;
22361 amit.gupta 57
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
22989 amit.gupta 58
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
23798 amit.gupta 59
import com.spice.profitmandi.service.authentication.RoleManager;
25880 amit.gupta 60
import com.spice.profitmandi.service.inventory.AvailabilityInfo;
25882 amit.gupta 61
import com.spice.profitmandi.service.inventory.Bucket;
25880 amit.gupta 62
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
63
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
25875 amit.gupta 64
import com.spice.profitmandi.service.inventory.ItemBucketService;
25879 amit.gupta 65
import com.spice.profitmandi.service.inventory.ItemQuantityPojo;
22287 amit.gupta 66
import com.spice.profitmandi.service.pricing.PricingService;
21356 kshitij.so 67
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 68
import com.spice.profitmandi.web.res.DealObjectResponse;
69
import com.spice.profitmandi.web.res.DealsResponse;
70
 
71
import io.swagger.annotations.ApiImplicitParam;
72
import io.swagger.annotations.ApiImplicitParams;
73
import io.swagger.annotations.ApiOperation;
74
 
75
@Controller
22319 amit.gupta 76
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 77
public class DealsController {
78
 
23568 govind 79
	private static final Logger logger = LogManager.getLogger(DealsController.class);
21339 kshitij.so 80
 
81
	@Value("${python.api.host}")
82
	private String host;
23816 amit.gupta 83
 
21339 kshitij.so 84
	@Value("${python.api.port}")
85
	private int port;
23816 amit.gupta 86
 
87
	// This is now unused as we are not supporting multiple companies.
23300 amit.gupta 88
	@Value("${gadgetCops.invoice.cc}")
23816 amit.gupta 89
	private String[] ccGadgetCopInvoiceTo;
22319 amit.gupta 90
 
91
	@Autowired
92
	private PricingService pricingService;
23816 amit.gupta 93
 
22273 amit.gupta 94
	@Autowired
25010 amit.gupta 95
	private CategoryRepository categoryRepository;
96
 
97
	@Autowired
22333 amit.gupta 98
	private Mongo mongoClient;
25879 amit.gupta 99
 
25875 amit.gupta 100
	@Autowired
101
	private ItemBucketService itemBucketService;
23816 amit.gupta 102
 
22333 amit.gupta 103
	@Autowired
22361 amit.gupta 104
	private UserAccountRepository userAccountRepository;
23816 amit.gupta 105
 
22989 amit.gupta 106
	@Autowired
22931 ashik.ali 107
	private ResponseSender<?> responseSender;
23816 amit.gupta 108
 
22554 amit.gupta 109
	@Autowired
25010 amit.gupta 110
	private CategoryRepository repository;
111
 
112
	@Autowired
23814 amit.gupta 113
	private TagListingRepository tagListingRepository;
23816 amit.gupta 114
 
23814 amit.gupta 115
	@Autowired
23426 amit.gupta 116
	private ItemRepository itemRepository;
23816 amit.gupta 117
 
23786 amit.gupta 118
	@Autowired
23861 amit.gupta 119
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
120
 
121
	@Autowired
23798 amit.gupta 122
	private RoleManager roleManagerService;
23816 amit.gupta 123
 
22336 amit.gupta 124
	List<String> filterableParams = Arrays.asList("brand");
24949 amit.gupta 125
 
22319 amit.gupta 126
	@RequestMapping(value = ProfitMandiConstants.URL_DEALS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21339 kshitij.so 127
	@ApiImplicitParams({
22319 amit.gupta 128
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21339 kshitij.so 129
	@ApiOperation(value = "Get deals")
22319 amit.gupta 130
	public ResponseEntity<?> getDeals(HttpServletRequest request, @RequestParam(value = "categoryId") String categoryId,
131
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
132
			@RequestParam(value = "sort", required = false) String sort,
133
			@RequestParam(value = "direction", required = false) String direction,
23816 amit.gupta 134
			@RequestParam(value = "filterData", required = false) String filterData)
135
			throws ProfitMandiBusinessException {
22319 amit.gupta 136
		logger.info("Request " + request.getParameterMap());
21339 kshitij.so 137
		String response = null;
22319 amit.gupta 138
		int userId = (int) request.getAttribute("userId");
23816 amit.gupta 139
 
140
		// If pincode belongs to Specific warehouse marked
141
		// availability should be fetched for that warehouse only
142
		// show only skus belonging to that specific
143
		// else use normal flow
22319 amit.gupta 144
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
145
		// TODO: move to properties
146
		String uri = "/deals/" + userId;
23532 amit.gupta 147
		RestClient rc = new RestClient();
21339 kshitij.so 148
		Map<String, String> params = new HashMap<>();
149
		params.put("offset", offset);
150
		params.put("limit", limit);
151
		params.put("categoryId", categoryId);
152
		params.put("direction", direction);
153
		params.put("sort", sort);
154
		params.put("filterData", filterData);
22272 amit.gupta 155
		params.put("source", "deals");
23786 amit.gupta 156
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
22289 amit.gupta 157
			params.put("tag_ids", getCommaSeparateTags(userId));
158
		}
21356 kshitij.so 159
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 160
		try {
23816 amit.gupta 161
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
23532 amit.gupta 162
		} catch (HttpHostConnectException e) {
163
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
164
		}
23816 amit.gupta 165
 
21339 kshitij.so 166
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 167
		for (JsonValue j : result_json) {
23816 amit.gupta 168
			// logger.info("res " + j.asArray());
21339 kshitij.so 169
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 170
			for (JsonValue jsonObject : j.asArray()) {
21356 kshitij.so 171
				innerObject.add(toDealObject(jsonObject.asObject()));
21339 kshitij.so 172
			}
22319 amit.gupta 173
			if (innerObject.size() > 0) {
21339 kshitij.so 174
				responseObject.add(innerObject);
175
			}
176
		}
23022 ashik.ali 177
		return responseSender.ok(responseObject);
21339 kshitij.so 178
	}
179
 
25876 amit.gupta 180
	@RequestMapping(value = "/fofo/buckets", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25879 amit.gupta 181
	public ResponseEntity<?> getBuckets(HttpServletRequest request) throws ProfitMandiBusinessException {
25875 amit.gupta 182
		logger.info("Request " + request.getParameterMap());
183
		return responseSender.ok(itemBucketService.getBuckets(Optional.of(true)));
184
	}
25879 amit.gupta 185
 
186
	@RequestMapping(value = "/fofo/bucket", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25880 amit.gupta 187
	public ResponseEntity<?> getBucketDetails(HttpServletRequest request, @RequestParam int id)
25879 amit.gupta 188
			throws ProfitMandiBusinessException {
25880 amit.gupta 189
		List<ItemQuantityPojo> iqPojo = itemBucketService.getBucketDetails(id);
25882 amit.gupta 190
		Map<Integer, Integer> itemIdsQtyMap = iqPojo.stream().collect(Collectors.toMap(x->x.getItemId(), x->x.getQuantity()));
25879 amit.gupta 191
 
192
		RestClient rc = new RestClient();
193
		Map<String, String> params = new HashMap<>();
194
		List<String> mandatoryQ = new ArrayList<>();
25882 amit.gupta 195
		mandatoryQ.add(String.format("+{!parent which=\"id:catalog*\"} itemId_i:(%s)", StringUtils.join(itemIdsQtyMap.keySet(), " ")));
25879 amit.gupta 196
 
197
		params.put("q", StringUtils.join(mandatoryQ, " "));
198
		params.put("fl", "*, [child parentFilter=id:catalog*]");
199
 
200
		params.put("wt", "json");
201
		String response = null;
202
		try {
203
			response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
204
		} catch (HttpHostConnectException e) {
205
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
206
		}
207
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
208
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
25880 amit.gupta 209
		List<FofoCatalogResponse> dealResponse = getCatalogSingleSkuResponse(docs, false);
25885 amit.gupta 210
		dealResponse = dealResponse.stream()
211
				//.filter(x->itemIdsQtyMap.keySet().contains((int)(x.getItems().get(0).getItem_id())))
25882 amit.gupta 212
				.map(x->{
213
					FofoAvailabilityInfo fai = x.getItems().get(0);
214
					fai.setAvailability(itemIdsQtyMap.get((int)fai.getItem_id()));
215
					return x;
216
				}).collect(Collectors.toList());
217
		Bucket bucket = itemBucketService.getBuckets(Optional.of(true)).get(0);
218
		bucket.setFofoCatalogResponses(dealResponse);
219
		return responseSender.ok(bucket);
25879 amit.gupta 220
	}
221
 
23816 amit.gupta 222
	private String getCommaSeparateTags(int userId) {
22361 amit.gupta 223
		UserCart uc = userAccountRepository.getUserCart(userId);
224
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
22287 amit.gupta 225
		List<String> strTagIds = new ArrayList<>();
226
		for (Integer tagId : tagIds) {
227
			strTagIds.add(String.valueOf(tagId));
22273 amit.gupta 228
		}
22287 amit.gupta 229
		return String.join(",", strTagIds);
22273 amit.gupta 230
	}
231
 
22319 amit.gupta 232
	@ApiImplicitParams({
233
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
234
	@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24091 tejbeer 235
	public ResponseEntity<?> getFofo(HttpServletRequest request,
236
			@RequestParam(value = "categoryId", required = false, defaultValue = "(3 OR 6)") String categoryId,
22319 amit.gupta 237
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
23816 amit.gupta 238
			@RequestParam(value = "sort", required = false) String sort,
239
			@RequestParam(value = "brand", required = false) String brand,
25011 amit.gupta 240
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
24946 amit.gupta 241
			@RequestParam(value = "q", required = false) String queryTerm,
24091 tejbeer 242
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
22328 amit.gupta 243
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
22319 amit.gupta 244
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
23786 amit.gupta 245
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
25879 amit.gupta 246
			// UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
25389 tejbeer 247
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getRetailerId());
23816 amit.gupta 248
			RestClient rc = new RestClient();
22319 amit.gupta 249
			Map<String, String> params = new HashMap<>();
22336 amit.gupta 250
			List<String> mandatoryQ = new ArrayList<>();
24974 amit.gupta 251
			if (queryTerm != null && !queryTerm.equals("null")) {
24975 amit.gupta 252
				mandatoryQ.add(String.format("+(%s)", queryTerm));
253
			} else {
254
				queryTerm = null;
24971 amit.gupta 255
			}
25015 amit.gupta 256
			if (subCategoryId != 0) {
24949 amit.gupta 257
				mandatoryQ
258
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
24875 amit.gupta 259
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
23814 amit.gupta 260
			} else if (hotDeal) {
23816 amit.gupta 261
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
262
						StringUtils.join(tagIds, " ")));
25015 amit.gupta 263
 
264
			} else if (StringUtils.isNotBlank(brand)) {
265
				mandatoryQ.add(
266
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
267
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
268
 
22347 amit.gupta 269
			} else {
23816 amit.gupta 270
				mandatoryQ.add(
271
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
22336 amit.gupta 272
			}
23816 amit.gupta 273
			params.put("q", StringUtils.join(mandatoryQ, " "));
22319 amit.gupta 274
			params.put("fl", "*, [child parentFilter=id:catalog*]");
24995 amit.gupta 275
			if (queryTerm == null) {
24975 amit.gupta 276
				params.put("sort", "create_s desc");
277
			}
22319 amit.gupta 278
			params.put("start", String.valueOf(offset));
279
			params.put("rows", String.valueOf(limit));
280
			params.put("wt", "json");
23532 amit.gupta 281
			String response = null;
282
			try {
23816 amit.gupta 283
				response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
23532 amit.gupta 284
			} catch (HttpHostConnectException e) {
285
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
286
			}
22319 amit.gupta 287
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
288
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 289
			dealResponse = getCatalogResponse(docs, hotDeal);
25561 amit.gupta 290
			if (Mongo.PARTNER_BLoCKED_BRANDS.containsKey(userInfo.getEmail())) {
25010 amit.gupta 291
				dealResponse.stream()
25561 amit.gupta 292
						.filter(x -> Mongo.PARTNER_BLoCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()));
24168 amit.gupta 293
			}
22319 amit.gupta 294
		} else {
23816 amit.gupta 295
			return responseSender.badRequest(
296
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
22319 amit.gupta 297
		}
298
		return responseSender.ok(dealResponse);
299
	}
22273 amit.gupta 300
 
22319 amit.gupta 301
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 302
	@ApiImplicitParams({
22319 amit.gupta 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,
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 {
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({
22319 amit.gupta 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,
23816 amit.gupta 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({
22319 amit.gupta 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({
416
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
417
	@ApiOperation(value = "Get unit deal object")
418
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
419
			throws ProfitMandiBusinessException {
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 {
440
				response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
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");
24149 amit.gupta 446
			dealResponse = getCatalogResponse(docs, false);
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,
25010 amit.gupta 456
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 457
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25543 amit.gupta 458
		logger.info("userInfo [{}]", userInfo);
25879 amit.gupta 459
		List<DBObject> brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(),
460
				categoryId);
24163 amit.gupta 461
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 462
	}
25879 amit.gupta 463
 
25813 amit.gupta 464
	@RequestMapping(value = "/fofo/accessory/all-categories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
465
	public ResponseEntity<?> getSubCategoriesToDisplay(HttpServletRequest request) throws Exception {
466
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
467
		logger.info("userInfo [{}]", userInfo);
468
		List<DBObject> subCateogriesDisplay = this.getSubCategoriesToDisplay();
469
		return new ResponseEntity<>(subCateogriesDisplay, HttpStatus.OK);
470
	}
23816 amit.gupta 471
 
25011 amit.gupta 472
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 473
		List<DBObject> subCategories = new ArrayList<>();
474
		RestClient rc = new RestClient();
475
		Map<String, String> params = new HashMap<>();
476
		params.put("q", "categoryId_i:6");
477
		params.put("group", "true");
478
		params.put("group.field", "subCategoryId_i");
479
		params.put("wt", "json");
25126 amit.gupta 480
		params.put("rows", "50");
25014 amit.gupta 481
		params.put("fl", "subCategoryId_i");
25010 amit.gupta 482
		String response = null;
483
		try {
484
			response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
485
		} catch (HttpHostConnectException e) {
486
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
487
		}
488
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
489
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
490
		List<Integer> categoryIds = new ArrayList<>();
25015 amit.gupta 491
		for (int i = 0; i < groups.length(); i++) {
492
			JSONObject groupObject = groups.getJSONObject(i);
493
			int subCategoryId = groupObject.getInt("groupValue");
25010 amit.gupta 494
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 495
			categoryIds.add(subCategoryId);
25010 amit.gupta 496
		}
25015 amit.gupta 497
 
25010 amit.gupta 498
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
25015 amit.gupta 499
		AtomicInteger i = new AtomicInteger(0);
500
		categories.forEach(x -> {
25011 amit.gupta 501
			DBObject dbObject = new BasicDBObject();
502
			dbObject.put("name", x.getLabel());
503
			dbObject.put("subCategoryId", x.getId());
504
			dbObject.put("rank", i.incrementAndGet());
505
			dbObject.put("categoryId", 6);
506
			dbObject.put("url", "http://api.profittill.com/uploads/campaigns/" + x.getId() + ".png");
507
			subCategories.add(dbObject);
25010 amit.gupta 508
		});
25015 amit.gupta 509
 
25011 amit.gupta 510
		return subCategories;
25015 amit.gupta 511
 
25010 amit.gupta 512
	}
513
 
22446 amit.gupta 514
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 515
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 516
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 517
	}
23816 amit.gupta 518
 
23793 tejbeer 519
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
520
	public ResponseEntity<?> getSubcategoriesToDisplay() {
521
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
522
	}
23816 amit.gupta 523
 
22406 amit.gupta 524
	@ApiImplicitParams({
23816 amit.gupta 525
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 526
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 527
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 528
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
529
		String uri = sb.append(skus).toString();
23532 amit.gupta 530
		RestClient rc = new RestClient();
531
		String response;
532
		try {
533
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 534
		} catch (HttpHostConnectException e) {
23532 amit.gupta 535
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
536
		}
22406 amit.gupta 537
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 538
		List<Object> responseObject = new ArrayList<>();
539
		for (JsonValue j : result_json) {
23816 amit.gupta 540
			// logger.info("res " + j.asArray());
22407 amit.gupta 541
			List<Object> innerObject = new ArrayList<>();
542
			for (JsonValue jsonObject : j.asArray()) {
543
				innerObject.add(toDealObject(jsonObject.asObject()));
544
			}
545
			if (innerObject.size() > 0) {
546
				responseObject.add(innerObject);
547
			}
548
		}
22408 amit.gupta 549
		return responseSender.ok(responseObject);
22401 amit.gupta 550
	}
21339 kshitij.so 551
 
24149 amit.gupta 552
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
553
			throws ProfitMandiBusinessException {
24091 tejbeer 554
		Map<Integer, TagListing> itemTagListingMap = null;
555
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
556
		List<Integer> tagIds = Arrays.asList(4);
557
		if (docs.length() > 0) {
558
			HashSet<Integer> itemsSet = new HashSet<>();
559
			for (int i = 0; i < docs.length(); i++) {
560
				JSONObject doc = docs.getJSONObject(i);
561
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
562
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
563
					int itemId = childItem.getInt("itemId_i");
564
					itemsSet.add(itemId);
565
				}
566
			}
567
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
568
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
569
		}
570
 
571
		for (int i = 0; i < docs.length(); i++) {
572
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
573
			JSONObject doc = docs.getJSONObject(i);
574
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
575
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
576
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
577
			ffdr.setTitle(doc.getString("title_s"));
24117 amit.gupta 578
			try {
579
				ffdr.setFeature(doc.getString("feature_s"));
24149 amit.gupta 580
			} catch (Exception e) {
24117 amit.gupta 581
				ffdr.setFeature(null);
24149 amit.gupta 582
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
24117 amit.gupta 583
			}
24091 tejbeer 584
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
585
 
586
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
587
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
588
				int itemId = childItem.getInt("itemId_i");
589
				TagListing tl = itemTagListingMap.get(itemId);
590
				if (hotDeal) {
591
					if (!tl.isHotDeals()) {
592
						continue;
593
					}
594
				}
595
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
596
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
597
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
598
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
599
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
600
					}
601
				} else {
602
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
603
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
604
					fdi.setMop((float) childItem.getDouble("mop_f"));
605
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
606
					fdi.setTagId(childItem.getInt("tagId_i"));
607
					fdi.setItem_id(itemId);
608
					Item item = itemRepository.selectById(itemId);
609
					// In case its tampered glass moq should be 5
610
					if (item.getCategoryId() == 10020) {
611
						fdi.setMinBuyQuantity(10);
612
					} else {
613
						fdi.setMinBuyQuantity(1);
614
					}
615
					if (hotDeal || !tl.isActive()) {
616
 
617
						int totalAvailability = 0; // Using item availability
618
													// cache for now but can be
619
													// changed to
620
													// use caching later.
621
						try {
622
							ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
623
							totalAvailability = iac.getTotalAvailability();
624
							fdi.setAvailability(totalAvailability);
625
						} catch (Exception e) {
626
							continue;
627
						}
628
						if (totalAvailability <= 0) {
629
							continue;
630
						}
631
					} else {
24149 amit.gupta 632
						// For accessories item availability should at be ordered for Rs.1000
25276 amit.gupta 633
						fdi.setAvailability(100);
24091 tejbeer 634
					}
635
					fdi.setQuantityStep(1);
636
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
637
					fofoAvailabilityInfoMap.put(itemId, fdi);
638
				}
639
			}
640
			if (fofoAvailabilityInfoMap.values().size() > 0) {
641
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
642
				dealResponse.add(ffdr);
643
			}
644
		}
645
		return dealResponse;
646
 
647
	}
648
 
25879 amit.gupta 649
	private List<FofoCatalogResponse> getCatalogSingleSkuResponse(JSONArray docs, boolean hotDeal)
650
			throws ProfitMandiBusinessException {
651
		Map<Integer, TagListing> itemTagListingMap = null;
652
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
653
		List<Integer> tagIds = Arrays.asList(4);
654
		if (docs.length() > 0) {
655
			HashSet<Integer> itemsSet = new HashSet<>();
656
			for (int i = 0; i < docs.length(); i++) {
657
				JSONObject doc = docs.getJSONObject(i);
658
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
659
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
660
					int itemId = childItem.getInt("itemId_i");
661
					itemsSet.add(itemId);
662
				}
663
			}
664
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
665
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
666
		}
25880 amit.gupta 667
 
25879 amit.gupta 668
		for (int i = 0; i < docs.length(); i++) {
669
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
670
			JSONObject doc = docs.getJSONObject(i);
25880 amit.gupta 671
 
25879 amit.gupta 672
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
673
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
674
				int itemId = childItem.getInt("itemId_i");
675
				TagListing tl = itemTagListingMap.get(itemId);
676
				if (hotDeal) {
677
					if (!tl.isHotDeals()) {
678
						continue;
679
					}
680
				}
681
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
682
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
683
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
684
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
685
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
686
					}
687
				} else {
688
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
689
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
690
					fdi.setMop((float) childItem.getDouble("mop_f"));
691
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
692
					fdi.setTagId(childItem.getInt("tagId_i"));
693
					fdi.setItem_id(itemId);
694
					Item item = itemRepository.selectById(itemId);
695
					// In case its tampered glass moq should be 5
696
					if (item.getCategoryId() == 10020) {
697
						fdi.setMinBuyQuantity(10);
698
					} else {
699
						fdi.setMinBuyQuantity(1);
700
					}
701
					if (hotDeal || !tl.isActive()) {
25880 amit.gupta 702
 
25879 amit.gupta 703
						int totalAvailability = 0; // Using item availability
704
						// cache for now but can be
705
						// changed to
706
						// use caching later.
707
						try {
708
							ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
709
							totalAvailability = iac.getTotalAvailability();
710
							fdi.setAvailability(totalAvailability);
711
						} catch (Exception e) {
712
							continue;
713
						}
714
						if (totalAvailability <= 0) {
715
							continue;
716
						}
717
					} else {
718
						// For accessories item availability should at be ordered for Rs.1000
719
						fdi.setAvailability(100);
720
					}
721
					fdi.setQuantityStep(1);
722
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
723
					fofoAvailabilityInfoMap.put(itemId, fdi);
724
				}
725
			}
726
			if (fofoAvailabilityInfoMap.values().size() > 0) {
25880 amit.gupta 727
				for (FofoAvailabilityInfo fofoAvailabilityInfo : fofoAvailabilityInfoMap.values()) {
25879 amit.gupta 728
					FofoCatalogResponse ffdr = new FofoCatalogResponse();
729
					ffdr.setCatalogId(doc.getInt("catalogId_i"));
730
					ffdr.setImageUrl(doc.getString("imageUrl_s"));
731
					ffdr.setTitle(doc.getString("title_s"));
732
					try {
733
						ffdr.setFeature(doc.getString("feature_s"));
734
					} catch (Exception e) {
735
						ffdr.setFeature(null);
736
						logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
737
					}
738
					ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
739
					ffdr.setItems(Arrays.asList(fofoAvailabilityInfo));
740
					dealResponse.add(ffdr);
741
				}
742
			}
743
		}
744
		return dealResponse;
25880 amit.gupta 745
 
25879 amit.gupta 746
	}
747
 
21339 kshitij.so 748
}