Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
22866 ashik.ali 1
package com.spice.profitmandi.web.controller;
2
 
22889 amit.gupta 3
import java.io.ByteArrayOutputStream;
4
import java.io.File;
5
import java.io.FileOutputStream;
6
import java.io.IOException;
7
import java.io.OutputStream;
8
import java.text.MessageFormat;
9
import java.time.LocalDate;
22907 amit.gupta 10
import java.time.LocalDateTime;
22889 amit.gupta 11
import java.time.format.DateTimeFormatter;
22932 amit.gupta 12
import java.util.ArrayList;
22889 amit.gupta 13
import java.util.Arrays;
14
import java.util.HashSet;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Set;
18
 
19
import javax.mail.internet.InternetAddress;
20
import javax.mail.internet.MimeMessage;
22866 ashik.ali 21
import javax.servlet.http.HttpServletRequest;
22
 
22889 amit.gupta 23
import org.apache.commons.io.FileUtils;
22866 ashik.ali 24
import org.slf4j.Logger;
25
import org.slf4j.LoggerFactory;
26
import org.springframework.beans.factory.annotation.Autowired;
27
import org.springframework.http.ResponseEntity;
22889 amit.gupta 28
import org.springframework.mail.javamail.JavaMailSender;
29
import org.springframework.mail.javamail.MimeMessageHelper;
22866 ashik.ali 30
import org.springframework.stereotype.Controller;
31
import org.springframework.transaction.annotation.Transactional;
22889 amit.gupta 32
import org.springframework.web.bind.annotation.RequestBody;
22866 ashik.ali 33
import org.springframework.web.bind.annotation.RequestMapping;
34
import org.springframework.web.bind.annotation.RequestMethod;
35
 
22889 amit.gupta 36
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
37
import com.spice.profitmandi.common.model.CustomAddress;
38
import com.spice.profitmandi.common.model.CustomCustomer;
39
import com.spice.profitmandi.common.model.CustomInsurancePolicy;
40
import com.spice.profitmandi.common.model.CustomOrderItem;
41
import com.spice.profitmandi.common.model.CustomRetailer;
42
import com.spice.profitmandi.common.model.GadgetCopsDocumentInsuranceModel;
22932 amit.gupta 43
import com.spice.profitmandi.common.model.GadgetCopsInsuranceCalcResponse;
22889 amit.gupta 44
import com.spice.profitmandi.common.model.PdfModel;
22866 ashik.ali 45
import com.spice.profitmandi.common.model.ProfitMandiConstants;
22889 amit.gupta 46
import com.spice.profitmandi.common.util.InsuranceUtils;
47
import com.spice.profitmandi.common.util.PdfUtils;
48
import com.spice.profitmandi.common.util.StringUtils;
49
import com.spice.profitmandi.common.util.Utils;
22866 ashik.ali 50
import com.spice.profitmandi.common.web.util.ResponseSender;
22889 amit.gupta 51
import com.spice.profitmandi.dao.entity.dtr.Document;
52
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
53
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
54
import com.spice.profitmandi.dao.entity.dtr.InsuranceProvider;
55
import com.spice.profitmandi.dao.entity.dtr.PolicyNumberGenerationSequence;
56
import com.spice.profitmandi.dao.entity.dtr.ThirdPartyInvoiceSequence;
57
import com.spice.profitmandi.dao.enumuration.dtr.ThirdParty;
58
import com.spice.profitmandi.dao.model.UserCart;
59
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
22866 ashik.ali 60
import com.spice.profitmandi.dao.repository.dtr.GadgetCopsInsuranceCalcRepository;
22889 amit.gupta 61
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
62
import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;
63
import com.spice.profitmandi.dao.repository.dtr.PolicyNumberGenerationSequenceRepository;
64
import com.spice.profitmandi.dao.repository.dtr.ThirdPartyInvoiceSequenceRepository;
65
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
66
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
22898 amit.gupta 67
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
22889 amit.gupta 68
import com.spice.profitmandi.service.pricing.PricingService;
69
import com.spice.profitmandi.service.wallet.WalletService;
22866 ashik.ali 70
 
22889 amit.gupta 71
import in.shop2020.model.v1.order.WalletReferenceType;
72
 
22866 ashik.ali 73
@Controller
22889 amit.gupta 74
@Transactional(rollbackFor = Throwable.class)
22866 ashik.ali 75
public class InsuranceController {
22889 amit.gupta 76
	private static final Logger LOGGER = LoggerFactory.getLogger(InsuranceController.class);
77
	private static final String gadgetCopsFilePath = "/GadgetCops";
22866 ashik.ali 78
 
79
	@Autowired
22889 amit.gupta 80
	private GadgetCopsInsuranceCalcRepository gadgetCopsInsuranceCalcRepository;
81
 
82
	@RequestMapping(value = ProfitMandiConstants.URL_INSURANCE_GADGET_COPS_MAPPING, method = RequestMethod.GET)
83
	public ResponseEntity<?> getById(HttpServletRequest request) {
84
		LOGGER.info("requested url : " + request.getRequestURL().toString());
22932 amit.gupta 85
		List<GadgetCopsInsuranceCalc> calcList = gadgetCopsInsuranceCalcRepository.selectAll();
86
 
87
		return responseSender.ok(this.toCalcResponseList(calcList));
22889 amit.gupta 88
	}
89
 
90
	@Autowired
22866 ashik.ali 91
	ResponseSender<?> responseSender;
22889 amit.gupta 92
 
93
	@Autowired
94
	ThirdPartyInvoiceSequenceRepository thirdPartyInvoiceSequenceRepository;
95
 
96
	@Autowired
97
	DocumentRepository documentRepository;
98
 
99
	@Autowired
100
	InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
22866 ashik.ali 101
 
22889 amit.gupta 102
	@Autowired
103
	InsurancePolicyRepository insurancePolicyRepository;
104
 
105
	@Autowired
106
	PricingService pricingService;
22866 ashik.ali 107
 
108
	@Autowired
22889 amit.gupta 109
	JavaMailSender mailSender;
110
 
111
	@Autowired
112
	InsuranceProviderRepository insuranceProviderRepository;
113
 
114
	@Autowired
115
	UserAccountRepository userAccountRepository;
22866 ashik.ali 116
 
22889 amit.gupta 117
	@Autowired
118
	WalletService walletService;
119
 
120
	@Autowired
22898 amit.gupta 121
	UserWalletRepository userWalletRepositoy;
122
 
123
	@Autowired
22889 amit.gupta 124
	PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
125
 
126
	@RequestMapping(value = ProfitMandiConstants.URL_DAMAGE_INSURANCE, method = RequestMethod.POST)
127
	public ResponseEntity<?> createTheftProtection(HttpServletRequest request,
128
			@RequestBody GadgetCopsDocumentInsuranceModel insuranceModel) throws Throwable {
22894 amit.gupta 129
		insuranceModel.setCustomerDateOfBirth(StringUtils.fromHypendatedDate(insuranceModel.getCustomerDateOfBirthString()));
22896 amit.gupta 130
		insuranceModel.setInvoiceCreationDate(LocalDate.now());
22893 amit.gupta 131
		insuranceModel.validate();
132
		int userId = (int) request.getAttribute("userId");
133
		UserCart uc = userAccountRepository.getUserCart(userId);
134
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
135
		try {
136
			policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
137
			policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
138
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
139
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
140
			policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
141
			policyNumberGenerationSequence.setSequence(1);
142
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
143
		}
144
		String policyNumber = StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX,
145
				policyNumberGenerationSequence.getSequence());
22889 amit.gupta 146
 
22893 amit.gupta 147
		InsuranceProvider insuranceProvider = insuranceProviderRepository
148
				.selectByName(ProfitMandiConstants.GADGET_COPS);
149
		Set<Float> devicePriceSet = new HashSet<>();
150
		devicePriceSet.add(insuranceModel.getPrice());
151
		Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(devicePriceSet,
152
				ProfitMandiConstants.GADGET_COPS);
153
		InsurancePolicy insurancePolicy = new InsurancePolicy();
154
		insurancePolicy.setInvoiceNumber(insuranceModel.getInvoiceNumber());
155
		insurancePolicy.setRetailerId(uc.getUserId());
156
		insurancePolicy.setPurchaseAmount(insurancePricesMap.get(insuranceModel.getPrice()).getDealerPrice());
157
		insurancePolicy.setSaleAmount(insurancePricesMap.get(insuranceModel.getPrice()).getSellingPrice());
158
		insurancePolicy.setSellingPrice(insuranceModel.getPrice());
159
		insurancePolicy.setSerialNumber(insuranceModel.getSerialNumber());
160
		insurancePolicy.setModelName(insuranceModel.getModelName());
161
		insurancePolicy.setBrand(insuranceModel.getBrand());
162
		insurancePolicy.setPolicyNumber(policyNumber);
163
		insurancePolicy.setProviderId(insuranceProvider.getId());
164
		insurancePolicy.setCustomerFirstName(insuranceModel.getCustomerFirstName());
165
		insurancePolicy.setCustomerLastName(insuranceModel.getCustomerFirstName());
166
		insurancePolicy.setCustomerMobileNumber(insuranceModel.getCustomerMobileNumber());
167
		insurancePolicy.setCustomerEmailId(insuranceModel.getCustomerEmailId());
168
		insurancePolicy.setCustomerDateOfBirth(insuranceModel.getCustomerDateOfBirth());
169
		insurancePolicy.setCustomerAddress1(insuranceModel.getCustomerAddress1());
170
		insurancePolicy.setCustomerAddress2(insuranceModel.getCustomerAddress2());
171
		insurancePolicy.setCustomerCity(insuranceModel.getCustomerCity());
172
		insurancePolicy.setCustomerPinCode(insuranceModel.getCustomerPinCode());
173
		insurancePolicy.setCustomerState(insuranceModel.getCustomerState());
174
		insurancePolicyRepository.persist(insurancePolicy);
22915 amit.gupta 175
		insuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
22913 amit.gupta 176
		String walletDescription = "Purchased Damage Protection policy " + insurancePolicy.getPolicyNumber() 
177
			+ " for " + insurancePolicy.getCustomerFirstName();
22893 amit.gupta 178
 
22913 amit.gupta 179
		walletService.consumeAmountFromWallet(uc.getUserId(), insurancePolicy.getId(), WalletReferenceType.DAMAGE_PROTECTION, walletDescription, insurancePolicy.getSaleAmount());
22898 amit.gupta 180
 
22893 amit.gupta 181
		try{
182
			InsuranceUtils.submitToGadgetCops(insuranceModel);
183
			insurancePolicy.setPosted(true);
184
		}catch (ProfitMandiBusinessException profitMandiBusinessException) {
185
			LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
186
		}
187
		insurancePolicyRepository.persist(insurancePolicy);			
22889 amit.gupta 188
 
22893 amit.gupta 189
		PdfModel pdfModel = this.getInvoicePdfModel(insurancePolicy);
190
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
191
		PdfUtils.generateAndWrite(pdfModel, byteArrayOutputStream);
22889 amit.gupta 192
 
22893 amit.gupta 193
		Document deviceDocument = documentRepository.selectById(insuranceModel.getDeviceImageDocumentId());
194
		File deviceImg = new File(deviceDocument.getPath() + deviceDocument.getName());
195
		Document invoiceDocument = documentRepository.selectById(insuranceModel.getDeviceImageDocumentId());
196
		File deviceInvoiceImg = new File(invoiceDocument.getPath() + invoiceDocument.getName());
22889 amit.gupta 197
 
22893 amit.gupta 198
		String messageText = MessageFormat.format(
199
				"Dear {0}, Thank you for purchasing Damage Protection Plan. Your Policy number is {1}",
200
				insurancePolicy.getCustomerFirstName(), insurancePolicy.getPolicyNumber());
201
		Utils.sendSms(messageText, insurancePolicy.getCustomerMobileNumber());
202
		List<File> attachments = this.savePolicyDocs(insurancePolicy.getPolicyNumber(), byteArrayOutputStream, deviceImg, deviceInvoiceImg);
203
		messageText += "\n Please find your Invoice, and documents submitted by you.";
22913 amit.gupta 204
		String subject = "Your Gadget Cop damage Protection purchase is successful";
22893 amit.gupta 205
		this.sendMailWithAttachments(insuranceModel.getCustomerEmailId() , subject, messageText, attachments);
22913 amit.gupta 206
 
22917 amit.gupta 207
		float taxableInsuranceMargin = (insurancePolicy.getSaleAmount() - insurancePolicy.getPurchaseAmount()) / (1 + ProfitMandiConstants.INSURANCE_TAX_RATE / 100);
22913 amit.gupta 208
		walletService.addAmountToWallet(uc.getUserId(), insurancePolicy.getId(), WalletReferenceType.CASHBACK, "Cashback against insurance policy", 
209
				taxableInsuranceMargin);
22889 amit.gupta 210
		LOGGER.info("requested url : " + request.getRequestURL().toString());
211
		return responseSender.ok(true);
22866 ashik.ali 212
	}
213
 
22889 amit.gupta 214
	private void sendMailWithAttachments(String email, String subject, String body, List<File> attachments) throws Exception {
215
 
216
    	MimeMessage message = mailSender.createMimeMessage();
22910 amit.gupta 217
    	MimeMessageHelper helper = new MimeMessageHelper(message,true);
22913 amit.gupta 218
    	helper.setSubject(subject);
22889 amit.gupta 219
    	helper.setText(body);
22916 amit.gupta 220
    	String[] cc = {"backup@shop2020.in"};
22889 amit.gupta 221
    	//String[] cc = {"amit.gupta@shop2020.in"};
22916 amit.gupta 222
    	helper.setCc(cc);
22918 amit.gupta 223
    	helper.setTo(email);
22889 amit.gupta 224
    	InternetAddress senderAddress = new InternetAddress("noreply@profitmandi.com", "ProfitMandi Admin");
225
    	helper.setTo("help@profitmandi.com");
226
    	helper.setFrom(senderAddress);
227
    	for (File file : attachments) {
228
    		helper.addAttachment(file.getName(), file);
229
    	}
230
    	mailSender.send(message);
231
 
232
	}
233
 
234
	private List<File> savePolicyDocs(String policyNumber, ByteArrayOutputStream pdfInvoiceStream, File deviceImg,
235
			File deviceInvoiceImg) throws Exception {
236
		// save file to gadgetCops/policyname
237
		String policyFolderPath = gadgetCopsFilePath + File.separator + policyNumber;
238
		File destDeviceInvoiceImg = new File(policyFolderPath + File.separator + "deviceInvoice.jpg");
239
		File destDeviceImg = new File(policyFolderPath + File.separator + "device.jpg");
240
		FileUtils.copyFile(deviceImg, destDeviceImg);
241
		FileUtils.copyFile(deviceInvoiceImg, destDeviceInvoiceImg);
242
 
243
		OutputStream outStream = null;
244
		try {
245
			outStream = new FileOutputStream(policyFolderPath + File.separator + "invoice.pdf");
246
			pdfInvoiceStream.writeTo(outStream);
22911 amit.gupta 247
			pdfInvoiceStream.flush();
22889 amit.gupta 248
		} catch (IOException e) {
249
			e.printStackTrace();
250
		} finally {
251
			outStream.close();
252
			pdfInvoiceStream.close();
253
		}
254
 
255
		File pdfInvoice = new File(policyFolderPath + File.separator + "invoice.pdf");
256
		return Arrays.asList(pdfInvoice, destDeviceImg, destDeviceInvoiceImg);
257
	}
258
 
22907 amit.gupta 259
	public String getFormattedDate(LocalDateTime localDate) {
22889 amit.gupta 260
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-YYYY HH:mm");
261
		return localDate.format(formatter);
262
	}
263
 
264
	private PdfModel getInvoicePdfModel(InsurancePolicy insurancePolicy) throws ProfitMandiBusinessException {
265
 
266
		PdfModel pdfModel = new PdfModel();
267
		pdfModel.setAuther("profitmandi");
268
		pdfModel.setTitle("Retailer Invoice");
22907 amit.gupta 269
		pdfModel.setInvoiceDate(getFormattedDate(insurancePolicy.getCreateTimestamp()));
22889 amit.gupta 270
 
271
		// insurance calculation
272
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
273
		final float totalInsuranceTaxRate = 18;
274
 
275
		float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
276
		CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
277
		customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #"
278
				+ insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
279
		customInsurancePolicy.setHsnCode("998716");
280
		customInsurancePolicy.setRate(taxableInsurancePrice);
281
		customInsurancePolicy.setIgstRate(18);
282
		customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 / 100);
283
		customInsurancePolicy.setCgstRate(9);
284
		customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 / 100);
285
		customInsurancePolicy.setSgstRate(9);
286
		customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 / 100);
287
		customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
288
		customInsurancePolicies.add(customInsurancePolicy);
289
 
290
		pdfModel.setInsurancePolicies(customInsurancePolicies);
291
		CustomCustomer customCustomer = new CustomCustomer();
292
		customCustomer.setFirstName(insurancePolicy.getCustomerFirstName());
293
		customCustomer.setLastName(insurancePolicy.getCustomerLastName());
294
		customCustomer.setEmailId(insurancePolicy.getCustomerEmailId());
295
		customCustomer.setMobileNumber(insurancePolicy.getCustomerMobileNumber());
296
 
297
		CustomAddress customAddress = new CustomAddress();
298
		customAddress.setName(insurancePolicy.getCustomerFirstName() + " " + insurancePolicy.getCustomerLastName());
299
		customAddress.setLine1(insurancePolicy.getCustomerAddress1());
300
		customAddress.setLine2(insurancePolicy.getCustomerAddress2());
301
		customAddress.setLandmark("");
302
		customAddress.setCity(insurancePolicy.getCustomerCity());
303
		customAddress.setPinCode(insurancePolicy.getCustomerPinCode());
304
		customAddress.setState(insurancePolicy.getCustomerState());
305
		customAddress.setPhoneNumber(insurancePolicy.getCustomerMobileNumber());
306
		customCustomer.setAddress(customAddress);
307
		pdfModel.setCustomer(customCustomer);
308
 
309
		// TODO get invoice number for damageProtection provider
310
		pdfModel.setInvoiceNumber(thirdPartyInvoiceSequenceRepository.getNextSequence(ThirdParty.GADGET_COP));
311
		pdfModel.setTotalAmount(gadgetCopsInsuranceCalcRepository.selectByPrice(insurancePolicy.getSellingPrice()));
312
 
313
		// Here bill is generated on behalf of GadgetCop
314
		ThirdPartyInvoiceSequence damageProtectionProvider = thirdPartyInvoiceSequenceRepository
315
				.selectByThirdParty(ThirdParty.GADGET_COP);
316
		// Gadget Cop
317
		// Gadget cop mobile
318
		CustomRetailer customRetailer = new CustomRetailer();
319
		customRetailer.setBusinessName(damageProtectionProvider.getName());
320
		customRetailer.setMobileNumber(damageProtectionProvider.getMobileNumber());
321
		customRetailer.setGstNumber(damageProtectionProvider.getGstNumber());
22912 amit.gupta 322
		//customRetailer.setAddress(address);
323
 
22889 amit.gupta 324
		CustomAddress providerAddress = new CustomAddress();
325
		providerAddress.setCity(damageProtectionProvider.getCity());
326
		providerAddress.setLine1(damageProtectionProvider.getLine1());
327
		providerAddress.setLine2(damageProtectionProvider.getLine2());
328
		providerAddress.setPinCode(damageProtectionProvider.getPin());
329
		providerAddress.setPhoneNumber(damageProtectionProvider.getMobileNumber());
330
		providerAddress.setState(damageProtectionProvider.getState());
22912 amit.gupta 331
 
332
		customRetailer.setAddress(providerAddress);
22889 amit.gupta 333
		pdfModel.setRetailer(customRetailer);
334
 
335
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
336
		pdfModel.setOrderItems(customerFofoOrderItems);
337
		return pdfModel;
338
	}
22932 amit.gupta 339
 
340
	private List<GadgetCopsInsuranceCalcResponse> toCalcResponseList (List<GadgetCopsInsuranceCalc> calcList) {
341
		List<GadgetCopsInsuranceCalcResponse> calcResponseList = new ArrayList<>();
342
		for (GadgetCopsInsuranceCalc calc : calcList) {
343
			GadgetCopsInsuranceCalcResponse calcResponse = new GadgetCopsInsuranceCalcResponse();
344
			calcResponse.setDealerPrice(calc.getDealerPrice());
345
			calcResponse.setPriceRangeMax(calc.getPriceRangeMax());
346
			calcResponse.setPriceRangeMin(calc.getPriceRangeMin());
347
			float taxableInsuranceMargin = (calc.getSellingPrice() - calc.getDealerPrice()) / (1 + ProfitMandiConstants.INSURANCE_TAX_RATE / 100);
348
			calcResponse.setCashBack(taxableInsuranceMargin);
349
			calcResponseList.add(calcResponse);
350
		}
351
		return calcResponseList;
352
	}
22889 amit.gupta 353
 
22866 ashik.ali 354
}