Subversion Repositories SmartDukaan

Rev

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