Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
21612 ashik.ali 1
package com.spice.profitmandi.web.controller;
2
 
21689 ashik.ali 3
import java.io.ByteArrayInputStream;
4
import java.io.ByteArrayOutputStream;
5
import java.io.InputStream;
21680 ashik.ali 6
import java.util.ArrayList;
7
import java.util.HashMap;
21612 ashik.ali 8
import java.util.HashSet;
21680 ashik.ali 9
import java.util.List;
10
import java.util.Map;
21612 ashik.ali 11
import java.util.Set;
12
 
13
import javax.servlet.http.HttpServletRequest;
21689 ashik.ali 14
import javax.servlet.http.HttpServletResponse;
21680 ashik.ali 15
import javax.transaction.Transactional;
21612 ashik.ali 16
 
17
import org.slf4j.Logger;
18
import org.slf4j.LoggerFactory;
19
import org.springframework.beans.factory.annotation.Autowired;
21689 ashik.ali 20
import org.springframework.core.io.InputStreamResource;
21
import org.springframework.http.HttpHeaders;
22
import org.springframework.http.HttpStatus;
23
import org.springframework.http.MediaType;
24
import org.springframework.http.ResponseEntity;
21612 ashik.ali 25
import org.springframework.stereotype.Controller;
26
import org.springframework.web.bind.annotation.RequestBody;
27
import org.springframework.web.bind.annotation.RequestMapping;
28
import org.springframework.web.bind.annotation.RequestMethod;
21689 ashik.ali 29
import org.springframework.web.bind.annotation.RequestParam;
21612 ashik.ali 30
 
31
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
21680 ashik.ali 32
import com.spice.profitmandi.common.model.CustomAddress;
21689 ashik.ali 33
import com.spice.profitmandi.common.model.CustomCustomer;
34
import com.spice.profitmandi.common.model.CustomFofoLineItem;
35
import com.spice.profitmandi.common.model.CustomFofoOrderItem;
36
import com.spice.profitmandi.common.model.CustomRetailer;
37
import com.spice.profitmandi.common.model.PdfModel;
21612 ashik.ali 38
import com.spice.profitmandi.common.model.ProfitMandiConstants;
21689 ashik.ali 39
import com.spice.profitmandi.common.util.PdfUtils;
21680 ashik.ali 40
import com.spice.profitmandi.common.util.StringUtils;
21728 ashik.ali 41
import com.spice.profitmandi.dao.entity.catalog.Item;
42
import com.spice.profitmandi.dao.entity.dtr.Retailer;
43
import com.spice.profitmandi.dao.entity.dtr.User;
44
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
45
import com.spice.profitmandi.dao.entity.fofo.Customer;
46
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
47
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
48
import com.spice.profitmandi.dao.entity.fofo.FofoLineItemSerialNumber;
49
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
50
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
51
import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;
52
import com.spice.profitmandi.dao.entity.fofo.PaymentOption;
53
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
54
import com.spice.profitmandi.dao.entity.transaction.LineItem;
55
import com.spice.profitmandi.dao.entity.transaction.Order;
56
import com.spice.profitmandi.dao.entity.user.Address;
57
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
58
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
59
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
60
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
61
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
62
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
63
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
64
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
65
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
66
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemSerialNumberRepository;
67
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
68
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
69
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
70
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
71
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
72
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
73
import com.spice.profitmandi.dao.repository.user.AddressRepository;
21612 ashik.ali 74
import com.spice.profitmandi.web.model.FofoDetails;
75
import com.spice.profitmandi.web.request.CreateOrderRequest;
76
import com.spice.profitmandi.web.request.CustomPaymentOption;
21680 ashik.ali 77
import com.spice.profitmandi.web.response.ItemIdQuantityAvailability;
78
import com.spice.profitmandi.web.response.Quantity;
21612 ashik.ali 79
import com.spice.profitmandi.web.util.CookiesFetcher;
80
import com.spice.profitmandi.web.util.MVCResponseSender;
81
 
82
@Controller
21680 ashik.ali 83
@Transactional
21612 ashik.ali 84
public class OrderController {
85
 
86
	private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
87
 
88
	@Autowired
89
	OrderRepository orderRepository;
90
 
91
	@Autowired
92
	InventoryItemRepository inventoryItemRepository;
93
 
94
	@Autowired
21680 ashik.ali 95
	CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
96
 
97
	@Autowired
98
	InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
99
 
100
	@Autowired
101
	CustomerRepository customerRepository;
102
 
103
	@Autowired
104
	AddressRepository addressRepository;
105
 
106
	@Autowired
107
	FofoLineItemSerialNumberRepository fofoLineItemSerialNumberRepository;
108
 
109
	@Autowired
110
	FofoLineItemRepository fofoLineItemRepository;
111
 
112
	@Autowired
113
	PaymentOptionRepository paymentOptionRepository;
114
 
115
	@Autowired
116
	ScanRecordRepository scanRecordRepository;
117
 
118
	@Autowired
119
	FofoOrderRepository fofoOrderRepository;
120
 
121
	@Autowired
21689 ashik.ali 122
	RetailerRepository retailerRepository;
123
 
124
	@Autowired
125
	UserRepository userRepository;
126
 
127
	@Autowired
128
	UserAccountRepository userAccountRepository;
129
 
130
	@Autowired
131
	RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
132
 
133
	@Autowired
21711 ashik.ali 134
	CustomerAddressRepository customerAddressRepository;
135
 
136
	@Autowired
21612 ashik.ali 137
	MVCResponseSender mvcResponseSender;
138
 
139
	@Autowired
140
	CookiesFetcher cookiesFetcher;
141
 
142
	@RequestMapping(value = "/order", method = RequestMethod.POST)
21680 ashik.ali 143
	public String createOrder(HttpServletRequest request, @RequestBody CreateOrderRequest createOrderRequest)  throws Throwable{
144
		//FofoDetails fofoDetails = cookiesFetcher.getCookiesObject(request);
145
		LOGGER.info("/order request {}", createOrderRequest);
146
		FofoDetails fofoDetails = new FofoDetails();
147
		fofoDetails.setFofoId(963490);
148
		Set<CustomFofoLineItem> fofoLineItems = createOrderRequest.getFofoLineItems();
149
		Set<Integer> itemIds = new HashSet<>();
150
		Set<Integer> nonSerializedItemIds = new HashSet<>();
151
		Map<Integer, Integer> itemIdQuantity = new HashMap<>();
152
		for(CustomFofoLineItem fofoLineItem : fofoLineItems){
153
			itemIds.add(fofoLineItem.getItemId());
154
			if(fofoLineItem.getSerialNumbers().size() > 0 && fofoLineItem.getQuantity() != fofoLineItem.getSerialNumbers().size()){
155
				itemIdQuantity.put(fofoLineItem.getItemId(), fofoLineItem.getQuantity());
156
			}
157
			if(fofoLineItem.getSerialNumbers().isEmpty()){
158
				nonSerializedItemIds.add(fofoLineItem.getItemId());
159
			}
160
		}
161
		if(!itemIdQuantity.isEmpty()){
162
			// if item quantity does not match with given serialnumbers size
163
			LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
164
			return "error";
165
		}
166
		float totalAmount = 0;
167
		Map<Integer, Float> lineItemPrice = new HashMap<>();
168
		List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoDetails.getFofoId(), itemIds);
169
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); 
170
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
171
			for(CustomFofoLineItem fofoLineItem : fofoLineItems){
172
				if(currentInventorySnapshot.getId().getItemId() == fofoLineItem.getItemId()){
173
					if(fofoLineItem.getQuantity() > currentInventorySnapshot.getAvailability()){
174
						ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
175
						itemIdQuantityAvailability.setItemId(fofoLineItem.getItemId());
176
						Quantity quantity = new Quantity();
177
						quantity.setAvailable(currentInventorySnapshot.getAvailability());
178
						quantity.setRequested(fofoLineItem.getQuantity());
179
						itemIdQuantityAvailability.setQuantity(quantity);
180
						itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
181
					}
182
				}
183
				if(!(fofoLineItem.getSellingPrice() > 0)){
184
					lineItemPrice.put(fofoLineItem.getItemId(), fofoLineItem.getSellingPrice());
185
				}else{
21689 ashik.ali 186
					totalAmount = totalAmount + fofoLineItem.getSellingPrice() * fofoLineItem.getQuantity();
21680 ashik.ali 187
				}
188
			}
189
		}
21612 ashik.ali 190
 
21680 ashik.ali 191
		try{
192
			this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
193
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
194
			LOGGER.error("Error occured while validating payment options : ", profitMandiBusinessException);
195
			return "error";
196
		}
21689 ashik.ali 197
 
21680 ashik.ali 198
		if(!itemIdQuantityAvailabilities.isEmpty()){
199
			// itemIdQuantity request is not valid
200
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
201
			return "error";
202
		}
203
 
204
		if(!lineItemPrice.isEmpty()){
205
			// given fofo line item price must be greater than zero
206
			LOGGER.error("requested itemId's selling price must greater thant 0");
207
			return "error";
208
		}
209
 
210
		Set<Integer> invalidItemIdSerialNumbers = new HashSet<>();
211
		Map<Integer, Set<String>> itemIdSerialNumbers = new HashMap<>();
212
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoDetails.getFofoId(), itemIds);
213
		if(inventoryItems.isEmpty()){
214
			// invalid item ids
215
			LOGGER.error("Requested itemId's are not available in inventoryItem");
216
			return "error";
217
		}
218
 
21711 ashik.ali 219
		Map<Integer, Float> itemIdPriceDropAmount = new HashMap<>();
220
 
21680 ashik.ali 221
		for(InventoryItem inventoryItem : inventoryItems){
222
			for(CustomFofoLineItem fofoLineItem : fofoLineItems){
223
				if(inventoryItem.getItemId() == fofoLineItem.getItemId()){
224
					if(fofoLineItem.getSerialNumbers().isEmpty()){
225
						if(!(inventoryItem.getSerialNumber() == null && inventoryItem.getSerialNumber().equals(""))){
226
							invalidItemIdSerialNumbers.add(inventoryItem.getItemId());
227
						}
228
					}
229
					if(!fofoLineItem.getSerialNumbers().isEmpty()){
230
						if(!fofoLineItem.getSerialNumbers().contains(inventoryItem.getSerialNumber())){
231
							if(!itemIdSerialNumbers.containsKey(fofoLineItem.getItemId())){
232
								Set<String> serialNumbers = new HashSet<>();
233
								serialNumbers.add(inventoryItem.getSerialNumber());
234
								itemIdSerialNumbers.put(fofoLineItem.getItemId(), serialNumbers);
235
							}else{
236
								itemIdSerialNumbers.get(fofoLineItem.getItemId()).add(inventoryItem.getSerialNumber());
237
							}
238
						}
239
					}
21711 ashik.ali 240
					itemIdPriceDropAmount.put(inventoryItem.getItemId(), inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount());
21680 ashik.ali 241
				}
242
			}
243
		}
244
 
245
		if(!invalidItemIdSerialNumbers.isEmpty()){
246
			LOGGER.error("Invalid itemId's serialNumbers {}", invalidItemIdSerialNumbers);
247
			// itemId's are serialized you are saying these are not serialized
248
			return "error";
249
		}
250
 
251
		if(!itemIdSerialNumbers.isEmpty()){
252
			LOGGER.error("Invalid itemId's serialNumbers {}", itemIdSerialNumbers);
253
			// itemId's are non serialized you are saying these are serialized
254
			return "error";
255
		}
256
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
257
		try{
258
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoDetails.getFofoId());
259
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
260
			invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
261
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
262
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
263
			invoiceNumberGenerationSequence.setFofoId(fofoDetails.getFofoId());
264
			invoiceNumberGenerationSequence.setPrefix("INVOICE");
265
			invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
266
		}
267
 
268
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
269
 
270
		if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
271
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
272
			return "error";
273
		}
274
 
275
		if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
276
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
277
			return "error";
278
		}
279
 
280
		Customer customer = null;
281
		try{
282
			customer = customerRepository.selectByEmailIdAndMobileNumber(customCustomer.getEmailId(), customCustomer.getMobileNumber());
283
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
284
			LOGGER.error("Error : ", profitMandiBusinessException);
285
			customer = new Customer();
21689 ashik.ali 286
			customCustomer.setName(customCustomer.getName());
21680 ashik.ali 287
			customer.setEmailId(customCustomer.getEmailId());
288
			customer.setMobileNumber(customCustomer.getMobileNumber());
289
			customerRepository.persist(customer);
290
		}
21711 ashik.ali 291
		CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress());
292
		customerAddress.setCustomerId(customer.getId());
293
		customerAddressRepository.persist(customerAddress);
21680 ashik.ali 294
 
295
			/*InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = */
296
 
297
 
298
		FofoOrder fofoOrder = new FofoOrder();
299
		fofoOrder.setCustomerId(customer.getId());
300
		fofoOrder.setFofoId(fofoDetails.getFofoId());
301
		fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
302
		fofoOrder.setTotalAmount(totalAmount);
303
		fofoOrderRepository.persist(fofoOrder);
304
 
305
		for(CustomPaymentOption customPaymentOption : createOrderRequest.getPaymentOptions()){
306
			PaymentOption paymentOption = new PaymentOption();
307
			paymentOption.setOrderId(fofoOrder.getId());
308
			paymentOption.setAmount(customPaymentOption.getAmount());
309
			paymentOption.setType(customPaymentOption.getType());
310
			paymentOptionRepository.persist(paymentOption);
311
		}
312
 
313
		List<Order> orders = orderRepository.selectByRetailerIdItemIds(fofoDetails.getFofoId(), itemIds);
314
 
315
		Set<Item> items = new HashSet<>(itemIds.size());
316
		for(Order order : orders){
317
			LineItem lineItem = order.getLineItem();
318
			items.add(lineItem.getItem());
319
		}
320
 
321
		if(items.size() != itemIds.size()){
322
			LOGGER.error("Requested ItemIds not found in catalog");
323
			// invalid itemIds 
324
			return "error";
325
		}
326
 
327
		Map<Integer, Map<String, String>> itemIdDetails = this.toMap(items);
328
 
329
		for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
330
			FofoLineItem fofoLineItem = new FofoLineItem();
331
			fofoLineItem.setItemId(customFofoLineItem.getItemId());
332
			fofoLineItem.setQuantity(customFofoLineItem.getQuantity());
21690 ashik.ali 333
			fofoLineItem.setSellingPrice(customFofoLineItem.getSellingPrice());
21680 ashik.ali 334
			fofoLineItem.setOrderId(fofoOrder.getId());
335
			fofoLineItem.setDp(customFofoLineItem.getSellingPrice());
21689 ashik.ali 336
			fofoLineItem.setTax(0);
337
			fofoLineItem.setTaxRate(0);
21711 ashik.ali 338
			fofoLineItem.setCost(itemIdPriceDropAmount.get(customFofoLineItem.getItemId()));
21680 ashik.ali 339
			Map<String, String> itemIdDetail = itemIdDetails.get(customFofoLineItem.getItemId());
340
			fofoLineItem.setBrand(itemIdDetail.get(ProfitMandiConstants.BRAND));
341
			fofoLineItem.setModelName(itemIdDetail.get(ProfitMandiConstants.MODEL_NAME));
342
			fofoLineItem.setModelNumber(itemIdDetail.get(ProfitMandiConstants.MODEL_NUMBER));
343
			fofoLineItem.setColor(itemIdDetail.get(ProfitMandiConstants.COLOR));
344
			fofoLineItemRepository.persist(fofoLineItem);
345
			LOGGER.info("\n\n");
346
			if(!customFofoLineItem.getSerialNumbers().isEmpty()){
347
				for(String serialNumber : customFofoLineItem.getSerialNumbers()){
348
					FofoLineItemSerialNumber fofoLineItemSerialNumber = new FofoLineItemSerialNumber();
349
					fofoLineItemSerialNumber.setFofoLineItemId(fofoLineItem.getId());
350
					fofoLineItemSerialNumber.setSerialNumber(serialNumber);
351
					fofoLineItemSerialNumberRepository.persist(fofoLineItemSerialNumber);
352
				}
353
			}
354
 
355
 
356
 
357
 
358
			for(InventoryItem inventoryItem : inventoryItems){
359
				if(inventoryItem.getItemId() == fofoLineItem.getItemId()){
360
					if(inventoryItem.getSerialNumber() == null || inventoryItem.getSerialNumber().isEmpty()){
361
						if(fofoLineItem.getQuantity() > 0)
362
						if(fofoLineItem.getQuantity() <= inventoryItem.getGoodQuantity()){
363
							inventoryItem.setGoodQuantity(inventoryItem.getGoodQuantity() - fofoLineItem.getQuantity());
364
							inventoryItem.setLastScanType(ScanType.SALE);
365
							inventoryItemRepository.persist(inventoryItem);
366
							ScanRecord scanRecord = new ScanRecord();
367
							scanRecord.setInventoryItemId(inventoryItem.getId());
368
							scanRecord.setFofoId(fofoDetails.getFofoId());
369
							scanRecord.setQuantity(fofoLineItem.getQuantity());
370
							scanRecord.setType(ScanType.SALE);
371
							scanRecordRepository.persist(scanRecord);
372
						}else{
373
							int availableGoodQuantity = inventoryItem.getGoodQuantity();
374
							inventoryItem.setGoodQuantity(0);
375
							fofoLineItem.setQuantity(fofoLineItem.getQuantity() - availableGoodQuantity);
376
							inventoryItem.setLastScanType(ScanType.SALE);
377
							inventoryItemRepository.persist(inventoryItem);
378
							ScanRecord scanRecord = new ScanRecord();
379
							scanRecord.setInventoryItemId(inventoryItem.getId());
380
							scanRecord.setFofoId(fofoDetails.getFofoId());
381
							scanRecord.setQuantity(availableGoodQuantity);
382
							scanRecord.setType(ScanType.SALE);
383
							scanRecordRepository.persist(scanRecord);
384
						}
385
					}else{
386
						inventoryItem.setGoodQuantity(0);
387
						inventoryItem.setLastScanType(ScanType.SALE);
388
						inventoryItemRepository.persist(inventoryItem);
389
						ScanRecord scanRecord = new ScanRecord();
390
						scanRecord.setInventoryItemId(inventoryItem.getId());
391
						scanRecord.setFofoId(fofoDetails.getFofoId());
392
						scanRecord.setQuantity(1);
393
						scanRecord.setType(ScanType.SALE);
394
						scanRecordRepository.persist(scanRecord);
395
					}
396
				}
397
			}
398
 
399
		}
21612 ashik.ali 400
		return null;
401
	}
402
 
21680 ashik.ali 403
 
404
	private Map<Integer, Map<String, String>> toMap(Set<Item> items){
405
		Map<Integer, Map<String, String>> map = new HashMap<>();
406
		for(Item item : items){
407
			Map<String, String> detailMap = new HashMap<>();
408
			detailMap.put(ProfitMandiConstants.BRAND, item.getBrand());
409
			detailMap.put(ProfitMandiConstants.MODEL_NAME, item.getModelName());
410
			detailMap.put(ProfitMandiConstants.MODEL_NUMBER, item.getModelNumber());
411
			detailMap.put(ProfitMandiConstants.COLOR, item.getColor());
412
			map.put(item.getId(), detailMap);
413
		}
414
		return map;
415
	}
416
 
21711 ashik.ali 417
	/*private Address createAddress(CustomAddress customAddress){
21680 ashik.ali 418
		Address address = new Address();
419
		address.setName(customAddress.getName());
420
		address.setLine1(customAddress.getLine1());
421
		address.setLine2(customAddress.getLine2());
422
		address.setLandmark(customAddress.getLandmark());
423
		address.setCity(customAddress.getCity());
424
		address.setPinCode(customAddress.getPinCode());
425
		address.setState(customAddress.getState());
426
		address.setCountry(customAddress.getCountry());
427
		address.setPhoneNumber(customAddress.getPhoneNumber());
428
		address.setEnabled(true);
429
		return address;
21711 ashik.ali 430
	}*/
431
 
432
	private CustomerAddress createCustomerAddress(CustomAddress customAddress){
433
		CustomerAddress customerAddress = new CustomerAddress();
434
		customerAddress.setName(customAddress.getName());
435
		customerAddress.setLine1(customAddress.getLine1());
436
		customerAddress.setLine2(customAddress.getLine2());
437
		customerAddress.setLandmark(customAddress.getLandmark());
438
		customerAddress.setCity(customAddress.getCity());
439
		customerAddress.setPinCode(customAddress.getPinCode());
440
		customerAddress.setState(customAddress.getState());
441
		customerAddress.setCountry(customAddress.getCountry());
442
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
443
		return customerAddress;
21680 ashik.ali 444
	}
445
 
21689 ashik.ali 446
	private CustomAddress createCustomAddress(Address address){
447
		CustomAddress customAddress = new CustomAddress();
448
		customAddress.setName(address.getName());
449
		customAddress.setLine1(address.getLine1());
450
		customAddress.setLine2(address.getLine2());
451
		customAddress.setLandmark(address.getLandmark());
452
		customAddress.setCity(address.getCity());
453
		customAddress.setPinCode(address.getPinCode());
454
		customAddress.setState(address.getState());
455
		customAddress.setCountry(address.getCountry());
456
		customAddress.setPhoneNumber(address.getPhoneNumber());
457
		return customAddress;
21680 ashik.ali 458
	}
459
 
21711 ashik.ali 460
	private CustomAddress createCustomAddress(CustomerAddress customerAddress){
461
		CustomAddress customAddress = new CustomAddress();
462
		customAddress.setName(customerAddress.getName());
463
		customAddress.setLine1(customerAddress.getLine1());
464
		customAddress.setLine2(customerAddress.getLine2());
465
		customAddress.setLandmark(customerAddress.getLandmark());
466
		customAddress.setCity(customerAddress.getCity());
467
		customAddress.setPinCode(customerAddress.getPinCode());
468
		customAddress.setState(customerAddress.getState());
469
		customAddress.setCountry(customerAddress.getCountry());
470
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
471
		return customAddress;
472
	}
473
 
21680 ashik.ali 474
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount) throws ProfitMandiBusinessException
21612 ashik.ali 475
	{
476
		float calculatedAmount = 0;
477
		Set<String> paymentOptionTypes = new HashSet<>();
478
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
21680 ashik.ali 479
			if(paymentOptionTypes.contains(customPaymentOption.getType().name())){
21612 ashik.ali 480
				throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_TYPE, customPaymentOption.getType().name(), "");
21680 ashik.ali 481
			}else{
482
				paymentOptionTypes.add(customPaymentOption.getType().name());
483
				calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
21612 ashik.ali 484
			}
485
		}
486
		if(calculatedAmount != totalAmount){
487
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "");
488
		}
489
	}
490
 
21689 ashik.ali 491
 
492
	@RequestMapping(value = "/generateInvoice")
493
	public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId) throws Throwable{
494
		LOGGER.info("Request received at url {} with params {} ", request.getRequestURI(), request.getParameterMap());
495
		//FofoDetails fofoDetails = cookiesFetcher.getCookiesObject(request);
21701 ashik.ali 496
 
21689 ashik.ali 497
		FofoDetails fofoDetails = new FofoDetails();
498
		fofoDetails.setFofoId(963490);
499
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
500
		PdfModel pdfModel = new PdfModel();
501
		pdfModel.setAuther("profitmandi");
502
		pdfModel.setTitle("Retailer Invoice");
503
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
504
		CustomCustomer customCustomer = new CustomCustomer();
505
		customCustomer.setName(customer.getName());
506
		customCustomer.setEmailId(customer.getEmailId());
507
		customCustomer.setMobileNumber(customer.getMobileNumber());
21711 ashik.ali 508
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId()); 
21689 ashik.ali 509
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
510
		pdfModel.setCustomer(customCustomer);
511
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
512
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
513
 
514
		Retailer retailer = retailerRepository.selectById(fofoDetails.getFofoId());
515
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
516
		CustomRetailer customRetailer = new CustomRetailer();
517
		customRetailer.setBusinessName(retailer.getName());
518
		customRetailer.setMobileNumber(user.getMobileNumber());
519
		customRetailer.setTinNumber(retailer.getNumber());
520
		Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
521
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
522
		pdfModel.setRetailer(customRetailer);
523
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
524
 
525
		Set<CustomFofoOrderItem> customerFofoOrderItems = new HashSet<>();
526
		for(FofoLineItem fofoLineItem : fofoLineItems){
527
			CustomFofoOrderItem customFofoOrderItem = new CustomFofoOrderItem();
528
			customFofoOrderItem.setAmount(fofoLineItem.getQuantity() * fofoLineItem.getSellingPrice());
529
			customFofoOrderItem.setDescription(fofoLineItem.getBrand() + " " + fofoLineItem.getModelName() + " " + fofoLineItem.getModelNumber() + " " + fofoLineItem.getColor());
530
			float itemTotal = customFofoOrderItem.getAmount() - fofoLineItem.getTax();
531
			customFofoOrderItem.setRate(fofoLineItem.getSellingPrice());
532
			customFofoOrderItem.setQuantity(fofoLineItem.getQuantity());
533
			customFofoOrderItem.setTax(fofoLineItem.getTax());
534
			customFofoOrderItem.setTaxRate(fofoLineItem.getTaxRate());
535
			customFofoOrderItem.setItemTotal(itemTotal);
536
			customFofoOrderItem.setSerialNumbers(String.join(", ",this.toSerialNumbers(fofoLineItem.getFofoLineItemSerialNumbers())));
537
			customerFofoOrderItems.add(customFofoOrderItem);
538
		}
539
		pdfModel.setOrderItems(customerFofoOrderItems);
540
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
541
		PdfUtils.generateAndWrite(pdfModel, byteArrayOutputStream);
542
		//final MediaType mediaType=MediaType.parseMediaType(profilePhotoModel.getContentType().getValue());
543
		LOGGER.info("Pdf Stream length {}", byteArrayOutputStream.toByteArray().length);
544
        final HttpHeaders headers=new HttpHeaders();
545
        headers.setContentType(MediaType.APPLICATION_PDF);
546
        //headers.set("Content-Disposition", "retailerInvoice.pdf");
547
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
548
        final InputStream inputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
549
        final InputStreamResource inputStreamResource=new InputStreamResource(inputStream);
550
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
551
	}
552
 
553
	private Set<String> toSerialNumbers(Set<FofoLineItemSerialNumber> fofoLineItemSerialNumbers){
554
		Set<String> serialNumbers = new HashSet<>(fofoLineItemSerialNumbers.size());
555
		for(FofoLineItemSerialNumber fofoLineItemSerialNumber : fofoLineItemSerialNumbers){
556
			serialNumbers.add(fofoLineItemSerialNumber.getSerialNumber());
557
		}
558
		return serialNumbers;
559
	}
21612 ashik.ali 560
}