Subversion Repositories SmartDukaan

Rev

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