Subversion Repositories SmartDukaan

Rev

Rev 22328 | Rev 22333 | 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.time.LocalDateTime;
4
import java.util.ArrayList;
5
import java.util.HashMap;
6
import java.util.List;
7
import java.util.Map;
8
 
9
import javax.servlet.http.HttpServletRequest;
10
 
22319 amit.gupta 11
import org.apache.commons.lang3.StringUtils;
12
import org.json.JSONArray;
13
import org.json.JSONObject;
21339 kshitij.so 14
import org.slf4j.Logger;
15
import org.slf4j.LoggerFactory;
22273 amit.gupta 16
import org.springframework.beans.factory.annotation.Autowired;
21339 kshitij.so 17
import org.springframework.beans.factory.annotation.Value;
18
import org.springframework.http.HttpStatus;
19
import org.springframework.http.MediaType;
20
import org.springframework.http.ResponseEntity;
21
import org.springframework.stereotype.Controller;
22286 amit.gupta 22
import org.springframework.transaction.annotation.Transactional;
21339 kshitij.so 23
import org.springframework.web.bind.annotation.PathVariable;
24
import org.springframework.web.bind.annotation.RequestMapping;
25
import org.springframework.web.bind.annotation.RequestMethod;
26
import org.springframework.web.bind.annotation.RequestParam;
27
 
28
import com.eclipsesource.json.Json;
29
import com.eclipsesource.json.JsonArray;
30
import com.eclipsesource.json.JsonObject;
31
import com.eclipsesource.json.JsonValue;
32
import com.google.gson.Gson;
21356 kshitij.so 33
import com.google.gson.reflect.TypeToken;
21643 ashik.ali 34
import com.spice.profitmandi.common.enumuration.SchemeType;
21339 kshitij.so 35
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
36
import com.spice.profitmandi.common.model.ProfitMandiConstants;
21740 ashik.ali 37
import com.spice.profitmandi.common.model.ProfitMandiResponse;
38
import com.spice.profitmandi.common.model.ResponseStatus;
22289 amit.gupta 39
import com.spice.profitmandi.common.model.UserInfo;
21643 ashik.ali 40
import com.spice.profitmandi.common.web.client.RestClient;
22319 amit.gupta 41
import com.spice.profitmandi.common.web.util.ResponseSender;
22289 amit.gupta 42
import com.spice.profitmandi.dao.enumuration.dtr.RoleType;
22287 amit.gupta 43
import com.spice.profitmandi.service.pricing.PricingService;
21356 kshitij.so 44
import com.spice.profitmandi.web.res.DealBrands;
21339 kshitij.so 45
import com.spice.profitmandi.web.res.DealObjectResponse;
46
import com.spice.profitmandi.web.res.DealsResponse;
22328 amit.gupta 47
import com.spice.profitmandi.web.res.FofoAvailabilityInfo;
48
import com.spice.profitmandi.web.res.FofoCatalogResponse;
21339 kshitij.so 49
 
50
import io.swagger.annotations.ApiImplicitParam;
51
import io.swagger.annotations.ApiImplicitParams;
52
import io.swagger.annotations.ApiOperation;
53
 
54
@Controller
22319 amit.gupta 55
@Transactional(rollbackFor = Throwable.class)
21339 kshitij.so 56
public class DealsController {
57
 
22319 amit.gupta 58
	private static final Logger logger = LoggerFactory.getLogger(DealsController.class);
21339 kshitij.so 59
 
60
	@Value("${python.api.host}")
61
	private String host;
62
	@Value("${python.api.port}")
63
	private int port;
22319 amit.gupta 64
 
65
	@Autowired
66
	private PricingService pricingService;
22273 amit.gupta 67
 
68
	@Autowired
22319 amit.gupta 69
	ResponseSender<?> responseSender;
21339 kshitij.so 70
 
22319 amit.gupta 71
	@RequestMapping(value = ProfitMandiConstants.URL_DEALS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21339 kshitij.so 72
	@ApiImplicitParams({
22319 amit.gupta 73
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21339 kshitij.so 74
	@ApiOperation(value = "Get deals")
22319 amit.gupta 75
	public ResponseEntity<?> getDeals(HttpServletRequest request, @RequestParam(value = "categoryId") String categoryId,
76
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
77
			@RequestParam(value = "sort", required = false) String sort,
78
			@RequestParam(value = "direction", required = false) String direction,
79
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
80
		logger.info("Request " + request.getParameterMap());
21339 kshitij.so 81
		String response = null;
22319 amit.gupta 82
		int userId = (int) request.getAttribute("userId");
83
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
84
		// TODO: move to properties
85
		String uri = "/deals/" + userId;
86
		RestClient rc = new RestClient(SchemeType.HTTP, host, port);
21339 kshitij.so 87
		Map<String, String> params = new HashMap<>();
88
		params.put("offset", offset);
89
		params.put("limit", limit);
90
		params.put("categoryId", categoryId);
91
		params.put("direction", direction);
92
		params.put("sort", sort);
93
		params.put("filterData", filterData);
22272 amit.gupta 94
		params.put("source", "deals");
22319 amit.gupta 95
		if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
22289 amit.gupta 96
			params.put("tag_ids", getCommaSeparateTags(userId));
97
		}
21356 kshitij.so 98
		List<Object> responseObject = new ArrayList<>();
21339 kshitij.so 99
		try {
100
			response = rc.get(uri, params);
101
		} catch (Exception | ProfitMandiBusinessException e) {
22319 amit.gupta 102
			logger.error("Unable to get deals", e);
103
			final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
104
					request.getRequestURL().toString(), HttpStatus.INTERNAL_SERVER_ERROR.toString(),
105
					HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, responseObject);
106
			return new ResponseEntity<>(profitMandiResponse, HttpStatus.INTERNAL_SERVER_ERROR);
21339 kshitij.so 107
		}
108
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 109
		for (JsonValue j : result_json) {
110
			logger.info("res " + j.asArray());
21339 kshitij.so 111
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 112
			for (JsonValue jsonObject : j.asArray()) {
21356 kshitij.so 113
				innerObject.add(toDealObject(jsonObject.asObject()));
21339 kshitij.so 114
			}
22319 amit.gupta 115
			if (innerObject.size() > 0) {
21339 kshitij.so 116
				responseObject.add(innerObject);
117
			}
118
		}
22319 amit.gupta 119
		final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
120
				request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS,
121
				responseObject);
122
		return new ResponseEntity<>(profitMandiResponse, HttpStatus.OK);
21339 kshitij.so 123
	}
124
 
22319 amit.gupta 125
	private String getCommaSeparateTags(int userId) throws Throwable {
22287 amit.gupta 126
		List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userId);
127
		List<String> strTagIds = new ArrayList<>();
128
		for (Integer tagId : tagIds) {
129
			strTagIds.add(String.valueOf(tagId));
22273 amit.gupta 130
		}
22287 amit.gupta 131
		return String.join(",", strTagIds);
22273 amit.gupta 132
	}
133
 
22319 amit.gupta 134
	@ApiImplicitParams({
135
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
136
	@RequestMapping(value = "/fofo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
137
	public ResponseEntity<?> getFofo(HttpServletRequest request, @RequestParam(value = "categoryId") String categoryId,
138
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
139
			@RequestParam(value = "sort", required = false) String sort) throws Throwable {
22328 amit.gupta 140
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
22319 amit.gupta 141
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
142
		if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
143
			List<Integer> tagIds = pricingService.getTagsIdsByRetailerId(userInfo.getUserId());
144
			RestClient rc  = new RestClient(SchemeType.HTTP, "dtr", 8984);
145
			Map<String, String> params = new HashMap<>();
146
			params.put("q", String.format("{!parent which=\"id:catalog*\"}tagId_i:(%s)", StringUtils.join(tagIds, " OR ")));
147
			params.put("fl", "*, [child parentFilter=id:catalog*]");
148
			params.put("sort", "rank_i asc");
149
			params.put("start", String.valueOf(offset));
150
			params.put("rows", String.valueOf(limit));
151
			params.put("wt", "json");
22330 amit.gupta 152
			logger.info(rc.getUrl());
22319 amit.gupta 153
			String response  =rc.get("solr/demo/select", params);
154
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
155
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
156
			for(int i=0; i < docs.length(); i++) {
22328 amit.gupta 157
				Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
22319 amit.gupta 158
				JSONObject doc = docs.getJSONObject(i);
22328 amit.gupta 159
				FofoCatalogResponse ffdr = new FofoCatalogResponse();
22319 amit.gupta 160
				ffdr.setCatalogId(doc.getInt("catalogId_i"));
161
				ffdr.setImageUrl(doc.getString("imageUrl_s"));
162
				ffdr.setTitle(doc.getString("title_s"));
22323 amit.gupta 163
				for(int j=0; j< doc.getJSONArray("_childDocuments_").length(); j++) {
164
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
22319 amit.gupta 165
					int itemId = childItem.getInt("itemId_i");
166
					float sellingPrice = (float)childItem.getDouble("sellingPrice_f");
22328 amit.gupta 167
					if(fofoAvailabilityInfoMap.containsKey(itemId)) {
168
						if(fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
169
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
170
							fofoAvailabilityInfoMap.get(itemId).setMop((float)childItem.getDouble("mop_f"));
22319 amit.gupta 171
						} 
172
					} else {
22328 amit.gupta 173
							FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
22319 amit.gupta 174
							fdi.setSellingPrice((float)childItem.getDouble("sellingPrice_f"));
175
							fdi.setMop((float)childItem.getDouble("mop_f"));
22324 amit.gupta 176
							fdi.setColor(childItem.has("color_s")?childItem.getString("color_s"): "");
22319 amit.gupta 177
							fdi.setTagId(childItem.getInt("tagId_i"));
22328 amit.gupta 178
							fdi.setItem_id(itemId);
179
							fdi.setAvailability(100);
180
							fdi.setQuantityStep(1);
181
							fdi.setMinBuyQuantity(1);
182
							fdi.setMaxQuantity(100);
183
							fofoAvailabilityInfoMap.put(itemId, fdi);
22319 amit.gupta 184
					}
185
				}
22328 amit.gupta 186
				ffdr.setItems(new ArrayList<FofoAvailabilityInfo>(fofoAvailabilityInfoMap.values()));
22319 amit.gupta 187
				dealResponse.add(ffdr);
188
			}
189
 
190
		} else {
191
			return responseSender.badRequest(new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
192
		}
193
		return responseSender.ok(dealResponse);
194
	}
22273 amit.gupta 195
 
22319 amit.gupta 196
	@RequestMapping(value = "/online-deals", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
22272 amit.gupta 197
	@ApiImplicitParams({
22319 amit.gupta 198
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
22272 amit.gupta 199
	@ApiOperation(value = "Get online deals")
22319 amit.gupta 200
	public ResponseEntity<?> getOnlineDeals(HttpServletRequest request,
201
			@RequestParam(value = "categoryId") String categoryId, @RequestParam(value = "offset") String offset,
202
			@RequestParam(value = "limit") String limit, @RequestParam(value = "sort", required = false) String sort,
203
			@RequestParam(value = "direction", required = false) String direction,
204
			@RequestParam(value = "filterData", required = false) String filterData) throws Throwable {
205
		logger.info("Request " + request.getParameterMap());
22272 amit.gupta 206
		String response = null;
22319 amit.gupta 207
		int userId = (int) request.getAttribute("userId");
208
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
22289 amit.gupta 209
 
22319 amit.gupta 210
		String uri = "/deals/" + userId;
211
		RestClient rc = new RestClient(SchemeType.HTTP, host, port);
22272 amit.gupta 212
		Map<String, String> params = new HashMap<>();
213
		params.put("offset", offset);
214
		params.put("limit", limit);
215
		params.put("categoryId", categoryId);
216
		params.put("direction", direction);
217
		params.put("sort", sort);
218
		params.put("source", "online");
219
		params.put("filterData", filterData);
22319 amit.gupta 220
		if (userInfo.getRoleNames().contains(RoleType.FOFO.toString())) {
22289 amit.gupta 221
			params.put("tag_ids", getCommaSeparateTags(userId));
222
		}
22272 amit.gupta 223
		List<Object> responseObject = new ArrayList<>();
224
		try {
225
			response = rc.get(uri, params);
226
		} catch (Exception | ProfitMandiBusinessException e) {
22319 amit.gupta 227
			logger.error("Unable to get deals", e);
228
			final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
229
					request.getRequestURL().toString(), HttpStatus.INTERNAL_SERVER_ERROR.toString(),
230
					HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, responseObject);
231
			return new ResponseEntity<>(profitMandiResponse, HttpStatus.INTERNAL_SERVER_ERROR);
22272 amit.gupta 232
		}
233
		JsonArray result_json = Json.parse(response).asArray();
22319 amit.gupta 234
		for (JsonValue j : result_json) {
235
			logger.info("res " + j.asArray());
22272 amit.gupta 236
			List<Object> innerObject = new ArrayList<>();
22319 amit.gupta 237
			for (JsonValue jsonObject : j.asArray()) {
22272 amit.gupta 238
				innerObject.add(toDealObject(jsonObject.asObject()));
239
			}
22319 amit.gupta 240
			if (innerObject.size() > 0) {
22272 amit.gupta 241
				responseObject.add(innerObject);
242
			}
243
		}
22319 amit.gupta 244
		final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
245
				request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS,
246
				responseObject);
247
		return new ResponseEntity<>(profitMandiResponse, HttpStatus.OK);
22272 amit.gupta 248
	}
249
 
22319 amit.gupta 250
	/*
251
	 * @RequestMapping(value = "/direct-deals",
252
	 * method=RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
253
	 * 
254
	 * @ApiImplicitParams({
255
	 * 
256
	 * @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required =
257
	 * true, dataType = "string", paramType = "header") }) public
258
	 * ResponseEntity<?> getDirectDeals(HttpServletRequest
259
	 * request, @RequestParam(value="categoryId") String
260
	 * categoryId,@RequestParam(value="offset") String offset,
261
	 * 
262
	 * @RequestParam(value="limit") String limit, @RequestParam(value="sort",
263
	 * required=false) String sort, @RequestParam(value="direction",
264
	 * required=false) String direction,
265
	 * 
266
	 * @RequestParam(value="filterData", required=false) String filterData ){
267
	 * 
268
	 * return new ResponseEntity<>(profitMandiResponse,HttpStatus.OK); }
269
	 */
270
 
271
	private Object toDealObject(JsonObject jsonObject) {
272
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
21339 kshitij.so 273
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
274
		}
275
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
276
	}
22319 amit.gupta 277
 
278
	@RequestMapping(value = ProfitMandiConstants.URL_BRANDS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21356 kshitij.so 279
	@ApiImplicitParams({
22319 amit.gupta 280
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21356 kshitij.so 281
	@ApiOperation(value = "Get brand list and count for category")
22319 amit.gupta 282
	public ResponseEntity<?> getBrands(HttpServletRequest request,
283
			@RequestParam(value = "category_id") String category_id) {
284
		logger.info("Request " + request.getParameterMap());
21356 kshitij.so 285
		String response = null;
22319 amit.gupta 286
		// TODO: move to properties
21356 kshitij.so 287
		String uri = ProfitMandiConstants.URL_BRANDS;
22319 amit.gupta 288
		RestClient rc = new RestClient(SchemeType.HTTP, host, port);
21356 kshitij.so 289
		Map<String, String> params = new HashMap<>();
290
		params.put("category_id", category_id);
21358 kshitij.so 291
		List<DealBrands> dealBrandsResponse = null;
21356 kshitij.so 292
		try {
293
			response = rc.get(uri, params);
294
		} catch (Exception | ProfitMandiBusinessException e) {
22319 amit.gupta 295
			logger.error("Unable to get deals", e);
296
			final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
297
					request.getRequestURL().toString(), HttpStatus.INTERNAL_SERVER_ERROR.toString(),
298
					HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, dealBrandsResponse);
299
			return new ResponseEntity<>(profitMandiResponse, HttpStatus.INTERNAL_SERVER_ERROR);
21356 kshitij.so 300
		}
22319 amit.gupta 301
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
302
		}.getType());
303
		final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
304
				request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS,
305
				dealBrandsResponse);
306
		return new ResponseEntity<>(profitMandiResponse, HttpStatus.OK);
21356 kshitij.so 307
	}
22319 amit.gupta 308
 
309
	@RequestMapping(value = ProfitMandiConstants.URL_UNIT_DEAL, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
21445 kshitij.so 310
	@ApiImplicitParams({
22319 amit.gupta 311
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
21445 kshitij.so 312
	@ApiOperation(value = "Get unit deal object")
22319 amit.gupta 313
	public ResponseEntity<?> getUnitDeal(HttpServletRequest request, @PathVariable(value = "id") long id) {
21445 kshitij.so 314
		String response = null;
22319 amit.gupta 315
		// TODO: move to properties
316
		String uri = "getDealById/" + id;
317
		System.out.println("Unit deal " + uri);
318
		RestClient rc = new RestClient(SchemeType.HTTP, host, port);
21445 kshitij.so 319
		Map<String, String> params = new HashMap<>();
320
		DealsResponse dealsResponse = null;
321
		try {
322
			response = rc.get(uri, params);
323
		} catch (Exception | ProfitMandiBusinessException e) {
22319 amit.gupta 324
			logger.error("Unable to get deals", e);
325
			final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
326
					request.getRequestURL().toString(), HttpStatus.INTERNAL_SERVER_ERROR.toString(),
327
					HttpStatus.INTERNAL_SERVER_ERROR, ResponseStatus.FAILURE, dealsResponse);
328
			return new ResponseEntity<>(profitMandiResponse, HttpStatus.INTERNAL_SERVER_ERROR);
21445 kshitij.so 329
		}
330
		JsonObject result_json = Json.parse(response).asObject();
22319 amit.gupta 331
		if (!result_json.isEmpty()) {
21445 kshitij.so 332
			dealsResponse = new Gson().fromJson(response, DealsResponse.class);
333
		}
22319 amit.gupta 334
		final ProfitMandiResponse<?> profitMandiResponse = new ProfitMandiResponse<>(LocalDateTime.now(),
335
				request.getRequestURL().toString(), HttpStatus.OK.toString(), HttpStatus.OK, ResponseStatus.SUCCESS,
336
				dealsResponse);
337
		return new ResponseEntity<>(profitMandiResponse, HttpStatus.OK);
21445 kshitij.so 338
	}
21339 kshitij.so 339
 
340
}