Subversion Repositories SmartDukaan

Rev

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