Subversion Repositories SmartDukaan

Rev

Rev 25011 | Rev 25014 | 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;
25010 amit.gupta 10
import java.util.concurrent.atomic.AtomicInteger;
23814 amit.gupta 11
import java.util.stream.Collectors;
21339 kshitij.so 12
 
13
import javax.servlet.http.HttpServletRequest;
14
 
22319 amit.gupta 15
import org.apache.commons.lang3.StringUtils;
23532 amit.gupta 16
import org.apache.http.conn.HttpHostConnectException;
23786 amit.gupta 17
import org.apache.logging.log4j.LogManager;
18
import org.apache.logging.log4j.Logger;
22319 amit.gupta 19
import org.json.JSONArray;
20
import org.json.JSONObject;
22273 amit.gupta 21
import org.springframework.beans.factory.annotation.Autowired;
21339 kshitij.so 22
import org.springframework.beans.factory.annotation.Value;
25010 amit.gupta 23
import org.springframework.cache.annotation.Cacheable;
21339 kshitij.so 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;
22287 amit.gupta 60
import com.spice.profitmandi.service.pricing.PricingService;
22952 amit.gupta 61
import com.spice.profitmandi.web.res.AvailabilityInfo;
21356 kshitij.so 62
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 63
import com.spice.profitmandi.web.res.DealObjectResponse;
64
import com.spice.profitmandi.web.res.DealsResponse;
22328 amit.gupta 65
import com.spice.profitmandi.web.res.FofoAvailabilityInfo;
66
import com.spice.profitmandi.web.res.FofoCatalogResponse;
21339 kshitij.so 67
 
68
import io.swagger.annotations.ApiImplicitParam;
69
import io.swagger.annotations.ApiImplicitParams;
70
import io.swagger.annotations.ApiOperation;
71
 
72
@Controller
22319 amit.gupta 73
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 74
public class DealsController {
75
 
23568 govind 76
	private static final Logger logger = LogManager.getLogger(DealsController.class);
21339 kshitij.so 77
 
78
	@Value("${python.api.host}")
79
	private String host;
23816 amit.gupta 80
 
21339 kshitij.so 81
	@Value("${python.api.port}")
82
	private int port;
23816 amit.gupta 83
 
84
	// This is now unused as we are not supporting multiple companies.
23300 amit.gupta 85
	@Value("${gadgetCops.invoice.cc}")
23816 amit.gupta 86
	private String[] ccGadgetCopInvoiceTo;
22319 amit.gupta 87
 
88
	@Autowired
89
	private PricingService pricingService;
23816 amit.gupta 90
 
22273 amit.gupta 91
	@Autowired
25010 amit.gupta 92
	private CategoryRepository categoryRepository;
93
 
94
	@Autowired
22333 amit.gupta 95
	private Mongo mongoClient;
23816 amit.gupta 96
 
22333 amit.gupta 97
	@Autowired
22361 amit.gupta 98
	private UserAccountRepository userAccountRepository;
23816 amit.gupta 99
 
22989 amit.gupta 100
	@Autowired
22931 ashik.ali 101
	private ResponseSender<?> responseSender;
23816 amit.gupta 102
 
22554 amit.gupta 103
	@Autowired
25010 amit.gupta 104
	private CategoryRepository repository;
105
 
106
	@Autowired
23814 amit.gupta 107
	private TagListingRepository tagListingRepository;
23816 amit.gupta 108
 
23814 amit.gupta 109
	@Autowired
23426 amit.gupta 110
	private ItemRepository itemRepository;
23816 amit.gupta 111
 
23786 amit.gupta 112
	@Autowired
23861 amit.gupta 113
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
114
 
115
	@Autowired
23798 amit.gupta 116
	private RoleManager roleManagerService;
23816 amit.gupta 117
 
22336 amit.gupta 118
	List<String> filterableParams = Arrays.asList("brand");
24949 amit.gupta 119
 
22319 amit.gupta 120
	@RequestMapping(value = ProfitMandiConstants.URL_DEALS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21339 kshitij.so 121
	@ApiImplicitParams({
22319 amit.gupta 122
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21339 kshitij.so 123
	@ApiOperation(value = "Get deals")
22319 amit.gupta 124
	public ResponseEntity<?> getDeals(HttpServletRequest request, @RequestParam(value = "categoryId") String categoryId,
125
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
126
			@RequestParam(value = "sort", required = false) String sort,
127
			@RequestParam(value = "direction", required = false) String direction,
23816 amit.gupta 128
			@RequestParam(value = "filterData", required = false) String filterData)
129
			throws ProfitMandiBusinessException {
22319 amit.gupta 130
		logger.info("Request " + request.getParameterMap());
21339 kshitij.so 131
		String response = null;
22319 amit.gupta 132
		int userId = (int) request.getAttribute("userId");
23816 amit.gupta 133
 
134
		// If pincode belongs to Specific warehouse marked
135
		// availability should be fetched for that warehouse only
136
		// show only skus belonging to that specific
137
		// else use normal flow
22319 amit.gupta 138
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
139
		// TODO: move to properties
140
		String uri = "/deals/" + userId;
23532 amit.gupta 141
		RestClient rc = new RestClient();
21339 kshitij.so 142
		Map<String, String> params = new HashMap<>();
143
		params.put("offset", offset);
144
		params.put("limit", limit);
145
		params.put("categoryId", categoryId);
146
		params.put("direction", direction);
147
		params.put("sort", sort);
148
		params.put("filterData", filterData);
22272 amit.gupta 149
		params.put("source", "deals");
23786 amit.gupta 150
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
22289 amit.gupta 151
			params.put("tag_ids", getCommaSeparateTags(userId));
152
		}
21356 kshitij.so 153
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 154
		try {
23816 amit.gupta 155
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
23532 amit.gupta 156
		} catch (HttpHostConnectException e) {
157
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
158
		}
23816 amit.gupta 159
 
21339 kshitij.so 160
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 161
		for (JsonValue j : result_json) {
23816 amit.gupta 162
			// logger.info("res " + j.asArray());
21339 kshitij.so 163
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 164
			for (JsonValue jsonObject : j.asArray()) {
21356 kshitij.so 165
				innerObject.add(toDealObject(jsonObject.asObject()));
21339 kshitij.so 166
			}
22319 amit.gupta 167
			if (innerObject.size() > 0) {
21339 kshitij.so 168
				responseObject.add(innerObject);
169
			}
170
		}
23022 ashik.ali 171
		return responseSender.ok(responseObject);
21339 kshitij.so 172
	}
173
 
23816 amit.gupta 174
	private String getCommaSeparateTags(int userId) {
22361 amit.gupta 175
		UserCart uc = userAccountRepository.getUserCart(userId);
176
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
22287 amit.gupta 177
		List<String> strTagIds = new ArrayList<>();
178
		for (Integer tagId : tagIds) {
179
			strTagIds.add(String.valueOf(tagId));
22273 amit.gupta 180
		}
22287 amit.gupta 181
		return String.join(",", strTagIds);
22273 amit.gupta 182
	}
183
 
22319 amit.gupta 184
	@ApiImplicitParams({
185
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
186
	@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
24091 tejbeer 187
	public ResponseEntity<?> getFofo(HttpServletRequest request,
188
			@RequestParam(value = "categoryId", required = false, defaultValue = "(3 OR 6)") String categoryId,
22319 amit.gupta 189
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
23816 amit.gupta 190
			@RequestParam(value = "sort", required = false) String sort,
191
			@RequestParam(value = "brand", required = false) String brand,
25011 amit.gupta 192
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
24946 amit.gupta 193
			@RequestParam(value = "q", required = false) String queryTerm,
24091 tejbeer 194
			@RequestParam(value = "hotDeal", required = false) boolean hotDeal) throws Throwable {
22328 amit.gupta 195
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
22319 amit.gupta 196
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
23786 amit.gupta 197
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
22361 amit.gupta 198
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
199
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(uc.getUserId());
23816 amit.gupta 200
			RestClient rc = new RestClient();
22319 amit.gupta 201
			Map<String, String> params = new HashMap<>();
22336 amit.gupta 202
			List<String> mandatoryQ = new ArrayList<>();
24974 amit.gupta 203
			if (queryTerm != null && !queryTerm.equals("null")) {
24975 amit.gupta 204
				mandatoryQ.add(String.format("+(%s)", queryTerm));
205
			} else {
206
				queryTerm = null;
24971 amit.gupta 207
			}
25011 amit.gupta 208
			if (StringUtils.isNotBlank(brand)) {
24091 tejbeer 209
				mandatoryQ.add(
210
						String.format("+(categoryId_i:%s) +(brand_ss:%s) +{!parent which=\"brand_ss:%s\"} tagId_i:(%s)",
211
								categoryId, brand, brand, StringUtils.join(tagIds, " ")));
25011 amit.gupta 212
			} else if (subCategoryId != 0) {
24949 amit.gupta 213
				mandatoryQ
214
						.add(String.format("+(subCategoryId_i:%s) +{!parent which=\"subCategoryId_i:%s\"} tagId_i:(%s)",
24875 amit.gupta 215
								subCategoryId, subCategoryId, StringUtils.join(tagIds, " ")));
24971 amit.gupta 216
 
23814 amit.gupta 217
			} else if (hotDeal) {
23816 amit.gupta 218
				mandatoryQ.add(String.format("+{!parent which=\"hot_deals_b=true\"} tagId_i:(%s)",
219
						StringUtils.join(tagIds, " ")));
22347 amit.gupta 220
			} else {
23816 amit.gupta 221
				mandatoryQ.add(
222
						String.format("+{!parent which=\"id:catalog*\"} tagId_i:(%s)", StringUtils.join(tagIds, " ")));
22336 amit.gupta 223
			}
23816 amit.gupta 224
			params.put("q", StringUtils.join(mandatoryQ, " "));
22319 amit.gupta 225
			params.put("fl", "*, [child parentFilter=id:catalog*]");
24995 amit.gupta 226
			if (queryTerm == null) {
24975 amit.gupta 227
				params.put("sort", "create_s desc");
228
			}
22319 amit.gupta 229
			params.put("start", String.valueOf(offset));
230
			params.put("rows", String.valueOf(limit));
231
			params.put("wt", "json");
23532 amit.gupta 232
			String response = null;
233
			try {
23816 amit.gupta 234
				response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
23532 amit.gupta 235
			} catch (HttpHostConnectException e) {
236
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
237
			}
22319 amit.gupta 238
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
239
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 240
			dealResponse = getCatalogResponse(docs, hotDeal);
24995 amit.gupta 241
			if (Mongo.EMAIL_BLOCKED_BRANDS.containsKey(userInfo.getEmail())) {
25010 amit.gupta 242
				dealResponse.stream()
243
						.filter(x -> Mongo.EMAIL_BLOCKED_BRANDS.get(userInfo.getEmail()).contains(x.getBrand()));
24168 amit.gupta 244
			}
22319 amit.gupta 245
		} else {
23816 amit.gupta 246
			return responseSender.badRequest(
247
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
22319 amit.gupta 248
		}
249
		return responseSender.ok(dealResponse);
250
	}
22273 amit.gupta 251
 
22319 amit.gupta 252
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 253
	@ApiImplicitParams({
22319 amit.gupta 254
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 255
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 256
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
257
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
258
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
259
			@RequestParam(value = "direction", required = false) String direction,
260
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
261
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 262
		String response = null;
22319 amit.gupta 263
		int userId = (int) request.getAttribute("userId");
22289 amit.gupta 264
 
22319 amit.gupta 265
		String uri = "/deals/" + userId;
23532 amit.gupta 266
		RestClient rc = new RestClient();
22272 amit.gupta 267
		Map<String, String> params = new HashMap<>();
268
		params.put("offset", offset);
269
		params.put("limit", limit);
270
		params.put("categoryId", categoryId);
271
		params.put("direction", direction);
272
		params.put("sort", sort);
273
		params.put("source", "online");
274
		params.put("filterData", filterData);
23816 amit.gupta 275
		/*
276
		 * if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
277
		 * params.put("tag_ids", getCommaSeparateTags(userId)); }
278
		 */
22272 amit.gupta 279
		List<Object> responseObject = new ArrayList<>();
23532 amit.gupta 280
		try {
281
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
282
		} catch (HttpHostConnectException e) {
283
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
284
		}
22931 ashik.ali 285
 
22272 amit.gupta 286
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 287
		for (JsonValue j : result_json) {
23816 amit.gupta 288
			// logger.info("res " + j.asArray());
22272 amit.gupta 289
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 290
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 291
				innerObject.add(toDealObject(jsonObject.asObject()));
292
			}
22319 amit.gupta 293
			if (innerObject.size() > 0) {
22272 amit.gupta 294
				responseObject.add(innerObject);
295
			}
296
		}
23022 ashik.ali 297
		return responseSender.ok(responseObject);
22272 amit.gupta 298
	}
299
 
22319 amit.gupta 300
	/*
24149 amit.gupta 301
	 * @RequestMapping(value = "/direct-deals", method=RequestMethod.GET,produces =
302
	 * MediaType.APPLICATION_JSON_VALUE)
22319 amit.gupta 303
	 * 
304
	 * @ApiImplicitParams({
305
	 * 
24149 amit.gupta 306
	 * @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true,
307
	 * dataType = "string", paramType = "header") }) public ResponseEntity<?>
308
	 * getDirectDeals(HttpServletRequest request, @RequestParam(value="categoryId")
309
	 * String categoryId,@RequestParam(value="offset") String offset,
22319 amit.gupta 310
	 * 
311
	 * @RequestParam(value="limit") String limit, @RequestParam(value="sort",
24149 amit.gupta 312
	 * required=false) String sort, @RequestParam(value="direction", required=false)
313
	 * String direction,
22319 amit.gupta 314
	 * 
315
	 * @RequestParam(value="filterData", required=false) String filterData ){
316
	 * 
317
	 * return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK); }
318
	 */
319
 
320
	private Object toDealObject(JsonObject jsonObject) {
321
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 322
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
323
		}
324
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
325
	}
22319 amit.gupta 326
 
327
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 328
	@ApiImplicitParams({
22319 amit.gupta 329
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 330
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 331
	public ResponseEntity<?> getBrands(HttpServletRequest request,
23816 amit.gupta 332
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
22319 amit.gupta 333
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 334
		String response = null;
22319 amit.gupta 335
		// TODO: move to properties
21356 kshitij.so 336
		String uri = ProfitMandiConstants.URL_BRANDS;
23532 amit.gupta 337
		RestClient rc = new RestClient();
21356 kshitij.so 338
		Map<String, String> params = new HashMap<>();
339
		params.put("category_id", category_id);
21358 kshitij.so 340
		List<DealBrands> dealBrandsResponse = null;
23532 amit.gupta 341
		try {
342
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
343
		} catch (HttpHostConnectException e) {
344
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
345
		}
23816 amit.gupta 346
 
22319 amit.gupta 347
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
348
		}.getType());
23022 ashik.ali 349
 
350
		return responseSender.ok(dealBrandsResponse);
21356 kshitij.so 351
	}
22319 amit.gupta 352
 
353
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 354
	@ApiImplicitParams({
22319 amit.gupta 355
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 356
	@ApiOperation(value = "Get unit deal object")
23816 amit.gupta 357
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
358
			throws ProfitMandiBusinessException {
21445 kshitij.so 359
		String response = null;
22319 amit.gupta 360
		// TODO: move to properties
361
		String uri = "getDealById/" + id;
362
		System.out.println("Unit deal " + uri);
23532 amit.gupta 363
		RestClient rc = new RestClient();
21445 kshitij.so 364
		Map<String, String> params = new HashMap<>();
365
		DealsResponse dealsResponse = null;
23532 amit.gupta 366
		try {
367
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
368
		} catch (HttpHostConnectException e) {
369
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
370
		}
23816 amit.gupta 371
 
21445 kshitij.so 372
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 373
		if (!result_json.isEmpty()) {
21445 kshitij.so 374
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
22952 amit.gupta 375
			Iterator<AvailabilityInfo> iter = dealsResponse.getAvailabilityInfo().iterator();
23816 amit.gupta 376
			while (iter.hasNext()) {
22952 amit.gupta 377
				AvailabilityInfo ai = iter.next();
23816 amit.gupta 378
				if (ai.getAvailability() <= 0)
22952 amit.gupta 379
					iter.remove();
380
			}
21445 kshitij.so 381
		}
23816 amit.gupta 382
		/*
383
		 * final ProfitMandiResponse<?> profitMandiResponse = new
384
		 * ProfitMandiResponse<>(LocalDateTime.now(),
24149 amit.gupta 385
		 * request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK,
386
		 * ResponseStatus.SUCCESS, dealsResponse);
23816 amit.gupta 387
		 */
22952 amit.gupta 388
		return responseSender.ok(dealsResponse);
21445 kshitij.so 389
	}
23816 amit.gupta 390
 
24091 tejbeer 391
	@RequestMapping(value = "/partnerdeals/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
392
	@ApiImplicitParams({
393
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
394
	@ApiOperation(value = "Get unit deal object")
395
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
396
			throws ProfitMandiBusinessException {
397
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
398
		List<Integer> tagIds = Arrays.asList(4);
399
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
400
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
401
			String categoryId = "(3 OR 6)";
402
			UserCart uc = userAccountRepository.getUserCart(userInfo.getUserId());
403
			RestClient rc = new RestClient();
404
			Map<String, String> params = new HashMap<>();
405
			List<String> mandatoryQ = new ArrayList<>();
406
			String catalogString = "catalog" + id;
407
 
24149 amit.gupta 408
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
409
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
410
 
24091 tejbeer 411
			params.put("q", StringUtils.join(mandatoryQ, " "));
412
			params.put("fl", "*, [child parentFilter=id:catalog*]");
413
			params.put("sort", "rank_i asc, create_s desc");
414
			params.put("wt", "json");
415
			String response = null;
416
			try {
417
				response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
418
			} catch (HttpHostConnectException e) {
419
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
420
			}
421
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
422
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
24149 amit.gupta 423
			dealResponse = getCatalogResponse(docs, false);
24091 tejbeer 424
		} else {
425
			return responseSender.badRequest(
426
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
427
		}
428
		return responseSender.ok(dealResponse.get(0));
429
	}
430
 
22333 amit.gupta 431
	@RequestMapping(value = "/fofo/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
25010 amit.gupta 432
	@Cacheable(value = "display", cacheManager = "thirtyMinsTimeOutCacheManager")
24949 amit.gupta 433
	public ResponseEntity<?> getBrandsToDisplay(HttpServletRequest request,
25010 amit.gupta 434
			@RequestParam(required = false, defaultValue = "0") int categoryId) throws Exception {
24163 amit.gupta 435
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
25010 amit.gupta 436
		List<DBObject> brandsDisplay = null;
437
		if (categoryId == 3) {
438
			brandsDisplay = mongoClient.getMongoBrands(userInfo.getRetailerId(), userInfo.getEmail(), categoryId);
439
		} else {
25011 amit.gupta 440
			brandsDisplay = this.getSubCategoriesToDisplay();
25010 amit.gupta 441
		}
24163 amit.gupta 442
		return new ResponseEntity<>(brandsDisplay, HttpStatus.OK);
22333 amit.gupta 443
	}
23816 amit.gupta 444
 
25011 amit.gupta 445
	private List<DBObject> getSubCategoriesToDisplay() throws Exception {
25010 amit.gupta 446
		List<DBObject> subCategories = new ArrayList<>();
447
		RestClient rc = new RestClient();
448
		Map<String, String> params = new HashMap<>();
449
		params.put("q", "categoryId_i:6");
450
		params.put("group", "true");
451
		params.put("group.field", "subCategoryId_i");
452
		params.put("wt", "json");
453
		String response = null;
454
		try {
455
			response = rc.get(SchemeType.HTTP, "dtr", 8984, "solr/demo/select", params);
456
		} catch (HttpHostConnectException e) {
457
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
458
		}
459
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("grouped");
460
		JSONArray groups = solrResponseJSONObj.getJSONObject("subCategoryId_i").getJSONArray("groups");
461
		List<Integer> categoryIds = new ArrayList<>();
462
		for(int i=0;i< groups.length();i++) {
463
			JSONObject groupObject = groups.getJSONObject(i); 
464
			int subCategoryId =  groupObject.getInt("groupValue");
465
			int quantity = groupObject.getJSONObject("doclist").getInt("numFound");
25013 amit.gupta 466
			categoryIds.add(subCategoryId);
25010 amit.gupta 467
		}
468
 
469
		List<Category> categories = categoryRepository.selectByIds(categoryIds);
470
		AtomicInteger i= new AtomicInteger(0);
471
		categories.forEach(x->{
25011 amit.gupta 472
			DBObject dbObject = new BasicDBObject();
473
			dbObject.put("name", x.getLabel());
474
			dbObject.put("subCategoryId", x.getId());
475
			dbObject.put("rank", i.incrementAndGet());
476
			dbObject.put("categoryId", 6);
477
			dbObject.put("url", "http://api.profittill.com/uploads/campaigns/" + x.getId() + ".png");
478
			subCategories.add(dbObject);
25010 amit.gupta 479
		});
480
 
25011 amit.gupta 481
		return subCategories;
482
 
25010 amit.gupta 483
	}
484
 
22446 amit.gupta 485
	@RequestMapping(value = "/banners/{bannerType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22448 amit.gupta 486
	public ResponseEntity<?> getBanners(@PathVariable String bannerType) {
22447 amit.gupta 487
		return new ResponseEntity<>(mongoClient.getBannersByType(bannerType), HttpStatus.OK);
22446 amit.gupta 488
	}
23816 amit.gupta 489
 
23793 tejbeer 490
	@RequestMapping(value = "/deals/subCategories", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
491
	public ResponseEntity<?> getSubcategoriesToDisplay() {
492
		return new ResponseEntity<>(mongoClient.getSubcategoriesToDisplay(), HttpStatus.OK);
493
	}
23816 amit.gupta 494
 
22406 amit.gupta 495
	@ApiImplicitParams({
23816 amit.gupta 496
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22401 amit.gupta 497
	@RequestMapping(value = "/deals/skus/{skus}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22931 ashik.ali 498
	public ResponseEntity<?> getDealsBySkus(@PathVariable String skus) throws ProfitMandiBusinessException {
22401 amit.gupta 499
		StringBuffer sb = new StringBuffer("/getDealsForNotification/");
500
		String uri = sb.append(skus).toString();
23532 amit.gupta 501
		RestClient rc = new RestClient();
502
		String response;
503
		try {
504
			response = rc.get(SchemeType.HTTP, host, port, uri, new HashMap<>());
23816 amit.gupta 505
		} catch (HttpHostConnectException e) {
23532 amit.gupta 506
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
507
		}
22406 amit.gupta 508
		JsonArray result_json = Json.parse(response).asArray();
22407 amit.gupta 509
		List<Object> responseObject = new ArrayList<>();
510
		for (JsonValue j : result_json) {
23816 amit.gupta 511
			// logger.info("res " + j.asArray());
22407 amit.gupta 512
			List<Object> innerObject = new ArrayList<>();
513
			for (JsonValue jsonObject : j.asArray()) {
514
				innerObject.add(toDealObject(jsonObject.asObject()));
515
			}
516
			if (innerObject.size() > 0) {
517
				responseObject.add(innerObject);
518
			}
519
		}
22408 amit.gupta 520
		return responseSender.ok(responseObject);
22401 amit.gupta 521
	}
21339 kshitij.so 522
 
24149 amit.gupta 523
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal)
524
			throws ProfitMandiBusinessException {
24091 tejbeer 525
		Map<Integer, TagListing> itemTagListingMap = null;
526
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
527
		List<Integer> tagIds = Arrays.asList(4);
528
		if (docs.length() > 0) {
529
			HashSet<Integer> itemsSet = new HashSet<>();
530
			for (int i = 0; i < docs.length(); i++) {
531
				JSONObject doc = docs.getJSONObject(i);
532
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
533
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
534
					int itemId = childItem.getInt("itemId_i");
535
					itemsSet.add(itemId);
536
				}
537
			}
538
			itemTagListingMap = tagListingRepository.selectByItemIdsAndTagIds(itemsSet, new HashSet<>(tagIds)).stream()
539
					.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
540
		}
541
 
542
		for (int i = 0; i < docs.length(); i++) {
543
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
544
			JSONObject doc = docs.getJSONObject(i);
545
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
546
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
547
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
548
			ffdr.setTitle(doc.getString("title_s"));
24117 amit.gupta 549
			try {
550
				ffdr.setFeature(doc.getString("feature_s"));
24149 amit.gupta 551
			} catch (Exception e) {
24117 amit.gupta 552
				ffdr.setFeature(null);
24149 amit.gupta 553
				logger.info("Could not find Feature_s for {}", ffdr.getCatalogId());
24117 amit.gupta 554
			}
24091 tejbeer 555
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
556
 
557
			for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
558
				JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
559
				int itemId = childItem.getInt("itemId_i");
560
				TagListing tl = itemTagListingMap.get(itemId);
561
				if (hotDeal) {
562
					if (!tl.isHotDeals()) {
563
						continue;
564
					}
565
				}
566
				float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
567
				if (fofoAvailabilityInfoMap.containsKey(itemId)) {
568
					if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
569
						fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
570
						fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
571
					}
572
				} else {
573
					FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
574
					fdi.setSellingPrice((float) childItem.getDouble("sellingPrice_f"));
575
					fdi.setMop((float) childItem.getDouble("mop_f"));
576
					fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
577
					fdi.setTagId(childItem.getInt("tagId_i"));
578
					fdi.setItem_id(itemId);
579
					Item item = itemRepository.selectById(itemId);
580
					// In case its tampered glass moq should be 5
581
					if (item.getCategoryId() == 10020) {
582
						fdi.setMinBuyQuantity(10);
583
					} else {
584
						fdi.setMinBuyQuantity(1);
585
					}
586
					if (hotDeal || !tl.isActive()) {
587
 
588
						int totalAvailability = 0; // Using item availability
589
													// cache for now but can be
590
													// changed to
591
													// use caching later.
592
						try {
593
							ItemAvailabilityCache iac = itemAvailabilityCacheRepository.selectByItemId(itemId);
594
							totalAvailability = iac.getTotalAvailability();
595
							fdi.setAvailability(totalAvailability);
596
						} catch (Exception e) {
597
							continue;
598
						}
599
						if (totalAvailability <= 0) {
600
							continue;
601
						}
602
					} else {
24149 amit.gupta 603
						// For accessories item availability should at be ordered for Rs.1000
604
						if (item.getCategoryId() == 10020 || fdi.getSellingPrice() < 100) {
605
							fdi.setAvailability((int) Math.ceil(1000 / fdi.getSellingPrice()));
606
						} else {
607
							fdi.setAvailability(10);
608
						}
24091 tejbeer 609
					}
610
					fdi.setQuantityStep(1);
611
					fdi.setMaxQuantity(Math.min(fdi.getAvailability(), 100));
612
					fofoAvailabilityInfoMap.put(itemId, fdi);
613
				}
614
			}
615
			if (fofoAvailabilityInfoMap.values().size() > 0) {
616
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
617
				dealResponse.add(ffdr);
618
			}
619
		}
620
		return dealResponse;
621
 
622
	}
623
 
21339 kshitij.so 624
}