Subversion Repositories SmartDukaan

Rev

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