Subversion Repositories SmartDukaan

Rev

Rev 35458 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
29707 tejbeer 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
4
import com.spice.profitmandi.common.model.CustomAddress;
5
import com.spice.profitmandi.common.model.CustomCustomer;
6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
7
import com.spice.profitmandi.common.solr.SolrService;
8
import com.spice.profitmandi.common.web.util.ResponseSender;
31147 tejbeer 9
import com.spice.profitmandi.dao.entity.catalog.CustomerOffer;
29707 tejbeer 10
import com.spice.profitmandi.dao.entity.catalog.CustomerOfferItem;
11
import com.spice.profitmandi.dao.entity.catalog.Item;
31048 amit.gupta 12
import com.spice.profitmandi.dao.entity.fofo.*;
29707 tejbeer 13
import com.spice.profitmandi.dao.model.CustomerOrderDetail;
14
import com.spice.profitmandi.dao.model.UserCart;
15
import com.spice.profitmandi.dao.repository.catalog.CustomerOfferItemRepository;
16
import com.spice.profitmandi.dao.repository.catalog.CustomerOfferRepository;
17
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
18
import com.spice.profitmandi.dao.repository.catalog.SamsungUpgradeOfferRepository;
19
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
31048 amit.gupta 20
import com.spice.profitmandi.dao.repository.fofo.*;
29707 tejbeer 21
import com.spice.profitmandi.service.CustomerService;
22
import com.spice.profitmandi.service.inventory.InventoryService;
23
import io.swagger.annotations.ApiImplicitParam;
24
import io.swagger.annotations.ApiImplicitParams;
31048 amit.gupta 25
import org.apache.logging.log4j.LogManager;
26
import org.apache.logging.log4j.Logger;
27
import org.springframework.beans.factory.annotation.Autowired;
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;
32
import org.springframework.util.StringUtils;
33
import org.springframework.web.bind.annotation.RequestBody;
34
import org.springframework.web.bind.annotation.RequestMapping;
35
import org.springframework.web.bind.annotation.RequestMethod;
36
import org.springframework.web.bind.annotation.RequestParam;
29707 tejbeer 37
 
31048 amit.gupta 38
import javax.servlet.http.HttpServletRequest;
39
import java.time.LocalDate;
40
import java.time.LocalDateTime;
41
import java.util.ArrayList;
42
import java.util.List;
35415 amit 43
import java.util.Map;
44
import java.util.Set;
45
import java.util.HashSet;
46
import java.util.function.Function;
31048 amit.gupta 47
import java.util.stream.Collectors;
48
 
29707 tejbeer 49
@Controller
50
@Transactional(rollbackFor = Throwable.class)
51
public class CustomerController {
52
 
53
	private static final Logger LOGGER = LogManager.getLogger(CustomerController.class);
54
 
55
	@Autowired
56
	private ResponseSender<?> responseSender;
57
 
58
	@Autowired
59
	private UserAccountRepository userAccountRepository;
60
 
61
	@Autowired
62
	private CustomerRepository customerRepository;
63
 
64
	@Autowired
65
	private InventoryService inventoryService;
66
 
67
	@Autowired
68
	private CustomerService customerService;
69
 
70
	@Autowired
71
	private CustomerAddressRepository customerAddressRepository;
72
 
73
	@Autowired
74
	private FofoOrderItemRepository fofoOrderItemRepository;
75
 
76
	@Autowired
77
	private SolrService commonSolrService;
78
 
79
	@Autowired
80
	private FofoLineItemRepository fofoLineItemRepository;
81
 
82
	@Autowired
83
	private ItemRepository itemRepository;
84
 
85
	@Autowired
86
	private FofoOrderRepository fofoOrderRepository;
87
 
88
	@Autowired
89
	private CustomerOfferRepository customerOfferRepository;
90
 
91
	@Autowired
92
	private CustomerOfferItemRepository customerOfferItemRepository;
93
 
94
	@Autowired
95
	private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
96
 
97
	@RequestMapping(value = "/customer/mobileNumber", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
98
	@ApiImplicitParams({
99
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
100
	public ResponseEntity<?> getCustomerByMobileNumber(HttpServletRequest request,
101
			@RequestParam(name = ProfitMandiConstants.MOBILE_NUMBER) String mobileNumber)
102
			throws ProfitMandiBusinessException {
103
		CustomCustomer customCustomer = null;
104
		LOGGER.info("Request Received at url {}", request.getRequestURI());
105
		try {
106
			Customer customer = customerRepository.selectByMobileNumber(mobileNumber);
107
			customCustomer = new CustomCustomer();
108
			customCustomer.setCustomerId(customer.getId());
109
			customCustomer.setEmailId(customer.getEmailId());
110
			customCustomer.setFirstName(customer.getFirstName());
111
			customCustomer.setLastName(customer.getLastName());
112
			customCustomer.setMobileNumber(customer.getMobileNumber());
113
			LOGGER.info(customer.getCustomerAddress());
35196 aman 114
			List<CustomerAddress> customerAddresses = customer.getCustomerAddress().stream().filter(c -> Boolean.TRUE.equals(c.getActive())).collect(Collectors.toList());
29707 tejbeer 115
			LOGGER.info(customerAddresses);
116
			if (!customerAddresses.isEmpty()) {
117
				List<CustomAddress> customAddresses = new ArrayList<>();
118
				for (CustomerAddress customerAddress : customerAddresses) {
119
					customAddresses.add(this.toCustomAddress(customerAddress));
120
				}
121
				customCustomer.setAddresses(customAddresses);
122
			}
123
		} catch (Exception e) {
124
			e.printStackTrace();
125
		}
126
		return responseSender.ok(customCustomer);
127
	}
128
 
129
	private CustomAddress toCustomAddress(CustomerAddress customerAddress) {
130
		CustomAddress customAddress = new CustomAddress();
131
		customAddress.setCity(customerAddress.getCity());
132
		customAddress.setCountry(customerAddress.getCountry());
133
		customAddress.setLandmark(customerAddress.getLandmark());
134
		customAddress.setLine1(customerAddress.getLine1());
135
		customAddress.setLine2(customerAddress.getLine2());
136
		customAddress.setName(customerAddress.getName());
137
		customAddress.setLastName(customerAddress.getLastName());
138
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
139
		customAddress.setPinCode(customerAddress.getPinCode());
140
		customAddress.setState(customerAddress.getState());
141
		customAddress.setId(customerAddress.getId());
35196 aman 142
		customAddress.setDefaultAddress(customerAddress.getDefault());
29707 tejbeer 143
		return customAddress;
144
	}
145
 
146
	@RequestMapping(value = "/customer/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
147
	@ApiImplicitParams({
148
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
149
	public ResponseEntity<?> addCustomer(HttpServletRequest request, @RequestBody CustomCustomer customCustomer)
150
			throws ProfitMandiBusinessException {
151
		Customer customer = new Customer();
152
		if (StringUtils.isEmpty(customCustomer.getFirstName())) {
153
			throw new ProfitMandiBusinessException("First Name", "Empty", "First Name required");
154
		}
155
		customer.setEmailId(customCustomer.getEmailId());
156
		customer.setFirstName(customCustomer.getFirstName());
157
		customer.setLastName(customCustomer.getLastName());
158
		customer.setMobileNumber(customCustomer.getMobileNumber());
159
		customer = customerService.addCustomer(customer);
160
		customCustomer.setCustomerId(customer.getId());
161
		return responseSender.ok(customCustomer);
162
 
163
	}
164
 
165
	@RequestMapping(value = "/customer/address", method = RequestMethod.POST)
166
	public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestParam int customerId,
167
			@RequestBody CustomAddress customAddress) {
168
		CustomerAddress customerAddress = this.toCustomerAddress(customerId, customAddress);
35196 aman 169
		customerAddress.setActive(true);
29707 tejbeer 170
		customerAddressRepository.persist(customerAddress);
171
		return responseSender.ok(this.toCustomAddress(customerAddress));
172
 
173
	}
174
 
36539 aman 175
	@RequestMapping(value = "/customer/address/update", method = RequestMethod.PUT)
176
	public ResponseEntity<?> updateAddress(HttpServletRequest request, @RequestParam int addressId,
177
			@RequestBody CustomAddress customAddress) {
178
		try {
179
			CustomerAddress customerAddress = customerAddressRepository.selectById(addressId);
180
			if (customAddress.getName() != null) customerAddress.setName(customAddress.getName());
181
			if (customAddress.getLastName() != null) customerAddress.setLastName(customAddress.getLastName());
182
			if (customAddress.getLine1() != null) customerAddress.setLine1(customAddress.getLine1());
183
			if (customAddress.getLine2() != null) customerAddress.setLine2(customAddress.getLine2());
184
			if (customAddress.getLandmark() != null) customerAddress.setLandmark(customAddress.getLandmark());
185
			if (customAddress.getCity() != null) customerAddress.setCity(customAddress.getCity());
186
			if (customAddress.getPinCode() != null) customerAddress.setPinCode(customAddress.getPinCode());
187
			if (customAddress.getState() != null) customerAddress.setState(customAddress.getState());
188
			if (customAddress.getCountry() != null) customerAddress.setCountry(customAddress.getCountry());
189
			if (customAddress.getPhoneNumber() != null) customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
190
			return responseSender.ok(this.toCustomAddress(customerAddress));
191
		} catch (ProfitMandiBusinessException e) {
192
			return responseSender.badRequest(e);
193
		}
194
	}
195
 
29707 tejbeer 196
	private CustomerAddress toCustomerAddress(int customerId, CustomAddress customAddress) {
197
		CustomerAddress customerAddress = new CustomerAddress();
198
		customerAddress.setCustomerId(customerId);
199
		customerAddress.setName(customAddress.getName());
200
		customerAddress.setLastName(customAddress.getLastName());
201
		customerAddress.setLine1(customAddress.getLine1());
202
		customerAddress.setLine2(customAddress.getLine2());
203
		customerAddress.setLandmark(customAddress.getLandmark());
204
		customerAddress.setCity(customAddress.getCity());
205
		customerAddress.setPinCode(customAddress.getPinCode());
206
		customerAddress.setState(customAddress.getState());
207
		customerAddress.setCountry(customAddress.getCountry());
208
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
209
 
210
		return customerAddress;
211
	}
212
 
213
	@RequestMapping(value = "/customer/order", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
214
	@ApiImplicitParams({
215
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
216
	public ResponseEntity<?> getOrderInvoiceDetail(HttpServletRequest request,
217
			@RequestParam(name = "offset") int offset, @RequestParam(name = "limit") int limit) throws Exception {
218
 
219
		int userId = (int) request.getAttribute("userId");
220
		UserCart uc = userAccountRepository.getUserCart(userId);
221
 
222
		List<CustomerOrderDetail> customerOrderDetails = new ArrayList<>();
223
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectOrderByFofoId(uc.getUserId(), offset, limit);
224
 
35415 amit 225
		if (fofoOrders.isEmpty()) {
226
			return responseSender.ok(customerOrderDetails);
227
		}
29707 tejbeer 228
 
35415 amit 229
		// Filter out cancelled orders
230
		List<FofoOrder> activeOrders = fofoOrders.stream()
231
				.filter(fo -> fo.getCancelledTimestamp() == null)
232
				.collect(Collectors.toList());
29707 tejbeer 233
 
35415 amit 234
		if (activeOrders.isEmpty()) {
235
			return responseSender.ok(customerOrderDetails);
236
		}
29707 tejbeer 237
 
35415 amit 238
		// Batch fetch all order items for all orders at once
239
		List<Integer> orderIds = activeOrders.stream().map(FofoOrder::getId).collect(Collectors.toList());
240
		List<FofoOrderItem> allOrderItems = fofoOrderItemRepository.selectByOrderIds(orderIds);
241
		Map<Integer, List<FofoOrderItem>> orderItemsByOrderId = allOrderItems.stream()
242
				.collect(Collectors.groupingBy(FofoOrderItem::getOrderId));
29707 tejbeer 243
 
35415 amit 244
		// Batch fetch all customers
245
		List<Integer> customerIds = activeOrders.stream().map(FofoOrder::getCustomerId).distinct().collect(Collectors.toList());
246
		Map<Integer, Customer> customerMap = customerRepository.selectAllByIds(customerIds).stream()
247
				.collect(Collectors.toMap(Customer::getId, Function.identity()));
29707 tejbeer 248
 
35415 amit 249
		// Batch fetch all customer addresses
250
		List<Integer> addressIds = activeOrders.stream().map(FofoOrder::getCustomerAddressId).distinct().collect(Collectors.toList());
251
		Map<Integer, CustomerAddress> addressMap = customerAddressRepository.selectAllByIds(addressIds).stream()
252
				.collect(Collectors.toMap(CustomerAddress::getId, Function.identity()));
29707 tejbeer 253
 
35415 amit 254
		// Batch fetch all items
255
		Set<Integer> itemIds = allOrderItems.stream().map(FofoOrderItem::getItemId).collect(Collectors.toSet());
256
		Map<Integer, Item> itemMap = itemRepository.selectByIds(new ArrayList<>(itemIds)).stream()
257
				.collect(Collectors.toMap(Item::getId, Function.identity()));
29707 tejbeer 258
 
35415 amit 259
		// Batch fetch all line items
260
		Set<Integer> orderItemIds = allOrderItems.stream().map(FofoOrderItem::getId).collect(Collectors.toSet());
261
		List<FofoLineItem> allLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(orderItemIds);
262
		Map<Integer, List<FofoLineItem>> lineItemsByOrderItemId = allLineItems.stream()
263
				.collect(Collectors.groupingBy(FofoLineItem::getFofoOrderItemId));
29707 tejbeer 264
 
35415 amit 265
		// Fetch customer offers once outside the loops
266
		Map<Integer, List<CustomerOffer>> customerOffersMap = customerOfferRepository.getCustomerOffer(LocalDate.now().atStartOfDay());
267
		List<CustomerOffer> customerOffers = customerOffersMap.get(uc.getUserId());
268
		List<Integer> offerIds = (customerOffers != null && !customerOffers.isEmpty())
269
				? customerOffers.stream().map(CustomerOffer::getId).collect(Collectors.toList())
270
				: new ArrayList<>();
29707 tejbeer 271
 
35415 amit 272
		// Process orders using pre-fetched data
273
		for (FofoOrder fo : activeOrders) {
274
			List<FofoOrderItem> fofoOrderItems = orderItemsByOrderId.getOrDefault(fo.getId(), new ArrayList<>());
275
			Customer customer = customerMap.get(fo.getCustomerId());
276
			CustomerAddress customerAddress = addressMap.get(fo.getCustomerAddressId());
29707 tejbeer 277
 
35415 amit 278
			for (FofoOrderItem foi : fofoOrderItems) {
279
				Item item = itemMap.get(foi.getItemId());
280
				if (item != null) {
281
					foi.setItemName(item.getItemDescription());
282
				}
29707 tejbeer 283
 
35415 amit 284
				List<FofoLineItem> fofoLineItems = lineItemsByOrderItemId.getOrDefault(foi.getId(), new ArrayList<>());
29707 tejbeer 285
 
35415 amit 286
				CustomerOrderDetail customerOrderDetail = new CustomerOrderDetail();
29707 tejbeer 287
 
35415 amit 288
				List<String> serialNumbers = fofoLineItems.stream()
289
						.map(FofoLineItem::getSerialNumber)
290
						.filter(x -> x != null)
291
						.collect(Collectors.toList());
29707 tejbeer 292
 
35415 amit 293
				customerOrderDetail.setSerialNumber(serialNumbers);
29707 tejbeer 294
 
35415 amit 295
				if (customerAddress != null) {
296
					customerOrderDetail.setCustomerName(customerAddress.getName());
297
					customerOrderDetail.setCustomerMobile(customerAddress.getPhoneNumber());
298
					customerOrderDetail.setCustomerEmail(customer != null ? customer.getEmailId() : null);
299
					customerOrderDetail.setCustomerCity(customerAddress.getCity());
300
					customerOrderDetail.setCustomerState(customerAddress.getState());
301
				}
29707 tejbeer 302
 
35415 amit 303
				if (item != null) {
304
					customerOrderDetail.setBrand(item.getBrand());
305
					customerOrderDetail.setColor(item.getColor());
306
					customerOrderDetail.setModelName(item.getModelName());
307
					customerOrderDetail.setModelNumber(item.getModelNumber());
308
				}
309
				customerOrderDetail.setFofoOrderItemId(foi.getId());
310
				customerOrderDetail.setFofoOrderId(foi.getOrderId());
311
				customerOrderDetail.setItemId(foi.getItemId());
312
				customerOrderDetail.setQuantity(foi.getQuantity());
313
				customerOrderDetail.setTotalPrice(foi.getSellingPrice());
314
				customerOrderDetail.setCreatedTimeStamp(foi.getCreateTimestamp());
315
				customerOrderDetail.setInvoiceNumber(fo.getInvoiceNumber());
316
				customerOrderDetail.setCancelledTimestamp(fo.getCancelledTimestamp());
317
				customerOrderDetail.setInsurance(false);
29707 tejbeer 318
 
35415 amit 319
				if (!serialNumbers.isEmpty() && item != null) {
320
					if ("85171300".equals(item.getHsnCode())) {
321
						customerOrderDetail.setInsurance(true);
29707 tejbeer 322
					}
323
				}
35415 amit 324
 
325
				long offerCount = 0;
326
				if (!offerIds.isEmpty() && item != null) {
327
					List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
328
							.selectByOfferIds(offerIds, item.getCatalogItemId(), LocalDate.now());
329
					offerCount = customerOfferItems.size();
330
				}
331
 
332
				customerOrderDetail.setOfferCount(offerCount);
333
				customerOrderDetails.add(customerOrderDetail);
29707 tejbeer 334
			}
35415 amit 335
		}
29707 tejbeer 336
 
337
		return responseSender.ok(customerOrderDetails);
338
	}
339
 
340
}