Subversion Repositories SmartDukaan

Rev

Rev 28377 | Rev 28392 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
26607 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
27025 tejbeer 3
import java.time.LocalDateTime;
26628 amit.gupta 4
import java.time.LocalTime;
27069 tejbeer 5
import java.time.format.DateTimeFormatter;
26607 amit.gupta 6
import java.util.ArrayList;
7
import java.util.Arrays;
28312 amit.gupta 8
import java.util.Comparator;
26607 amit.gupta 9
import java.util.HashMap;
10
import java.util.HashSet;
11
import java.util.List;
12
import java.util.Map;
26745 amit.gupta 13
import java.util.Optional;
26607 amit.gupta 14
import java.util.Set;
15
import java.util.stream.Collectors;
16
 
17
import javax.servlet.http.HttpServletRequest;
28334 amit.gupta 18
import javax.servlet.http.HttpServletResponse;
26607 amit.gupta 19
 
20
import org.apache.commons.lang3.StringUtils;
21
import org.apache.http.conn.HttpHostConnectException;
22
import org.apache.logging.log4j.LogManager;
23
import org.apache.logging.log4j.Logger;
24
import org.json.JSONArray;
25
import org.json.JSONObject;
26
import org.springframework.beans.factory.annotation.Autowired;
27
import org.springframework.beans.factory.annotation.Value;
26745 amit.gupta 28
import org.springframework.cache.annotation.Cacheable;
26607 amit.gupta 29
import org.springframework.http.MediaType;
30
import org.springframework.http.ResponseEntity;
31
import org.springframework.stereotype.Controller;
32
import org.springframework.transaction.annotation.Transactional;
26923 amit.gupta 33
import org.springframework.web.bind.annotation.GetMapping;
26662 amit.gupta 34
import org.springframework.web.bind.annotation.PathVariable;
26607 amit.gupta 35
import org.springframework.web.bind.annotation.RequestBody;
36
import org.springframework.web.bind.annotation.RequestMapping;
37
import org.springframework.web.bind.annotation.RequestMethod;
38
import org.springframework.web.bind.annotation.RequestParam;
28322 amit.gupta 39
import org.springframework.web.bind.annotation.ResponseBody;
26607 amit.gupta 40
 
41
import com.eclipsesource.json.JsonObject;
26774 amit.gupta 42
import com.fasterxml.jackson.annotation.JsonProperty;
26607 amit.gupta 43
import com.google.gson.Gson;
44
import com.google.gson.reflect.TypeToken;
28377 tejbeer 45
import com.spice.profitmandi.common.enumuration.MessageType;
26607 amit.gupta 46
import com.spice.profitmandi.common.enumuration.SchemeType;
47
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
26923 amit.gupta 48
import com.spice.profitmandi.common.model.CreatePendingOrderItem;
26648 amit.gupta 49
import com.spice.profitmandi.common.model.CreatePendingOrderRequest;
26651 amit.gupta 50
import com.spice.profitmandi.common.model.CustomRetailer;
26607 amit.gupta 51
import com.spice.profitmandi.common.model.ProfitMandiConstants;
28377 tejbeer 52
import com.spice.profitmandi.common.model.SendNotificationModel;
26607 amit.gupta 53
import com.spice.profitmandi.common.model.UserInfo;
54
import com.spice.profitmandi.common.solr.SolrService;
28304 amit.gupta 55
import com.spice.profitmandi.common.util.FormattingUtils;
26607 amit.gupta 56
import com.spice.profitmandi.common.web.client.RestClient;
57
import com.spice.profitmandi.common.web.util.ResponseSender;
58
import com.spice.profitmandi.dao.entity.catalog.Item;
59
import com.spice.profitmandi.dao.entity.catalog.TagListing;
28377 tejbeer 60
import com.spice.profitmandi.dao.entity.dtr.User;
26745 amit.gupta 61
import com.spice.profitmandi.dao.entity.dtr.WebListing;
28374 amit.gupta 62
import com.spice.profitmandi.dao.entity.dtr.WebOffer;
26774 amit.gupta 63
import com.spice.profitmandi.dao.entity.fofo.Customer;
26857 amit.gupta 64
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
28267 amit.gupta 65
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
26855 tejbeer 66
import com.spice.profitmandi.dao.entity.fofo.PendingOrder;
67
import com.spice.profitmandi.dao.entity.fofo.PendingOrderItem;
26715 amit.gupta 68
import com.spice.profitmandi.dao.entity.fofo.PincodePartner;
28377 tejbeer 69
import com.spice.profitmandi.dao.entity.fofo.RazorPay;
26630 amit.gupta 70
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
27045 tejbeer 71
import com.spice.profitmandi.dao.enumuration.transaction.OrderStatus;
26607 amit.gupta 72
import com.spice.profitmandi.dao.model.AddCartRequest;
73
import com.spice.profitmandi.dao.model.CartItem;
74
import com.spice.profitmandi.dao.model.CartItemResponseModel;
75
import com.spice.profitmandi.dao.model.CartResponse;
27045 tejbeer 76
import com.spice.profitmandi.dao.model.CustomerOrderDetail;
26607 amit.gupta 77
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
78
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
28290 tejbeer 79
import com.spice.profitmandi.dao.repository.cs.CsService;
26718 amit.gupta 80
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
27030 amit.gupta 81
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
26745 amit.gupta 82
import com.spice.profitmandi.dao.repository.dtr.WebListingRepository;
28374 amit.gupta 83
import com.spice.profitmandi.dao.repository.dtr.WebOfferRepository;
26745 amit.gupta 84
import com.spice.profitmandi.dao.repository.dtr.WebProductListingRepository;
26607 amit.gupta 85
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
26788 amit.gupta 86
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
26774 amit.gupta 87
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
26855 tejbeer 88
import com.spice.profitmandi.dao.repository.fofo.PendingOrderItemRepository;
89
import com.spice.profitmandi.dao.repository.fofo.PendingOrderRepository;
26648 amit.gupta 90
import com.spice.profitmandi.dao.repository.fofo.PendingOrderService;
26715 amit.gupta 91
import com.spice.profitmandi.dao.repository.fofo.PincodePartnerRepository;
28377 tejbeer 92
import com.spice.profitmandi.dao.repository.fofo.RazorPayRepository;
26607 amit.gupta 93
import com.spice.profitmandi.dao.repository.inventory.ItemAvailabilityCacheRepository;
26784 amit.gupta 94
import com.spice.profitmandi.service.CustomerService;
28377 tejbeer 95
import com.spice.profitmandi.service.EmailService;
96
import com.spice.profitmandi.service.NotificationService;
26607 amit.gupta 97
import com.spice.profitmandi.service.authentication.RoleManager;
26923 amit.gupta 98
import com.spice.profitmandi.service.inventory.AvailabilityModel;
26607 amit.gupta 99
import com.spice.profitmandi.service.inventory.FofoAvailabilityInfo;
100
import com.spice.profitmandi.service.inventory.FofoCatalogResponse;
26923 amit.gupta 101
import com.spice.profitmandi.service.inventory.InventoryService;
26909 amit.gupta 102
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
26683 amit.gupta 103
import com.spice.profitmandi.service.scheme.SchemeService;
26651 amit.gupta 104
import com.spice.profitmandi.service.user.RetailerService;
26630 amit.gupta 105
import com.spice.profitmandi.web.processor.OtpProcessor;
26607 amit.gupta 106
import com.spice.profitmandi.web.res.DealBrands;
107
import com.spice.profitmandi.web.res.DealObjectResponse;
108
import com.spice.profitmandi.web.res.DealsResponse;
109
import com.spice.profitmandi.web.res.ValidateCartResponse;
28322 amit.gupta 110
import com.spice.profitmandi.web.services.PartnerIndexService;
26607 amit.gupta 111
 
112
import io.swagger.annotations.ApiImplicitParam;
113
import io.swagger.annotations.ApiImplicitParams;
114
import io.swagger.annotations.ApiOperation;
115
 
116
@Controller
117
@Transactional(rollbackFor = Throwable.class)
118
public class StoreController {
119
 
120
	private static final Logger logger = LogManager.getLogger(StoreController.class);
26630 amit.gupta 121
 
26628 amit.gupta 122
	private static final LocalTime CUTOFF_TIME = LocalTime.of(15, 0);
26745 amit.gupta 123
 
124
	private static final List<Integer> TAG_IDS = Arrays.asList(4);
125
 
26788 amit.gupta 126
	@Autowired
127
	CustomerAddressRepository customerAddressRepository;
28374 amit.gupta 128
 
129
	@Autowired
130
	WebOfferRepository webOfferRepository;
26607 amit.gupta 131
 
28315 amit.gupta 132
	@Value("${new.solr.url}")
28314 amit.gupta 133
	private String solrUrl;
28345 tejbeer 134
 
26923 amit.gupta 135
	@Autowired
28322 amit.gupta 136
	private PartnerIndexService partnerIndexService;
28345 tejbeer 137
 
28322 amit.gupta 138
	@Autowired
26923 amit.gupta 139
	InventoryService inventoryService;
27045 tejbeer 140
 
27030 amit.gupta 141
	@Autowired
142
	UserAccountRepository userAccountRepository;
26923 amit.gupta 143
 
26607 amit.gupta 144
	@Value("${python.api.host}")
145
	private String host;
26833 amit.gupta 146
 
26784 amit.gupta 147
	@Autowired
148
	CustomerService customerService;
26607 amit.gupta 149
 
150
	@Value("${python.api.port}")
151
	private int port;
26923 amit.gupta 152
 
26909 amit.gupta 153
	@Autowired
154
	private SaholicInventoryService saholicInventoryService;
26607 amit.gupta 155
 
156
	@Autowired
26715 amit.gupta 157
	private PincodePartnerRepository pincodePartnerRepository;
158
 
159
	@Autowired
26718 amit.gupta 160
	private FofoStoreRepository fofoStoreRepository;
26745 amit.gupta 161
 
26718 amit.gupta 162
	@Autowired
26651 amit.gupta 163
	private RetailerService retailerService;
26861 tejbeer 164
 
26857 amit.gupta 165
	@Autowired
166
	private PendingOrderRepository pendingOrderRepository;
26861 tejbeer 167
 
26857 amit.gupta 168
	@Autowired
169
	private PendingOrderItemRepository pendingOrderItemRepository;
26652 amit.gupta 170
 
26651 amit.gupta 171
	@Autowired
26652 amit.gupta 172
	private PendingOrderService pendingOrderService;
26648 amit.gupta 173
 
174
	@Autowired
26774 amit.gupta 175
	private CustomerRepository customerRepository;
176
 
177
	@Autowired
26607 amit.gupta 178
	private SolrService commonSolrService;
179
 
180
	@Autowired
26630 amit.gupta 181
	private OtpProcessor otpProcessor;
182
 
183
	@Autowired
26607 amit.gupta 184
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
185
 
26609 amit.gupta 186
	@Autowired
26607 amit.gupta 187
	private ResponseSender<?> responseSender;
188
 
189
	@Autowired
190
	private TagListingRepository tagListingRepository;
191
 
192
	@Autowired
193
	private ItemRepository itemRepository;
26701 amit.gupta 194
 
26683 amit.gupta 195
	@Autowired
196
	private SchemeService schemeService;
26607 amit.gupta 197
 
198
	@Autowired
199
	private ItemAvailabilityCacheRepository itemAvailabilityCacheRepository;
200
 
201
	@Autowired
26745 amit.gupta 202
	private WebListingRepository webListingRepository;
203
 
204
	@Autowired
205
	private WebProductListingRepository webProductListingRepository;
206
 
207
	@Autowired
26607 amit.gupta 208
	private RoleManager roleManagerService;
209
 
27028 tejbeer 210
	@Autowired
28304 amit.gupta 211
	EmailService emailService;
27028 tejbeer 212
 
213
	@Autowired
28290 tejbeer 214
	CsService csService;
28339 tejbeer 215
 
28377 tejbeer 216
	@Autowired
217
	private NotificationService notificationService;
218
 
219
	@Autowired
220
	private com.spice.profitmandi.dao.repository.dtr.UserRepository dtrUserRepository;
221
 
28339 tejbeer 222
	private static final List<String> offlineOrders = Arrays.asList("EMIOD", "POD");
223
 
26607 amit.gupta 224
	List<String> filterableParams = Arrays.asList("brand");
225
 
26668 amit.gupta 226
	@RequestMapping(value = "/store/entity/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
227
	@ApiImplicitParams({
228
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
229
	@ApiOperation(value = "Get unit deal object")
230
	public ResponseEntity<?> getUnitFocoDeal(HttpServletRequest request, @PathVariable(value = "id") long id)
231
			throws ProfitMandiBusinessException {
232
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
233
		List<Integer> tagIds = Arrays.asList(4);
234
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
235
		if (roleManagerService.isPartner(userInfo.getRoleIds())) {
236
			String categoryId = "(3 OR 6)";
26745 amit.gupta 237
 
26668 amit.gupta 238
			RestClient rc = new RestClient();
239
			Map<String, String> params = new HashMap<>();
240
			List<String> mandatoryQ = new ArrayList<>();
241
			String catalogString = "catalog" + id;
26607 amit.gupta 242
 
26668 amit.gupta 243
			mandatoryQ.add(String.format("+(categoryId_i:%s) +(id:%s) +{!parent which=\"id:%s\"} tagId_i:(%s)",
244
					categoryId, catalogString, catalogString, StringUtils.join(tagIds, " ")));
245
 
246
			params.put("q", StringUtils.join(mandatoryQ, " "));
247
			params.put("fl", "*, [child parentFilter=id:catalog*]");
248
			params.put("sort", "rank_i asc, create_s desc");
249
			params.put("wt", "json");
250
			String response = null;
251
			try {
28316 amit.gupta 252
				response = rc.get(SchemeType.HTTP, solrUrl, 8984, "solr/demo/select", params);
26668 amit.gupta 253
			} catch (HttpHostConnectException e) {
254
				throw new ProfitMandiBusinessException("", "", "Could not connect to host");
255
			}
256
			JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
257
			JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
26909 amit.gupta 258
			dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
26668 amit.gupta 259
		} else {
260
			return responseSender.badRequest(
261
					new ProfitMandiBusinessException("Retailer id", userInfo.getUserId(), "NOT_FOFO_RETAILER"));
262
		}
263
		return responseSender.ok(dealResponse.get(0));
264
	}
265
 
26607 amit.gupta 266
	private Object toDealObject(JsonObject jsonObject) {
267
		if (jsonObject.get("dealObject") != null && jsonObject.get("dealObject").asInt() == 1) {
268
			return new Gson().fromJson(jsonObject.toString(), DealObjectResponse.class);
269
		}
270
		return new Gson().fromJson(jsonObject.toString(), DealsResponse.class);
271
	}
272
 
273
	@RequestMapping(value = "/store/brands", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
274
	@ApiImplicitParams({
275
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
276
	@ApiOperation(value = "Get brand list and count for category")
277
	public ResponseEntity<?> getBrands(HttpServletRequest request,
278
			@RequestParam(value = "category_id") String category_id) throws ProfitMandiBusinessException {
279
		logger.info("Request " + request.getParameterMap());
280
		String response = null;
281
		// TODO: move to properties
282
		String uri = ProfitMandiConstants.URL_BRANDS;
283
		RestClient rc = new RestClient();
284
		Map<String, String> params = new HashMap<>();
285
		params.put("category_id", category_id);
286
		List<DealBrands> dealBrandsResponse = null;
287
		try {
288
			response = rc.get(SchemeType.HTTP, host, port, uri, params);
289
		} catch (HttpHostConnectException e) {
290
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
291
		}
292
 
293
		dealBrandsResponse = new Gson().fromJson(response, new TypeToken<List<DealBrands>>() {
294
		}.getType());
295
 
296
		return responseSender.ok(dealBrandsResponse);
297
	}
298
 
26745 amit.gupta 299
	@RequestMapping(value = "/store/listing/{listingUrl}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
300
	public ResponseEntity<?> bestSellers(HttpServletRequest request, @PathVariable String listingUrl) throws Exception {
26909 amit.gupta 301
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
28287 amit.gupta 302
		WebListing webListing = webListingRepository.selectByUrl(listingUrl);
303
		webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing));
26745 amit.gupta 304
		return responseSender.ok(webListing);
26654 amit.gupta 305
	}
306
 
26632 amit.gupta 307
	@RequestMapping(value = "/store/otp/generateOTP", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26783 amit.gupta 308
	public ResponseEntity<?> generateOtp(HttpServletRequest request, @RequestParam String mobile) throws Exception {
26630 amit.gupta 309
 
26857 amit.gupta 310
		return responseSender.ok(otpProcessor.generateOtp(mobile, OtpType.REGISTRATION));
26630 amit.gupta 311
 
312
	}
26652 amit.gupta 313
 
26784 amit.gupta 314
	@RequestMapping(value = "/store/checkmobile/{mobile}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26833 amit.gupta 315
	public ResponseEntity<?> checkRegistrationUsingMobile(HttpServletRequest request, @PathVariable String mobile)
316
			throws Exception {
26774 amit.gupta 317
		try {
318
			Customer customer = customerRepository.selectByMobileNumber(mobile);
26777 amit.gupta 319
			customer.setPasswordExist(StringUtils.isNotEmpty(customer.getPassword()));
26774 amit.gupta 320
			return responseSender.ok(new CustomerModel(true, customer));
321
		} catch (Exception e) {
322
			return responseSender.ok(new CustomerModel(false, null));
323
		}
324
	}
26833 amit.gupta 325
 
26784 amit.gupta 326
	@RequestMapping(value = "/store/signin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
327
	public ResponseEntity<?> signIn(HttpServletRequest request, @RequestBody UserModel userModel) throws Exception {
26833 amit.gupta 328
		if (customerService.authenticate(userModel.getMobile(), userModel.getPassword())) {
26784 amit.gupta 329
			return responseSender.ok(true);
330
		} else {
331
			return responseSender.ok(false);
332
		}
333
	}
26923 amit.gupta 334
 
26841 amit.gupta 335
	@RequestMapping(value = "/store/resetPassword", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26923 amit.gupta 336
	public ResponseEntity<?> resetPassword(HttpServletRequest request, @RequestBody UserModel userModel)
337
			throws Exception {
26843 amit.gupta 338
		customerService.changePassword(userModel.getMobile(), userModel.getPassword());
26841 amit.gupta 339
		return responseSender.ok(true);
340
	}
26774 amit.gupta 341
 
26857 amit.gupta 342
	@RequestMapping(value = "/store/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
343
	public ResponseEntity<?> register(HttpServletRequest request, @RequestBody UserModel userModel) throws Exception {
344
		Customer customer = new Customer();
345
		customer.setPassword(userModel.getPassword());
346
		customer.setEmailId(userModel.getEmail());
347
		customer.setFirstName(userModel.getFirstName());
348
		customer.setLastName(userModel.getLastName());
349
		customer.setMobileNumber(userModel.getMobile());
350
		return responseSender.ok(customerService.addCustomer(customer));
351
	}
352
 
26648 amit.gupta 353
	@RequestMapping(value = "/store/confirmOrder", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
26857 amit.gupta 354
	public ResponseEntity<?> confirmOrder(HttpServletRequest request,
26652 amit.gupta 355
			@RequestBody CreatePendingOrderRequest createPendingOrderRequest) throws Exception {
26648 amit.gupta 356
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
357
		Integer storeId = userInfo.getRetailerId();
358
		createPendingOrderRequest.setFofoId(storeId);
26923 amit.gupta 359
		List<CreatePendingOrderItem> pendingOrderItems = createPendingOrderRequest.getCreatePendingOrderItem();
360
		List<CartItem> cartItems = new ArrayList<>();
361
		pendingOrderItems.stream().forEach(x -> {
362
			CartItem ci = new CartItem();
363
			ci.setItemId(x.getItemId());
364
			ci.setQuantity(x.getQuantity());
365
			ci.setSellingPrice(x.getSellingPrice());
366
			cartItems.add(ci);
367
		});
368
		CartResponse cr = this.validateCart(storeId, cartItems);
369
		if (cr.getCartMessageChanged() > 0 || cr.getTotalAmount() != createPendingOrderRequest.getTotalAmount()) {
370
			return responseSender.badRequest("Invalid request");
371
		}
26652 amit.gupta 372
 
27028 tejbeer 373
		Map<String, String> returnMap = this.pendingOrderService.createPendingOrder(createPendingOrderRequest, cr);
374
 
28339 tejbeer 375
		PendingOrder pendingOrder = pendingOrderRepository.selectById(Integer.parseInt(returnMap.get("poId")));
376
		if (offlineOrders.contains(pendingOrder.getPayMethod())) {
377
 
378
			Map<String, Object> emailModel = pendingOrderService.sendCreateOrderMail(pendingOrder);
379
 
380
			CustomRetailer customRetailer = retailerService.getFofoRetailer(pendingOrder.getFofoId());
381
			Customer customer = customerRepository.selectById(pendingOrder.getCustomerId());
382
			String[] customerEmail = null;
383
			if (customer.getEmailId() != null) {
384
				customerEmail = new String[] { customer.getEmailId() };
385
			}
28377 tejbeer 386
 
28339 tejbeer 387
			List<String> bccTo = Arrays.asList("kamini.sharma@smartdukaan.com", "tarun.verma@smartdukaan.com",
388
					"hemant.kaura@smartdukaan.com", "niranjan.kala@smartdukaan.com", "sm@smartdukaan.com",
389
					"tejbeer.kaur@shop2020.in", customRetailer.getEmail());
28377 tejbeer 390
 
28339 tejbeer 391
			List<String> authUserEmails = csService.getAuthUserByPartnerId(customRetailer.getPartnerId());
392
			if (authUserEmails != null) {
393
				authUserEmails = new ArrayList<>();
394
			}
395
			logger.info("authUserEmails {}", authUserEmails);
396
			authUserEmails.addAll(bccTo);
28374 amit.gupta 397
			StringBuffer itemBuffer = new StringBuffer();
398
			List<PendingOrderItem> orderItems = pendingOrderItemRepository.selectByOrderId(pendingOrder.getId());
399
			int totalItems = 0;
400
			String itemNoColor = null;
401
			float maxValue = 0;
28391 tejbeer 402
			for (PendingOrderItem orderItem : orderItems) {
403
				if (maxValue < orderItem.getSellingPrice()) {
28374 amit.gupta 404
					maxValue = orderItem.getSellingPrice();
405
					itemNoColor = itemRepository.selectById(orderItem.getItemId()).getItemDescriptionNoColor();
406
				}
407
				totalItems += orderItem.getQuantity();
408
			}
28391 tejbeer 409
			if (totalItems > 1) {
28374 amit.gupta 410
				itemBuffer.append(StringUtils.abbreviate(itemNoColor, 22));
28391 tejbeer 411
				itemBuffer.append(" +").append(totalItems - 1).append(" items");
28374 amit.gupta 412
			} else {
413
				itemBuffer.append(StringUtils.abbreviate(itemNoColor, 30));
414
			}
28391 tejbeer 415
			String message = String.format(OtpProcessor.TEMPLATE_ORDER_CREATED, pendingOrder.getId(),
416
					itemBuffer.toString(), pendingOrder.getTotalAmount());
28374 amit.gupta 417
			otpProcessor.sendSms(OtpProcessor.TEMPLATE_ORDER_CREATED_ID, message, customer.getMobileNumber());
28391 tejbeer 418
 
28339 tejbeer 419
			emailService.sendMailWithAttachments("Order Created with SmartDukaan", "order-confirm.vm", emailModel,
28377 tejbeer 420
					customerEmail, null, bccTo.toArray(new String[0]));
421
 
422
			List<String> gmailIds = csService.getAuthUserIdByPartnerId(customRetailer.getPartnerId()).stream()
423
					.map(x -> x.getGmailId()).collect(Collectors.toList());
28391 tejbeer 424
			gmailIds.add("tarunverma09@gmail.com");
28377 tejbeer 425
			List<User> user = dtrUserRepository.selectAllByEmailIds(gmailIds);
426
			List<Integer> userIds = user.stream().map(x -> x.getId()).collect(Collectors.toList());
427
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
428
			sendNotificationModel.setCampaignName("Online Order Alert");
429
			sendNotificationModel.setTitle("Online Order Update");
28391 tejbeer 430
			sendNotificationModel.setMessage(String.format(
431
					"You have new Online Order. Please check your Dashboard. In case of an activation scheme pls ensure the handset is activated, payout will be processed as per brand's activation report."));
28377 tejbeer 432
			sendNotificationModel.setType("url");
433
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
434
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
435
			sendNotificationModel.setMessageType(MessageType.notification);
436
			int userId = userAccountRepository.selectUserIdByRetailerId(pendingOrder.getFofoId());
437
			sendNotificationModel.setUserIds(Arrays.asList(userId));
438
			notificationService.sendNotification(sendNotificationModel);
439
 
440
			sendNotificationModel = new SendNotificationModel();
441
			sendNotificationModel.setCampaignName("Online Order Alert");
442
			sendNotificationModel.setTitle("Online Order Update");
443
			sendNotificationModel.setMessage(String.format("Your Partner " + customRetailer.getBusinessName()
444
					+ " have new Online Order. Please inform your partner"));
445
			sendNotificationModel.setType("url");
446
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
447
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
448
			sendNotificationModel.setMessageType(MessageType.notification);
449
			sendNotificationModel.setUserIds(userIds);
450
 
28339 tejbeer 451
		}
27028 tejbeer 452
		return responseSender.ok(returnMap);
453
 
26648 amit.gupta 454
	}
26630 amit.gupta 455
 
26857 amit.gupta 456
	@RequestMapping(value = "/store/address", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
457
	@ApiImplicitParams({
458
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
459
	@ApiOperation(value = "Get brand list and count for category")
460
	public ResponseEntity<?> getAddress(HttpServletRequest request) throws Exception {
461
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
462
		Integer storeId = userInfo.getRetailerId();
463
		CustomRetailer customRetailer = retailerService.getFofoRetailer(storeId);
464
 
465
		return responseSender.ok(customRetailer.getAddress());
466
 
467
	}
468
 
469
	@RequestMapping(value = "/store/address/{pincode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
470
	@ApiImplicitParams({
471
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
472
	@ApiOperation(value = "Get brand list and count for category")
473
	public ResponseEntity<?> getStoresByPincode(HttpServletRequest request, @PathVariable String pincode)
474
			throws Exception {
475
		List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pincode);
28321 amit.gupta 476
		int fofoId = ProfitMandiConstants.DEFAULT_STORE;
26857 amit.gupta 477
		if (pincodePartners.size() > 0) {
28287 amit.gupta 478
			List<Integer> fofoIds = pincodePartners.stream().map(x -> x.getFofoId()).collect(Collectors.toList());
28267 amit.gupta 479
			List<FofoStore> fofoStores = fofoStoreRepository.selectActivePartnersByRetailerIds(fofoIds);
28287 amit.gupta 480
			if (fofoStores.size() > 0) {
28267 amit.gupta 481
				fofoId = fofoStores.get(0).getId();
482
			}
28287 amit.gupta 483
 
26857 amit.gupta 484
		}
485
		return responseSender.ok(fofoStoreRepository.selectByRetailerId(fofoId).getCode());
486
	}
26923 amit.gupta 487
 
28298 tejbeer 488
	@RequestMapping(value = "/store/address/detail/{pincode}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
489
	@ApiImplicitParams({
490
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
491
	@ApiOperation(value = "Get brand list and count for category")
492
	public ResponseEntity<?> getStoresDetailsByPincode(HttpServletRequest request, @PathVariable String pincode)
493
			throws Exception {
494
		List<CustomRetailer> customerRetailers = new ArrayList<>();
495
		List<PincodePartner> pincodePartners = pincodePartnerRepository.selectPartnersByPincode(pincode);
496
 
497
		if (!pincodePartners.isEmpty()) {
498
			List<Integer> fofoIds = pincodePartners.stream().map(x -> x.getFofoId()).collect(Collectors.toList());
499
			List<Integer> activefofoIds = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
500
					.filter(x -> x.isActive()).map(x -> x.getId()).collect(Collectors.toList());
501
			Map<Integer, CustomRetailer> customerRetailerMap = retailerService.getFofoRetailers(activefofoIds);
502
			customerRetailers.addAll(customerRetailerMap.values());
503
		}
504
 
505
		logger.info("customerRetailers" + customerRetailers);
506
		return responseSender.ok(customerRetailers);
507
	}
508
 
26855 tejbeer 509
	@RequestMapping(value = "/store/order", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
510
	public ResponseEntity<?> getOrderDetail(HttpServletRequest request, @RequestParam(value = "id") int id,
27049 tejbeer 511
			@RequestParam(name = "offset") int offset, @RequestParam(name = "limit") int limit) throws Exception {
26855 tejbeer 512
		List<CustomerOrderDetail> customerOrderDetails = new ArrayList<>();
27049 tejbeer 513
		List<Integer> catalogIds = new ArrayList<>();
26855 tejbeer 514
		List<PendingOrder> pendingOrders = pendingOrderRepository.selectByCustomerId(id, offset, limit);
515
		if (!pendingOrders.isEmpty()) {
516
			for (PendingOrder po : pendingOrders) {
517
				List<PendingOrderItem> pois = pendingOrderItemRepository.selectByOrderId(po.getId());
27049 tejbeer 518
				for (PendingOrderItem pendingOrderItem : pois) {
519
					Item item = itemRepository.selectById(pendingOrderItem.getItemId());
520
					pendingOrderItem.setItemName(item.getItemDescription());
521
					catalogIds.add(item.getCatalogItemId());
522
				}
523
 
524
				Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
525
 
26855 tejbeer 526
				for (PendingOrderItem poi : pois) {
527
 
528
					CustomerOrderDetail customerOrderDetail = new CustomerOrderDetail();
529
 
530
					Item item = itemRepository.selectById(poi.getItemId());
27049 tejbeer 531
					JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
532
					customerOrderDetail.setImageUrl(jsonObj.getString("imageUrl_s"));
26855 tejbeer 533
					customerOrderDetail.setBrand(item.getBrand());
534
					customerOrderDetail.setColor(item.getColor());
27056 tejbeer 535
					customerOrderDetail.setPendingOrderItemId(poi.getId());
26855 tejbeer 536
					customerOrderDetail.setId(poi.getOrderId());
537
					customerOrderDetail.setItemId(poi.getItemId());
538
					customerOrderDetail.setModelName(item.getModelName());
539
					customerOrderDetail.setModelNumber(item.getModelNumber());
540
					customerOrderDetail.setQuantity(poi.getQuantity());
27045 tejbeer 541
					customerOrderDetail.setBilledTimestamp(poi.getBilledTimestamp());
542
					customerOrderDetail.setStatus(poi.getStatus());
26855 tejbeer 543
					customerOrderDetail.setTotalPrice(poi.getSellingPrice());
544
					customerOrderDetail.setPayMethod(po.getPayMethod());
26861 tejbeer 545
					customerOrderDetail.setCreatedTimeStamp(po.getCreateTimestamp());
26855 tejbeer 546
					customerOrderDetails.add(customerOrderDetail);
547
				}
548
			}
549
		}
550
 
551
		return responseSender.ok(customerOrderDetails);
552
	}
553
 
26745 amit.gupta 554
	@RequestMapping(value = "/store/listing", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26774 amit.gupta 555
	public ResponseEntity<?> getStoresListing(HttpServletRequest request) throws Exception {
26745 amit.gupta 556
		List<WebListing> webListings = webListingRepository.selectAllWebListing(Optional.of(true));
28287 amit.gupta 557
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
26745 amit.gupta 558
		for (WebListing webListing : webListings) {
28287 amit.gupta 559
			webListing.setFofoCatalogResponses(getDealResponses(userInfo, webListing));
26745 amit.gupta 560
		}
561
		return responseSender.ok(webListings);
562
	}
563
 
28287 amit.gupta 564
	private List<FofoCatalogResponse> getDealResponses(UserInfo userInfo, WebListing webListing)
565
			throws ProfitMandiBusinessException {
566
		List<Integer> webProducts = webProductListingRepository.selectAllByWebListingId(webListing.getId()).stream()
567
				.filter(x -> x.getRank() > 0).map(x -> x.getEntityId()).collect(Collectors.toList());
568
		if (webProducts.size() == 0) {
569
			return new ArrayList<>();
570
		}
571
		RestClient rc = new RestClient();
572
		Map<String, String> params = new HashMap<>();
573
		List<String> mandatoryQ = new ArrayList<>();
574
		mandatoryQ.add(String.format(
575
				"+{!parent which=\"catalogId_i:" + StringUtils.join(webProducts, " ") + "\"} tagId_i:(%s)",
576
				StringUtils.join(TAG_IDS, " ")));
577
		params.put("q", StringUtils.join(mandatoryQ, " "));
578
		params.put("fl", "*, [child parentFilter=id:catalog*]");
579
		// params.put("sort", "create_s desc");
580
		params.put("start", String.valueOf(0));
581
		params.put("rows", String.valueOf(100));
582
		params.put("wt", "json");
583
		String response = null;
584
		try {
585
			response = rc.get(SchemeType.HTTP, "50.116.10.120", 8984, "solr/demo/select", params);
586
		} catch (HttpHostConnectException e) {
587
			throw new ProfitMandiBusinessException("", "", "Could not connect to host");
588
		}
589
		JSONObject solrResponseJSONObj = new JSONObject(response).getJSONObject("response");
590
		JSONArray docs = solrResponseJSONObj.getJSONArray("docs");
591
		List<FofoCatalogResponse> dealResponse = getCatalogResponse(docs, false, userInfo.getRetailerId());
592
		return dealResponse;
593
	}
594
 
26652 amit.gupta 595
	@RequestMapping(value = "/store/cart", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
596
	@ApiImplicitParams({
26651 amit.gupta 597
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
26652 amit.gupta 598
	@ApiOperation(value = "Get brand list and count for category")
599
	public ResponseEntity<?> cart(HttpServletRequest request, @RequestBody AddCartRequest cartRequest)
600
			throws Exception {
26923 amit.gupta 601
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
602
		Integer storeId = userInfo.getRetailerId();
603
		ValidateCartResponse vc = new ValidateCartResponse(this.validateCart(storeId, cartRequest.getCartItems()),
604
				"Success", "Items added to cart successfully");
605
		return responseSender.ok(vc);
606
	}
607
 
608
	// Validate Cart for B2C Customers
609
	private CartResponse validateCart(int storeId, List<CartItem> cartItems) throws Exception {
610
		cartItems = cartItems.stream().filter(x -> x.getQuantity() > 0).collect(Collectors.toList());
611
		List<Integer> itemIds = cartItems.stream().map(x -> x.getItemId()).collect(Collectors.toList());
612
		Map<Integer, AvailabilityModel> inventoryItemAvailabilityMap = inventoryService.getStoreAndOurStock(storeId,
613
				itemIds);
26607 amit.gupta 614
		CartResponse cartResponse = new CartResponse();
26612 amit.gupta 615
		List<CartItemResponseModel> cartItemResponseModels = new ArrayList<>();
616
		cartResponse.setCartItems(cartItemResponseModels);
26607 amit.gupta 617
		Set<Integer> itemsIdsSet = new HashSet<>(itemIds);
26668 amit.gupta 618
		logger.info("Store Id {}, Item Ids {}", storeId, itemsIdsSet);
26607 amit.gupta 619
 
620
		Map<Integer, Item> itemsMap = itemRepository.selectByIds(itemsIdsSet).stream()
621
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
622
 
26923 amit.gupta 623
		Map<Integer, TagListing> tagListingMap = tagListingRepository
26607 amit.gupta 624
				.selectByItemIdsAndTagIds(new HashSet<>(itemIds), new HashSet<>(Arrays.asList(4))).stream()
625
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
626
 
627
		List<Integer> catalogIds = itemsMap.values().stream().map(x -> x.getCatalogItemId())
628
				.collect(Collectors.toList());
629
 
630
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
631
 
632
		// cartResponse.getCartItems()
26923 amit.gupta 633
		int cartMessageChanged = 0;
634
		int cartMessageOOS = 0;
635
		int totalAmount = 0;
636
		int totalQty = 0;
637
		for (CartItem cartItem : cartItems) {
26607 amit.gupta 638
			Item item = itemsMap.get(cartItem.getItemId());
26923 amit.gupta 639
			TagListing tagListing = tagListingMap.get(cartItem.getItemId());
640
			Float cashback = schemeService.getItemSchemeCashBack().get(cartItem.getItemId());
641
			cashback = cashback == null ? 0 : cashback;
642
			float itemSellingPrice = tagListing.getMop() - cashback;
26607 amit.gupta 643
			CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
26923 amit.gupta 644
			cartItemResponseModel.setSellingPrice(cartItem.getSellingPrice());
645
			if (itemSellingPrice != cartItem.getSellingPrice()) {
646
				cartItemResponseModel.setSellingPrice(itemSellingPrice);
647
				cartMessageChanged++;
648
			}
26628 amit.gupta 649
			int estimate = -2;
27025 tejbeer 650
			LocalDateTime promiseDeliveryTime = LocalDateTime.now();
26923 amit.gupta 651
			int qtyRequired = (int) cartItem.getQuantity();
652
			AvailabilityModel availabilityModel = inventoryItemAvailabilityMap.get(cartItem.getItemId());
653
			cartItemResponseModel.setMaxQuantity(availabilityModel.getMaxAvailability());
654
			if (availabilityModel.getStoreAvailability() >= qtyRequired) {
655
				estimate = 0;
656
			} else if (availabilityModel.getWarehouseAvailability() >= qtyRequired) {
26628 amit.gupta 657
				estimate = 2;
26923 amit.gupta 658
			} else if (availabilityModel.getStoreAvailability() > 0) {
659
				estimate = 0;
660
				qtyRequired = availabilityModel.getStoreAvailability();
661
				cartMessageChanged++;
662
			} else if (availabilityModel.getWarehouseAvailability() > 0) {
663
				qtyRequired = availabilityModel.getWarehouseAvailability();
664
				estimate = 2;
665
				cartMessageChanged++;
26620 amit.gupta 666
			} else {
26923 amit.gupta 667
				qtyRequired = 0;
26926 amit.gupta 668
				cartMessageChanged++;
26607 amit.gupta 669
			}
26923 amit.gupta 670
			cartItemResponseModel.setQuantity(qtyRequired);
26630 amit.gupta 671
			if (estimate >= 0 && LocalTime.now().isAfter(CUTOFF_TIME)) {
26628 amit.gupta 672
				estimate = estimate + 1;
27025 tejbeer 673
				promiseDeliveryTime = promiseDeliveryTime.plusDays(3);
26628 amit.gupta 674
			}
26923 amit.gupta 675
			totalQty += qtyRequired;
676
			totalAmount += qtyRequired * itemSellingPrice;
26628 amit.gupta 677
			cartItemResponseModel.setEstimate(estimate);
26616 amit.gupta 678
			cartItemResponseModel.setTitle(item.getItemDescriptionNoColor());
26614 amit.gupta 679
			cartItemResponseModel.setItemId(cartItem.getItemId());
26615 amit.gupta 680
			cartItemResponseModel.setMinBuyQuantity(1);
26923 amit.gupta 681
			cartItemResponseModel.setQuantity(qtyRequired);
26621 amit.gupta 682
			cartItemResponseModel.setQuantityStep(1);
27025 tejbeer 683
			cartItemResponseModel.setPromiseDelivery(promiseDeliveryTime);
26923 amit.gupta 684
			cartItemResponseModel.setMaxQuantity(availabilityModel.getMaxAvailability());
26607 amit.gupta 685
			cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
686
			cartItemResponseModel.setImageUrl(contentMap.get(item.getCatalogItemId()).getString("imageUrl_s"));
687
			cartItemResponseModel.setColor(item.getColor());
26620 amit.gupta 688
			cartItemResponseModels.add(cartItemResponseModel);
26607 amit.gupta 689
		}
26923 amit.gupta 690
		cartResponse.setCartItems(cartItemResponseModels);
691
		cartResponse.setCartMessageChanged(cartMessageChanged);
692
		cartResponse.setCartMessageOOS(cartMessageOOS);
693
		int maxEstimate = cartItemResponseModels.stream().mapToInt(x -> x.getEstimate()).max().getAsInt();
694
		cartResponse.setMaxEstimate(maxEstimate);
695
		cartResponse.setTotalAmount(totalAmount);
696
		cartResponse.setTotalQty(totalQty);
26652 amit.gupta 697
 
26923 amit.gupta 698
		return cartResponse;
699
 
26648 amit.gupta 700
	}
26607 amit.gupta 701
 
27030 amit.gupta 702
	@RequestMapping(value = "/store/partnerStock", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
703
	public ResponseEntity<?> partnerStock(HttpServletRequest request,
704
			@RequestParam(value = "categoryId", required = false, defaultValue = "3") String categoryId,
705
			@RequestParam(value = "offset") String offset, @RequestParam(value = "limit") String limit,
706
			@RequestParam(value = "sort", required = false) String sort,
707
			@RequestParam(value = "brand", required = false) String brand,
708
			@RequestParam(value = "subCategoryId", required = false) int subCategoryId,
709
			@RequestParam(value = "q", required = false) String queryTerm,
28287 amit.gupta 710
			@RequestParam(required = false) String listing,
711
			@RequestParam(required = false, defaultValue = "true") boolean partnerStockOnly) throws Throwable {
27030 amit.gupta 712
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
713
		UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
28269 amit.gupta 714
		FofoStore fs = fofoStoreRepository.selectByRetailerId(userInfo.getRetailerId());
715
		sort = "w" + fs.getWarehouseId() + "_i desc";
27045 tejbeer 716
		dealResponse = this.getCatalogResponse(
28314 amit.gupta 717
				commonSolrService.getSolrDocs(queryTerm, categoryId, offset, limit, sort, brand, subCategoryId, false),
718
				false, userInfo.getRetailerId());
27030 amit.gupta 719
		return responseSender.ok(dealResponse);
720
	}
721
 
26909 amit.gupta 722
	private List<FofoCatalogResponse> getCatalogResponse(JSONArray docs, boolean hotDeal, int fofoId)
26607 amit.gupta 723
			throws ProfitMandiBusinessException {
26909 amit.gupta 724
		Map<Integer, Integer> ourItemAvailabilityMap = null;
725
		Map<Integer, Integer> partnerStockAvailabilityMap = null;
26607 amit.gupta 726
		List<FofoCatalogResponse> dealResponse = new ArrayList<>();
727
		List<Integer> tagIds = Arrays.asList(4);
728
		if (docs.length() > 0) {
729
			HashSet<Integer> itemsSet = new HashSet<>();
730
			for (int i = 0; i < docs.length(); i++) {
731
				JSONObject doc = docs.getJSONObject(i);
732
				if (doc.has("_childDocuments_")) {
733
					for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
734
						JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
735
						int itemId = childItem.getInt("itemId_i");
736
						itemsSet.add(itemId);
737
					}
738
				}
739
			}
740
			if (itemsSet.size() == 0) {
741
				return dealResponse;
742
			}
28269 amit.gupta 743
			if (fofoId > 0) {
26909 amit.gupta 744
				partnerStockAvailabilityMap = currentInventorySnapshotRepository.selectItemsStock(fofoId).stream()
745
						.collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
746
			}
28287 amit.gupta 747
			ourItemAvailabilityMap = saholicInventoryService.getTotalAvailabilityByItemIds(new ArrayList<>(itemsSet));
26607 amit.gupta 748
		}
749
 
750
		for (int i = 0; i < docs.length(); i++) {
751
			Map<Integer, FofoAvailabilityInfo> fofoAvailabilityInfoMap = new HashMap<>();
752
			JSONObject doc = docs.getJSONObject(i);
753
			FofoCatalogResponse ffdr = new FofoCatalogResponse();
754
			ffdr.setCatalogId(doc.getInt("catalogId_i"));
755
			ffdr.setImageUrl(doc.getString("imageUrl_s"));
756
			ffdr.setTitle(doc.getString("title_s"));
28374 amit.gupta 757
			List<WebOffer> webOffers = webOfferRepository.selectAllActiveOffers().get(ffdr.getCatalogId());
28391 tejbeer 758
			if (webOffers != null && webOffers.size() > 0) {
759
				ffdr.setOffers(webOffers.stream().map(x -> x.getSmallText()).collect(Collectors.toList()));
28374 amit.gupta 760
			}
26607 amit.gupta 761
			try {
762
				ffdr.setFeature(doc.getString("feature_s"));
763
			} catch (Exception e) {
764
				ffdr.setFeature(null);
765
			}
766
			ffdr.setBrand(doc.getJSONArray("brand_ss").getString(0));
767
			if (doc.has("_childDocuments_")) {
768
				for (int j = 0; j < doc.getJSONArray("_childDocuments_").length(); j++) {
769
					JSONObject childItem = doc.getJSONArray("_childDocuments_").getJSONObject(j);
770
					int itemId = childItem.getInt("itemId_i");
771
					float sellingPrice = (float) childItem.getDouble("sellingPrice_f");
772
					if (fofoAvailabilityInfoMap.containsKey(itemId)) {
773
						if (fofoAvailabilityInfoMap.get(itemId).getSellingPrice() > sellingPrice) {
774
							fofoAvailabilityInfoMap.get(itemId).setSellingPrice(sellingPrice);
775
							fofoAvailabilityInfoMap.get(itemId).setMop((float) childItem.getDouble("mop_f"));
776
						}
777
					} else {
778
						FofoAvailabilityInfo fdi = new FofoAvailabilityInfo();
26909 amit.gupta 779
						fdi.setSellingPrice(sellingPrice);
780
						fdi.setMrp(childItem.getDouble("mrp_f"));
26607 amit.gupta 781
						fdi.setMop((float) childItem.getDouble("mop_f"));
782
						fdi.setColor(childItem.has("color_s") ? childItem.getString("color_s") : "");
783
						fdi.setTagId(childItem.getInt("tagId_i"));
784
						fdi.setItem_id(itemId);
26909 amit.gupta 785
						Float cashBack = schemeService.getItemSchemeCashBack().get(itemId);
786
						cashBack = cashBack == null ? 0 : cashBack;
28391 tejbeer 787
						// TODO:Dont commit
788
						// fdi.setCashback(Math.min(100, fdi.getMop()));
26673 amit.gupta 789
						fdi.setMinBuyQuantity(1);
28313 amit.gupta 790
						int partnerAvailability = partnerStockAvailabilityMap.get(itemId) == null ? 0
791
								: partnerStockAvailabilityMap.get(itemId);
28287 amit.gupta 792
						int ourStockAvailability = ourItemAvailabilityMap.get(itemId) == null ? 0
793
								: Math.max(0, ourItemAvailabilityMap.get(itemId));
28313 amit.gupta 794
						fdi.setActive(partnerAvailability > 0);
28287 amit.gupta 795
						fdi.setAvailability(Math.min(5, ourStockAvailability + partnerAvailability));
26607 amit.gupta 796
						fdi.setQuantityStep(1);
28269 amit.gupta 797
						fdi.setMaxQuantity(fdi.getAvailability());
26607 amit.gupta 798
						fofoAvailabilityInfoMap.put(itemId, fdi);
799
					}
800
				}
801
			}
802
			if (fofoAvailabilityInfoMap.values().size() > 0) {
28313 amit.gupta 803
				ffdr.setItems(fofoAvailabilityInfoMap.values().stream()
804
						.sorted(Comparator.comparing(FofoAvailabilityInfo::isActive, Comparator.reverseOrder())
805
								.thenComparingInt(y -> -y.getAvailability()))
806
						.collect(Collectors.toList()));
26607 amit.gupta 807
				dealResponse.add(ffdr);
808
			}
809
		}
28314 amit.gupta 810
		return dealResponse.stream()
811
				.sorted(Comparator
812
						.comparing(FofoCatalogResponse::getItems,
813
								(s1, s2) -> (s2.get(0).isActive() ? 1 : 0) - (s1.get(0).isActive() ? 1 : 0))
814
						.thenComparing(FofoCatalogResponse::getItems,
815
								(x, y) -> y.get(0).getAvailability() - x.get(0).getAvailability()))
816
				.collect(Collectors.toList());
26607 amit.gupta 817
	}
26923 amit.gupta 818
 
819
	@GetMapping(value = "store/order-status/{pendingOrderId}")
27028 tejbeer 820
	public ResponseEntity<?> orderStatus(HttpServletRequest request, @PathVariable int pendingOrderId)
821
			throws Exception {
26923 amit.gupta 822
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderId);
823
		List<PendingOrderItem> pendingOrderItems = pendingOrderItemRepository.selectByOrderId(pendingOrder.getId());
824
		List<Integer> catalogIds = new ArrayList<>();
27028 tejbeer 825
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 826
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
827
			pendingOrderItem.setItemName(item.getItemDescription());
828
			catalogIds.add(item.getCatalogItemId());
829
		}
830
		Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
27028 tejbeer 831
		for (PendingOrderItem pendingOrderItem : pendingOrderItems) {
26923 amit.gupta 832
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
833
			JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
834
			pendingOrderItem.setImgUrl(jsonObj.getString("imageUrl_s"));
835
		}
836
		pendingOrder.setPendingOrderItems(pendingOrderItems);
27069 tejbeer 837
 
26923 amit.gupta 838
		return responseSender.ok(pendingOrder);
839
	}
840
 
26833 amit.gupta 841
	@RequestMapping(value = "/store/addresses/{customerId}", method = RequestMethod.GET)
842
	public ResponseEntity<?> getAll(HttpServletRequest request, @PathVariable int customerId) throws Throwable {
27045 tejbeer 843
		return responseSender.ok(customerAddressRepository.selectByActiveCustomerId(customerId));
26788 amit.gupta 844
	}
26833 amit.gupta 845
 
26857 amit.gupta 846
	@RequestMapping(value = "/store/address", method = RequestMethod.POST)
847
	public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestBody CustomerAddress customerAddress)
848
			throws Throwable {
849
		customerAddressRepository.persist(customerAddress);
850
		return responseSender.ok(customerAddress);
851
	}
852
 
27045 tejbeer 853
	@RequestMapping(value = "/store/deactivateCustomerAddress", method = RequestMethod.POST)
854
	public ResponseEntity<?> deactivateAddresss(HttpServletRequest request, @RequestParam int id) throws Throwable {
855
		CustomerAddress cust = customerAddressRepository.selectById(id);
856
		cust.setActive(false);
857
		return responseSender.ok(cust);
858
	}
859
 
26861 tejbeer 860
	@RequestMapping(value = "/store/updateCustomer", method = RequestMethod.POST)
861
	public ResponseEntity<?> updateCustomerProfile(HttpServletRequest request, @RequestBody Customer customer)
862
			throws Throwable {
863
		Customer cust = customerRepository.selectById(customer.getId());
864
		cust.setGender(customer.getGender());
26867 tejbeer 865
		cust.setProfileImageId(customer.getProfileImageId());
26861 tejbeer 866
		cust.setDob(customer.getDob());
867
		return responseSender.ok(cust);
868
	}
28345 tejbeer 869
 
28322 amit.gupta 870
	@RequestMapping(value = "/stores/{state}/{city}/{storeCode}", method = RequestMethod.GET)
28345 tejbeer 871
	public void getStoreIndex(HttpServletResponse response, HttpServletRequest request, @PathVariable String state,
872
			@PathVariable String city, @PathVariable String storeCode) throws Throwable {
28325 amit.gupta 873
		logger.info("Store code {}", storeCode);
28345 tejbeer 874
		Map<String, Integer> map = retailerService.getStoreCodeRetailerMap();
875
		logger.info("retailer id {}", map.get(storeCode));
28336 amit.gupta 876
		String retailerName = retailerService.getAllFofoRetailers().get(map.get(storeCode)).getBusinessName();
28322 amit.gupta 877
		String html = partnerIndexService.getPartnerIndexHtml();
28332 amit.gupta 878
		logger.info("html {}", html);
28327 amit.gupta 879
		html = html.replace("Buy Mobiles and Accessories at exciting prices - SmartDukaan",
28338 amit.gupta 880
				String.format("%s is now ONLINE. Buy Mobiles, Accessories & more | SmartDukaan", retailerName));
28334 amit.gupta 881
		response.getWriter().write(html);
28322 amit.gupta 882
	}
26861 tejbeer 883
 
27048 tejbeer 884
	@RequestMapping(value = "/cancelPendingOrderItem", method = RequestMethod.POST)
885
	public ResponseEntity<?> cancelPendingOrderItem(HttpServletRequest request, @RequestParam int id,
27045 tejbeer 886
 
28354 tejbeer 887
			@RequestParam String statusDescription, @RequestParam String reason) throws Exception {
27048 tejbeer 888
 
889
		PendingOrderItem pendingOrderItem = pendingOrderItemRepository.selectById(id);
27057 tejbeer 890
		PendingOrder pendingOrder = pendingOrderRepository.selectById(pendingOrderItem.getOrderId());
28304 amit.gupta 891
		Customer customer = customerRepository.selectById(pendingOrder.getCustomerId());
27048 tejbeer 892
		if (pendingOrderItem.getBilledTimestamp() == null) {
893
			pendingOrderItem.setStatus(OrderStatus.CANCELLED);
28354 tejbeer 894
			pendingOrderItem.setRemark(reason);
895
			pendingOrderItem.setStatusDescription("cancel by self");
28304 amit.gupta 896
			pendingOrderItem.setCancelledTimestamp(LocalDateTime.now());
27048 tejbeer 897
			List<OrderStatus> status = pendingOrderItemRepository.selectByOrderId(pendingOrderItem.getOrderId())
898
					.stream().map(x -> x.getStatus()).collect(Collectors.toList());
899
 
28345 tejbeer 900
			if (!status.contains(OrderStatus.PENDING) && !status.contains(OrderStatus.PROCESSING)
901
					&& !status.contains(OrderStatus.BILLED) && !status.contains(OrderStatus.UNSETTLED)
902
					&& !status.contains(OrderStatus.CLAIMED)) {
27048 tejbeer 903
				pendingOrder.setStatus(OrderStatus.CLOSED);
904
			}
905
 
906
			pendingOrderItemRepository.persist(pendingOrderItem);
28304 amit.gupta 907
			String itemDescription = itemRepository.selectById(pendingOrderItem.getItemId()).getItemDescription();
28313 amit.gupta 908
			otpProcessor.sendSms(OtpProcessor.SELF_CANCELLED_TEMPLATE_ID,
909
					String.format(OtpProcessor.SELF_CANCELLED_TEMPLATE, pendingOrder.getId(),
28304 amit.gupta 910
							StringUtils.abbreviate(itemDescription, 30),
28313 amit.gupta 911
							FormattingUtils.format(pendingOrderItem.getCancelledTimestamp())),
28304 amit.gupta 912
					customer.getMobileNumber());
28339 tejbeer 913
 
914
			List<Integer> catalogIds = new ArrayList<>();
915
 
916
			Item item = itemRepository.selectById(pendingOrderItem.getItemId());
917
			pendingOrderItem.setItemName(item.getItemDescription());
918
			catalogIds.add(item.getCatalogItemId());
919
 
920
			Map<Integer, JSONObject> contentMap = commonSolrService.getContentByCatalogIds(catalogIds);
921
			JSONObject jsonObj = contentMap.get(item.getCatalogItemId());
922
			pendingOrderItem.setImgUrl(jsonObj.getString("imageUrl_s"));
923
			pendingOrder.setPendingOrderItems(Arrays.asList(pendingOrderItem));
924
			CustomerAddress customerAddress = customerAddressRepository.selectById(pendingOrder.getCustomerAddressId());
925
 
926
			DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy h:mm a");
927
 
928
			Map<String, Object> emailModel = new HashMap<>();
929
			emailModel.put("customer", customerAddress);
930
			emailModel.put("pendingOrder", pendingOrder);
931
			emailModel.put("date", dateTimeFormatter);
932
 
933
			String[] customerEmail = null;
934
			if (customer.getEmailId() != null) {
28355 tejbeer 935
				customerEmail = new String[] { customer.getEmailId() };
28339 tejbeer 936
 
28355 tejbeer 937
				List<String> bccTo = Arrays.asList("tejbeer.kaur@smartdukaan.com");
938
 
28339 tejbeer 939
				emailService.sendMailWithAttachments("Order Cancellation", "order-cancellation.vm", emailModel,
28355 tejbeer 940
						customerEmail, null, bccTo.toArray(new String[0]));
28339 tejbeer 941
 
942
			}
27048 tejbeer 943
		}
944
 
945
		return responseSender.ok(true);
946
 
947
	}
948
 
26774 amit.gupta 949
}
950
 
26784 amit.gupta 951
class UserModel {
26857 amit.gupta 952
	@JsonProperty(required = true)
26784 amit.gupta 953
	private String mobile;
26857 amit.gupta 954
	@JsonProperty(required = true)
26784 amit.gupta 955
	private String password;
26857 amit.gupta 956
	@JsonProperty(required = false)
957
	private String firstName;
958
	@JsonProperty(required = false)
959
	private String lastName;
960
	@JsonProperty(required = false)
961
	private String email;
26833 amit.gupta 962
 
26784 amit.gupta 963
	@Override
964
	public String toString() {
965
		return "UserModel [mobile=" + mobile + ", password=" + password + "]";
966
	}
26833 amit.gupta 967
 
26784 amit.gupta 968
	public String getMobile() {
969
		return mobile;
970
	}
26833 amit.gupta 971
 
26784 amit.gupta 972
	public void setMobile(String mobile) {
973
		this.mobile = mobile;
974
	}
26833 amit.gupta 975
 
26784 amit.gupta 976
	public String getPassword() {
977
		return password;
978
	}
26833 amit.gupta 979
 
26784 amit.gupta 980
	public void setPassword(String password) {
981
		this.password = password;
982
	}
26857 amit.gupta 983
 
984
	public String getFirstName() {
985
		return firstName;
986
	}
987
 
988
	public void setFirstName(String firstName) {
989
		this.firstName = firstName;
990
	}
991
 
992
	public String getLastName() {
993
		return lastName;
994
	}
995
 
996
	public void setLastName(String lastName) {
997
		this.lastName = lastName;
998
	}
999
 
1000
	public String getEmail() {
1001
		return email;
1002
	}
1003
 
1004
	public void setEmail(String email) {
1005
		this.email = email;
1006
	}
1007
 
26784 amit.gupta 1008
}
1009
 
26774 amit.gupta 1010
class CustomerModel {
26783 amit.gupta 1011
 
26774 amit.gupta 1012
	@JsonProperty(required = false)
1013
	private Customer customer;
1014
	@JsonProperty(required = true)
1015
	private boolean exists;
1016
 
1017
	public CustomerModel(boolean exists, Customer customer) {
1018
		super();
1019
		this.customer = customer;
1020
		this.exists = exists;
1021
	}
1022
 
1023
	@Override
1024
	public String toString() {
1025
		return "CustomerModel [customer=" + customer + ", exists=" + exists + "]";
1026
	}
1027
 
1028
	public Customer getCustomer() {
1029
		return customer;
1030
	}
1031
 
1032
	public void setCustomer(Customer customer) {
1033
		this.customer = customer;
1034
	}
1035
 
1036
	public boolean isExists() {
1037
		return exists;
1038
	}
1039
 
1040
	public void setExists(boolean exists) {
1041
		this.exists = exists;
1042
	}
26607 amit.gupta 1043
}