Subversion Repositories SmartDukaan

Rev

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