Subversion Repositories SmartDukaan

Rev

Rev 22994 | Rev 22999 | 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
 
22913 amit.gupta 180
		walletService.consumeAmountFromWallet(uc.getUserId(), insurancePolicy.getId(), WalletReferenceType.DAMAGE_PROTECTION, walletDescription, insurancePolicy.getSaleAmount());
22898 amit.gupta 181
 
22893 amit.gupta 182
		try{
183
			InsuranceUtils.submitToGadgetCops(insuranceModel);
184
			insurancePolicy.setPosted(true);
185
		}catch (ProfitMandiBusinessException profitMandiBusinessException) {
186
			LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
22994 amit.gupta 187
			throw new ProfitMandiBusinessException("", "", "GDTCPSServerDown_1000");
22893 amit.gupta 188
		}
189
		insurancePolicyRepository.persist(insurancePolicy);			
22889 amit.gupta 190
 
22893 amit.gupta 191
		PdfModel pdfModel = this.getInvoicePdfModel(insurancePolicy);
192
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
193
		PdfUtils.generateAndWrite(pdfModel, byteArrayOutputStream);
22889 amit.gupta 194
 
22893 amit.gupta 195
		Document deviceDocument = documentRepository.selectById(insuranceModel.getDeviceImageDocumentId());
196
		File deviceImg = new File(deviceDocument.getPath() + deviceDocument.getName());
197
		Document invoiceDocument = documentRepository.selectById(insuranceModel.getDeviceImageDocumentId());
198
		File deviceInvoiceImg = new File(invoiceDocument.getPath() + invoiceDocument.getName());
22889 amit.gupta 199
 
22893 amit.gupta 200
		String messageText = MessageFormat.format(
201
				"Dear {0}, Thank you for purchasing Damage Protection Plan. Your Policy number is {1}",
202
				insurancePolicy.getCustomerFirstName(), insurancePolicy.getPolicyNumber());
203
		Utils.sendSms(messageText, insurancePolicy.getCustomerMobileNumber());
204
		List<File> attachments = this.savePolicyDocs(insurancePolicy.getPolicyNumber(), byteArrayOutputStream, deviceImg, deviceInvoiceImg);
205
		messageText += "\n Please find your Invoice, and documents submitted by you.";
22913 amit.gupta 206
		String subject = "Your Gadget Cop damage Protection purchase is successful";
22893 amit.gupta 207
		this.sendMailWithAttachments(insuranceModel.getCustomerEmailId() , subject, messageText, attachments);
22913 amit.gupta 208
 
22917 amit.gupta 209
		float taxableInsuranceMargin = (insurancePolicy.getSaleAmount() - insurancePolicy.getPurchaseAmount()) / (1 + ProfitMandiConstants.INSURANCE_TAX_RATE / 100);
22913 amit.gupta 210
		walletService.addAmountToWallet(uc.getUserId(), insurancePolicy.getId(), WalletReferenceType.CASHBACK, "Cashback against insurance policy", 
211
				taxableInsuranceMargin);
22889 amit.gupta 212
		LOGGER.info("requested url : " + request.getRequestURL().toString());
22993 amit.gupta 213
		JSONObject jsonObject = new JSONObject();
214
		jsonObject.append("policyNumber", insurancePolicy.getPolicyNumber());
22997 amit.gupta 215
		return responseSender.ok(jsonObject.toString());
22866 ashik.ali 216
	}
217
 
22889 amit.gupta 218
	private void sendMailWithAttachments(String email, String subject, String body, List<File> attachments) throws Exception {
219
 
220
    	MimeMessage message = mailSender.createMimeMessage();
22910 amit.gupta 221
    	MimeMessageHelper helper = new MimeMessageHelper(message,true);
22913 amit.gupta 222
    	helper.setSubject(subject);
22889 amit.gupta 223
    	helper.setText(body);
22916 amit.gupta 224
    	String[] cc = {"backup@shop2020.in"};
22889 amit.gupta 225
    	//String[] cc = {"amit.gupta@shop2020.in"};
22916 amit.gupta 226
    	helper.setCc(cc);
22918 amit.gupta 227
    	helper.setTo(email);
22889 amit.gupta 228
    	InternetAddress senderAddress = new InternetAddress("noreply@profitmandi.com", "ProfitMandi Admin");
229
    	helper.setTo("help@profitmandi.com");
230
    	helper.setFrom(senderAddress);
231
    	for (File file : attachments) {
232
    		helper.addAttachment(file.getName(), file);
233
    	}
234
    	mailSender.send(message);
235
 
236
	}
237
 
238
	private List<File> savePolicyDocs(String policyNumber, ByteArrayOutputStream pdfInvoiceStream, File deviceImg,
239
			File deviceInvoiceImg) throws Exception {
240
		// save file to gadgetCops/policyname
241
		String policyFolderPath = gadgetCopsFilePath + File.separator + policyNumber;
242
		File destDeviceInvoiceImg = new File(policyFolderPath + File.separator + "deviceInvoice.jpg");
243
		File destDeviceImg = new File(policyFolderPath + File.separator + "device.jpg");
244
		FileUtils.copyFile(deviceImg, destDeviceImg);
245
		FileUtils.copyFile(deviceInvoiceImg, destDeviceInvoiceImg);
246
 
247
		OutputStream outStream = null;
248
		try {
249
			outStream = new FileOutputStream(policyFolderPath + File.separator + "invoice.pdf");
250
			pdfInvoiceStream.writeTo(outStream);
22911 amit.gupta 251
			pdfInvoiceStream.flush();
22889 amit.gupta 252
		} catch (IOException e) {
253
			e.printStackTrace();
254
		} finally {
255
			outStream.close();
256
			pdfInvoiceStream.close();
257
		}
258
 
259
		File pdfInvoice = new File(policyFolderPath + File.separator + "invoice.pdf");
260
		return Arrays.asList(pdfInvoice, destDeviceImg, destDeviceInvoiceImg);
261
	}
262
 
22907 amit.gupta 263
	public String getFormattedDate(LocalDateTime localDate) {
22889 amit.gupta 264
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-YYYY HH:mm");
265
		return localDate.format(formatter);
266
	}
267
 
268
	private PdfModel getInvoicePdfModel(InsurancePolicy insurancePolicy) throws ProfitMandiBusinessException {
269
 
270
		PdfModel pdfModel = new PdfModel();
271
		pdfModel.setAuther("profitmandi");
272
		pdfModel.setTitle("Retailer Invoice");
22907 amit.gupta 273
		pdfModel.setInvoiceDate(getFormattedDate(insurancePolicy.getCreateTimestamp()));
22889 amit.gupta 274
 
275
		// insurance calculation
276
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
277
		final float totalInsuranceTaxRate = 18;
278
 
279
		float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
280
		CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
281
		customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #"
282
				+ insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
283
		customInsurancePolicy.setHsnCode("998716");
284
		customInsurancePolicy.setRate(taxableInsurancePrice);
285
		customInsurancePolicy.setIgstRate(18);
286
		customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 / 100);
287
		customInsurancePolicy.setCgstRate(9);
288
		customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 / 100);
289
		customInsurancePolicy.setSgstRate(9);
290
		customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 / 100);
291
		customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
292
		customInsurancePolicies.add(customInsurancePolicy);
293
 
294
		pdfModel.setInsurancePolicies(customInsurancePolicies);
295
		CustomCustomer customCustomer = new CustomCustomer();
296
		customCustomer.setFirstName(insurancePolicy.getCustomerFirstName());
297
		customCustomer.setLastName(insurancePolicy.getCustomerLastName());
298
		customCustomer.setEmailId(insurancePolicy.getCustomerEmailId());
299
		customCustomer.setMobileNumber(insurancePolicy.getCustomerMobileNumber());
300
 
301
		CustomAddress customAddress = new CustomAddress();
302
		customAddress.setName(insurancePolicy.getCustomerFirstName() + " " + insurancePolicy.getCustomerLastName());
303
		customAddress.setLine1(insurancePolicy.getCustomerAddress1());
304
		customAddress.setLine2(insurancePolicy.getCustomerAddress2());
305
		customAddress.setLandmark("");
306
		customAddress.setCity(insurancePolicy.getCustomerCity());
307
		customAddress.setPinCode(insurancePolicy.getCustomerPinCode());
308
		customAddress.setState(insurancePolicy.getCustomerState());
309
		customAddress.setPhoneNumber(insurancePolicy.getCustomerMobileNumber());
310
		customCustomer.setAddress(customAddress);
311
		pdfModel.setCustomer(customCustomer);
312
 
313
		// TODO get invoice number for damageProtection provider
314
		pdfModel.setInvoiceNumber(thirdPartyInvoiceSequenceRepository.getNextSequence(ThirdParty.GADGET_COP));
315
		pdfModel.setTotalAmount(gadgetCopsInsuranceCalcRepository.selectByPrice(insurancePolicy.getSellingPrice()));
316
 
317
		// Here bill is generated on behalf of GadgetCop
318
		ThirdPartyInvoiceSequence damageProtectionProvider = thirdPartyInvoiceSequenceRepository
319
				.selectByThirdParty(ThirdParty.GADGET_COP);
320
		// Gadget Cop
321
		// Gadget cop mobile
322
		CustomRetailer customRetailer = new CustomRetailer();
323
		customRetailer.setBusinessName(damageProtectionProvider.getName());
324
		customRetailer.setMobileNumber(damageProtectionProvider.getMobileNumber());
325
		customRetailer.setGstNumber(damageProtectionProvider.getGstNumber());
22912 amit.gupta 326
		//customRetailer.setAddress(address);
327
 
22889 amit.gupta 328
		CustomAddress providerAddress = new CustomAddress();
329
		providerAddress.setCity(damageProtectionProvider.getCity());
330
		providerAddress.setLine1(damageProtectionProvider.getLine1());
331
		providerAddress.setLine2(damageProtectionProvider.getLine2());
332
		providerAddress.setPinCode(damageProtectionProvider.getPin());
333
		providerAddress.setPhoneNumber(damageProtectionProvider.getMobileNumber());
334
		providerAddress.setState(damageProtectionProvider.getState());
22912 amit.gupta 335
 
336
		customRetailer.setAddress(providerAddress);
22889 amit.gupta 337
		pdfModel.setRetailer(customRetailer);
338
 
339
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
340
		pdfModel.setOrderItems(customerFofoOrderItems);
341
		return pdfModel;
342
	}
22932 amit.gupta 343
 
344
	private List<GadgetCopsInsuranceCalcResponse> toCalcResponseList (List<GadgetCopsInsuranceCalc> calcList) {
345
		List<GadgetCopsInsuranceCalcResponse> calcResponseList = new ArrayList<>();
346
		for (GadgetCopsInsuranceCalc calc : calcList) {
347
			GadgetCopsInsuranceCalcResponse calcResponse = new GadgetCopsInsuranceCalcResponse();
348
			calcResponse.setDealerPrice(calc.getDealerPrice());
349
			calcResponse.setPriceRangeMax(calc.getPriceRangeMax());
350
			calcResponse.setPriceRangeMin(calc.getPriceRangeMin());
351
			float taxableInsuranceMargin = (calc.getSellingPrice() - calc.getDealerPrice()) / (1 + ProfitMandiConstants.INSURANCE_TAX_RATE / 100);
22937 amit.gupta 352
			calcResponse.setCashBack((int)taxableInsuranceMargin);
22932 amit.gupta 353
			calcResponseList.add(calcResponse);
354
		}
355
		return calcResponseList;
356
	}
22889 amit.gupta 357
 
22866 ashik.ali 358
}