Subversion Repositories SmartDukaan

Rev

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