Subversion Repositories SmartDukaan

Rev

Rev 35415 | Go to most recent revision | 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") })
35435 amit 100
	@Transactional(readOnly = true)
29707 tejbeer 101
	public ResponseEntity<?> getCustomerByMobileNumber(HttpServletRequest request,
102
			@RequestParam(name = ProfitMandiConstants.MOBILE_NUMBER) String mobileNumber)
103
			throws ProfitMandiBusinessException {
104
		CustomCustomer customCustomer = null;
105
		LOGGER.info("Request Received at url {}", request.getRequestURI());
106
		try {
107
			Customer customer = customerRepository.selectByMobileNumber(mobileNumber);
108
			customCustomer = new CustomCustomer();
109
			customCustomer.setCustomerId(customer.getId());
110
			customCustomer.setEmailId(customer.getEmailId());
111
			customCustomer.setFirstName(customer.getFirstName());
112
			customCustomer.setLastName(customer.getLastName());
113
			customCustomer.setMobileNumber(customer.getMobileNumber());
114
			LOGGER.info(customer.getCustomerAddress());
35196 aman 115
			List<CustomerAddress> customerAddresses = customer.getCustomerAddress().stream().filter(c -> Boolean.TRUE.equals(c.getActive())).collect(Collectors.toList());
29707 tejbeer 116
			LOGGER.info(customerAddresses);
117
			if (!customerAddresses.isEmpty()) {
118
				List<CustomAddress> customAddresses = new ArrayList<>();
119
				for (CustomerAddress customerAddress : customerAddresses) {
120
					customAddresses.add(this.toCustomAddress(customerAddress));
121
				}
122
				customCustomer.setAddresses(customAddresses);
123
			}
124
		} catch (Exception e) {
125
			e.printStackTrace();
126
		}
127
		return responseSender.ok(customCustomer);
128
	}
129
 
130
	private CustomAddress toCustomAddress(CustomerAddress customerAddress) {
131
		CustomAddress customAddress = new CustomAddress();
132
		customAddress.setCity(customerAddress.getCity());
133
		customAddress.setCountry(customerAddress.getCountry());
134
		customAddress.setLandmark(customerAddress.getLandmark());
135
		customAddress.setLine1(customerAddress.getLine1());
136
		customAddress.setLine2(customerAddress.getLine2());
137
		customAddress.setName(customerAddress.getName());
138
		customAddress.setLastName(customerAddress.getLastName());
139
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
140
		customAddress.setPinCode(customerAddress.getPinCode());
141
		customAddress.setState(customerAddress.getState());
142
		customAddress.setId(customerAddress.getId());
35196 aman 143
		customAddress.setDefaultAddress(customerAddress.getDefault());
29707 tejbeer 144
		return customAddress;
145
	}
146
 
147
	@RequestMapping(value = "/customer/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
148
	@ApiImplicitParams({
149
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
150
	public ResponseEntity<?> addCustomer(HttpServletRequest request, @RequestBody CustomCustomer customCustomer)
151
			throws ProfitMandiBusinessException {
152
		Customer customer = new Customer();
153
		if (StringUtils.isEmpty(customCustomer.getFirstName())) {
154
			throw new ProfitMandiBusinessException("First Name", "Empty", "First Name required");
155
		}
156
		customer.setEmailId(customCustomer.getEmailId());
157
		customer.setFirstName(customCustomer.getFirstName());
158
		customer.setLastName(customCustomer.getLastName());
159
		customer.setMobileNumber(customCustomer.getMobileNumber());
160
		customer = customerService.addCustomer(customer);
161
		customCustomer.setCustomerId(customer.getId());
162
		return responseSender.ok(customCustomer);
163
 
164
	}
165
 
166
	@RequestMapping(value = "/customer/address", method = RequestMethod.POST)
167
	public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestParam int customerId,
168
			@RequestBody CustomAddress customAddress) {
169
		CustomerAddress customerAddress = this.toCustomerAddress(customerId, customAddress);
35196 aman 170
		customerAddress.setActive(true);
29707 tejbeer 171
		customerAddressRepository.persist(customerAddress);
172
		return responseSender.ok(this.toCustomAddress(customerAddress));
173
 
174
	}
175
 
176
	private CustomerAddress toCustomerAddress(int customerId, CustomAddress customAddress) {
177
		CustomerAddress customerAddress = new CustomerAddress();
178
		customerAddress.setCustomerId(customerId);
179
		customerAddress.setName(customAddress.getName());
180
		customerAddress.setLastName(customAddress.getLastName());
181
		customerAddress.setLine1(customAddress.getLine1());
182
		customerAddress.setLine2(customAddress.getLine2());
183
		customerAddress.setLandmark(customAddress.getLandmark());
184
		customerAddress.setCity(customAddress.getCity());
185
		customerAddress.setPinCode(customAddress.getPinCode());
186
		customerAddress.setState(customAddress.getState());
187
		customerAddress.setCountry(customAddress.getCountry());
188
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
189
 
190
		return customerAddress;
191
	}
192
 
193
	@RequestMapping(value = "/customer/order", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
194
	@ApiImplicitParams({
195
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
35435 amit 196
	@Transactional(readOnly = true)
29707 tejbeer 197
	public ResponseEntity<?> getOrderInvoiceDetail(HttpServletRequest request,
198
			@RequestParam(name = "offset") int offset, @RequestParam(name = "limit") int limit) throws Exception {
199
 
200
		int userId = (int) request.getAttribute("userId");
201
		UserCart uc = userAccountRepository.getUserCart(userId);
202
 
203
		List<CustomerOrderDetail> customerOrderDetails = new ArrayList<>();
204
		List<FofoOrder> fofoOrders = fofoOrderRepository.selectOrderByFofoId(uc.getUserId(), offset, limit);
205
 
35415 amit 206
		if (fofoOrders.isEmpty()) {
207
			return responseSender.ok(customerOrderDetails);
208
		}
29707 tejbeer 209
 
35415 amit 210
		// Filter out cancelled orders
211
		List<FofoOrder> activeOrders = fofoOrders.stream()
212
				.filter(fo -> fo.getCancelledTimestamp() == null)
213
				.collect(Collectors.toList());
29707 tejbeer 214
 
35415 amit 215
		if (activeOrders.isEmpty()) {
216
			return responseSender.ok(customerOrderDetails);
217
		}
29707 tejbeer 218
 
35415 amit 219
		// Batch fetch all order items for all orders at once
220
		List<Integer> orderIds = activeOrders.stream().map(FofoOrder::getId).collect(Collectors.toList());
221
		List<FofoOrderItem> allOrderItems = fofoOrderItemRepository.selectByOrderIds(orderIds);
222
		Map<Integer, List<FofoOrderItem>> orderItemsByOrderId = allOrderItems.stream()
223
				.collect(Collectors.groupingBy(FofoOrderItem::getOrderId));
29707 tejbeer 224
 
35415 amit 225
		// Batch fetch all customers
226
		List<Integer> customerIds = activeOrders.stream().map(FofoOrder::getCustomerId).distinct().collect(Collectors.toList());
227
		Map<Integer, Customer> customerMap = customerRepository.selectAllByIds(customerIds).stream()
228
				.collect(Collectors.toMap(Customer::getId, Function.identity()));
29707 tejbeer 229
 
35415 amit 230
		// Batch fetch all customer addresses
231
		List<Integer> addressIds = activeOrders.stream().map(FofoOrder::getCustomerAddressId).distinct().collect(Collectors.toList());
232
		Map<Integer, CustomerAddress> addressMap = customerAddressRepository.selectAllByIds(addressIds).stream()
233
				.collect(Collectors.toMap(CustomerAddress::getId, Function.identity()));
29707 tejbeer 234
 
35415 amit 235
		// Batch fetch all items
236
		Set<Integer> itemIds = allOrderItems.stream().map(FofoOrderItem::getItemId).collect(Collectors.toSet());
237
		Map<Integer, Item> itemMap = itemRepository.selectByIds(new ArrayList<>(itemIds)).stream()
238
				.collect(Collectors.toMap(Item::getId, Function.identity()));
29707 tejbeer 239
 
35415 amit 240
		// Batch fetch all line items
241
		Set<Integer> orderItemIds = allOrderItems.stream().map(FofoOrderItem::getId).collect(Collectors.toSet());
242
		List<FofoLineItem> allLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(orderItemIds);
243
		Map<Integer, List<FofoLineItem>> lineItemsByOrderItemId = allLineItems.stream()
244
				.collect(Collectors.groupingBy(FofoLineItem::getFofoOrderItemId));
29707 tejbeer 245
 
35415 amit 246
		// Fetch customer offers once outside the loops
247
		Map<Integer, List<CustomerOffer>> customerOffersMap = customerOfferRepository.getCustomerOffer(LocalDate.now().atStartOfDay());
248
		List<CustomerOffer> customerOffers = customerOffersMap.get(uc.getUserId());
249
		List<Integer> offerIds = (customerOffers != null && !customerOffers.isEmpty())
250
				? customerOffers.stream().map(CustomerOffer::getId).collect(Collectors.toList())
251
				: new ArrayList<>();
29707 tejbeer 252
 
35415 amit 253
		// Process orders using pre-fetched data
254
		for (FofoOrder fo : activeOrders) {
255
			List<FofoOrderItem> fofoOrderItems = orderItemsByOrderId.getOrDefault(fo.getId(), new ArrayList<>());
256
			Customer customer = customerMap.get(fo.getCustomerId());
257
			CustomerAddress customerAddress = addressMap.get(fo.getCustomerAddressId());
29707 tejbeer 258
 
35415 amit 259
			for (FofoOrderItem foi : fofoOrderItems) {
260
				Item item = itemMap.get(foi.getItemId());
261
				if (item != null) {
262
					foi.setItemName(item.getItemDescription());
263
				}
29707 tejbeer 264
 
35415 amit 265
				List<FofoLineItem> fofoLineItems = lineItemsByOrderItemId.getOrDefault(foi.getId(), new ArrayList<>());
29707 tejbeer 266
 
35415 amit 267
				CustomerOrderDetail customerOrderDetail = new CustomerOrderDetail();
29707 tejbeer 268
 
35415 amit 269
				List<String> serialNumbers = fofoLineItems.stream()
270
						.map(FofoLineItem::getSerialNumber)
271
						.filter(x -> x != null)
272
						.collect(Collectors.toList());
29707 tejbeer 273
 
35415 amit 274
				customerOrderDetail.setSerialNumber(serialNumbers);
29707 tejbeer 275
 
35415 amit 276
				if (customerAddress != null) {
277
					customerOrderDetail.setCustomerName(customerAddress.getName());
278
					customerOrderDetail.setCustomerMobile(customerAddress.getPhoneNumber());
279
					customerOrderDetail.setCustomerEmail(customer != null ? customer.getEmailId() : null);
280
					customerOrderDetail.setCustomerCity(customerAddress.getCity());
281
					customerOrderDetail.setCustomerState(customerAddress.getState());
282
				}
29707 tejbeer 283
 
35415 amit 284
				if (item != null) {
285
					customerOrderDetail.setBrand(item.getBrand());
286
					customerOrderDetail.setColor(item.getColor());
287
					customerOrderDetail.setModelName(item.getModelName());
288
					customerOrderDetail.setModelNumber(item.getModelNumber());
289
				}
290
				customerOrderDetail.setFofoOrderItemId(foi.getId());
291
				customerOrderDetail.setFofoOrderId(foi.getOrderId());
292
				customerOrderDetail.setItemId(foi.getItemId());
293
				customerOrderDetail.setQuantity(foi.getQuantity());
294
				customerOrderDetail.setTotalPrice(foi.getSellingPrice());
295
				customerOrderDetail.setCreatedTimeStamp(foi.getCreateTimestamp());
296
				customerOrderDetail.setInvoiceNumber(fo.getInvoiceNumber());
297
				customerOrderDetail.setCancelledTimestamp(fo.getCancelledTimestamp());
298
				customerOrderDetail.setInsurance(false);
29707 tejbeer 299
 
35415 amit 300
				if (!serialNumbers.isEmpty() && item != null) {
301
					if ("85171300".equals(item.getHsnCode())) {
302
						customerOrderDetail.setInsurance(true);
29707 tejbeer 303
					}
304
				}
35415 amit 305
 
306
				long offerCount = 0;
307
				if (!offerIds.isEmpty() && item != null) {
308
					List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
309
							.selectByOfferIds(offerIds, item.getCatalogItemId(), LocalDate.now());
310
					offerCount = customerOfferItems.size();
311
				}
312
 
313
				customerOrderDetail.setOfferCount(offerCount);
314
				customerOrderDetails.add(customerOrderDetail);
29707 tejbeer 315
			}
35415 amit 316
		}
29707 tejbeer 317
 
318
		return responseSender.ok(customerOrderDetails);
319
	}
320
 
321
}