Subversion Repositories SmartDukaan

Rev

Rev 29597 | Rev 33314 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 29597 Rev 30330
Line 7... Line 7...
7
import java.io.OutputStream;
7
import java.io.OutputStream;
8
import java.text.MessageFormat;
8
import java.text.MessageFormat;
9
import java.time.LocalDate;
9
import java.time.LocalDate;
10
import java.time.LocalDateTime;
10
import java.time.LocalDateTime;
11
import java.time.format.DateTimeFormatter;
11
import java.time.format.DateTimeFormatter;
12
import java.util.ArrayList;
-
 
13
import java.util.Arrays;
12
import java.util.Arrays;
14
import java.util.HashSet;
13
import java.util.HashSet;
15
import java.util.List;
14
import java.util.List;
16
import java.util.Map;
15
import java.util.Map;
17
import java.util.Set;
16
import java.util.Set;
Line 41... Line 40...
41
import com.spice.profitmandi.common.model.CustomCustomer;
40
import com.spice.profitmandi.common.model.CustomCustomer;
42
import com.spice.profitmandi.common.model.CustomInsurancePolicy;
41
import com.spice.profitmandi.common.model.CustomInsurancePolicy;
43
import com.spice.profitmandi.common.model.CustomOrderItem;
42
import com.spice.profitmandi.common.model.CustomOrderItem;
44
import com.spice.profitmandi.common.model.CustomRetailer;
43
import com.spice.profitmandi.common.model.CustomRetailer;
45
import com.spice.profitmandi.common.model.GadgetCopsDocumentInsuranceModel;
44
import com.spice.profitmandi.common.model.GadgetCopsDocumentInsuranceModel;
46
import com.spice.profitmandi.common.model.GadgetCopsInsuranceCalcResponse;
-
 
47
import com.spice.profitmandi.common.model.PdfModel;
45
import com.spice.profitmandi.common.model.InvoicePdfModel;
-
 
46
 
48
import com.spice.profitmandi.common.model.ProfitMandiConstants;
47
import com.spice.profitmandi.common.model.ProfitMandiConstants;
49
import com.spice.profitmandi.common.util.InsuranceUtils;
48
import com.spice.profitmandi.common.util.InsuranceUtils;
50
import com.spice.profitmandi.common.util.PdfUtils;
49
import com.spice.profitmandi.common.util.PdfUtils;
51
import com.spice.profitmandi.common.util.StringUtils;
50
import com.spice.profitmandi.common.util.StringUtils;
52
import com.spice.profitmandi.common.web.util.ResponseSender;
51
import com.spice.profitmandi.common.web.util.ResponseSender;
Line 83... Line 82...
83
	private static final Logger LOGGER = LogManager.getLogger(InsuranceController.class);
82
	private static final Logger LOGGER = LogManager.getLogger(InsuranceController.class);
84
	private static final String gadgetCopsFilePath = "/GadgetCops";
83
	private static final String gadgetCopsFilePath = "/GadgetCops";
85
 
84
 
86
	@Autowired
85
	@Autowired
87
	private RangeItemPriceRepository rangeItemPriceRepository;
86
	private RangeItemPriceRepository rangeItemPriceRepository;
88
	
87
 
89
	@Autowired
88
	@Autowired
90
	private RangeItemRepository rangeItemRepository;
89
	private RangeItemRepository rangeItemRepository;
91
	
90
 
92
	//This is now unused as we are not supporting multiple companies.
91
	// This is now unused as we are not supporting multiple companies.
93
	@Value("${fofo.warehouseIds}")
92
	@Value("${fofo.warehouseIds}")
94
	private int[] warehouseIds; 
93
	private int[] warehouseIds;
95
	
94
 
-
 
95
	@Autowired
96
	@Autowired OtpProcessor otpProcessor;
96
	OtpProcessor otpProcessor;
97
	
-
 
98
 
97
 
99
	@RequestMapping(value = ProfitMandiConstants.URL_INSURANCE_GADGET_COPS_MAPPING, method = RequestMethod.GET)
98
	@RequestMapping(value = ProfitMandiConstants.URL_INSURANCE_GADGET_COPS_MAPPING, method = RequestMethod.GET)
100
	public ResponseEntity<?> getById(HttpServletRequest request) {
99
	public ResponseEntity<?> getById(HttpServletRequest request) {
101
		LOGGER.info("requested url : " + request.getRequestURL().toString());
100
		LOGGER.info("requested url : " + request.getRequestURL().toString());
102
		Map<Integer, List<RangeItemPrice>> rangeItemPrices = rangeItemPriceRepository.selectAll().stream().collect(Collectors.groupingBy(RangeItemPrice::getRangeItemId, Collectors.toList()));
101
		Map<Integer, List<RangeItemPrice>> rangeItemPrices = rangeItemPriceRepository.selectAll().stream()
-
 
102
				.collect(Collectors.groupingBy(RangeItemPrice::getRangeItemId, Collectors.toList()));
103
		List<RangeItem> rangeItems = rangeItemRepository.selectAll();
103
		List<RangeItem> rangeItems = rangeItemRepository.selectAll();
104
		rangeItems.stream().forEach(x-> x.setRangeItemPrices(rangeItemPrices.get(x.getId())));
104
		rangeItems.stream().forEach(x -> x.setRangeItemPrices(rangeItemPrices.get(x.getId())));
105
		return responseSender.ok(rangeItems);
105
		return responseSender.ok(rangeItems);
106
	}
106
	}
107
 
107
 
108
	@Autowired
108
	@Autowired
109
	ResponseSender<?> responseSender;
109
	ResponseSender<?> responseSender;
110
	
110
 
111
	@Autowired
111
	@Autowired
112
	GadgetCopsInsuranceCalcRepository gadgetCopsInsuranceCalcRepository;
112
	GadgetCopsInsuranceCalcRepository gadgetCopsInsuranceCalcRepository;
113
 
113
 
114
	@Autowired
114
	@Autowired
115
	ThirdPartyInvoiceSequenceRepository thirdPartyInvoiceSequenceRepository;
115
	ThirdPartyInvoiceSequenceRepository thirdPartyInvoiceSequenceRepository;
Line 117... Line 117...
117
	@Autowired
117
	@Autowired
118
	DocumentRepository documentRepository;
118
	DocumentRepository documentRepository;
119
 
119
 
120
	@Autowired
120
	@Autowired
121
	InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
121
	InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
122
	
122
 
123
	@Autowired
123
	@Autowired
124
	InsurancePolicyRepository insurancePolicyRepository;
124
	InsurancePolicyRepository insurancePolicyRepository;
125
 
125
 
126
	@Autowired
126
	@Autowired
127
	PricingService pricingService;
127
	PricingService pricingService;
128
	
128
 
129
	@Autowired
129
	@Autowired
130
	JavaMailSender mailSender;
130
	JavaMailSender mailSender;
131
 
131
 
132
	@Autowired
132
	@Autowired
133
	InsuranceProviderRepository insuranceProviderRepository;
133
	InsuranceProviderRepository insuranceProviderRepository;
134
 
134
 
135
	@Autowired
135
	@Autowired
136
	UserAccountRepository userAccountRepository;
136
	UserAccountRepository userAccountRepository;
137
	
137
 
138
	@Autowired
138
	@Autowired
139
	WalletService walletService;
139
	WalletService walletService;
140
 
140
 
141
	@Autowired
141
	@Autowired
142
	UserWalletRepository userWalletRepositoy;
142
	UserWalletRepository userWalletRepositoy;
Line 145... Line 145...
145
	PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
145
	PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
146
 
146
 
147
	@RequestMapping(value = ProfitMandiConstants.URL_DAMAGE_INSURANCE, method = RequestMethod.POST)
147
	@RequestMapping(value = ProfitMandiConstants.URL_DAMAGE_INSURANCE, method = RequestMethod.POST)
148
	public ResponseEntity<?> createDamageProtection(HttpServletRequest request,
148
	public ResponseEntity<?> createDamageProtection(HttpServletRequest request,
149
			@RequestBody GadgetCopsDocumentInsuranceModel insuranceModel) throws Throwable {
149
			@RequestBody GadgetCopsDocumentInsuranceModel insuranceModel) throws Throwable {
-
 
150
		insuranceModel
150
		insuranceModel.setCustomerDateOfBirth(StringUtils.fromHypendatedDate(insuranceModel.getCustomerDateOfBirthString()));
151
				.setCustomerDateOfBirth(StringUtils.fromHypendatedDate(insuranceModel.getCustomerDateOfBirthString()));
151
		insuranceModel.setInvoiceCreationDate(LocalDate.now());
152
		insuranceModel.setInvoiceCreationDate(LocalDate.now());
152
		insuranceModel.validate();
153
		insuranceModel.validate();
153
		int userId = (int) request.getAttribute("userId");
154
		int userId = (int) request.getAttribute("userId");
154
		UserCart uc = userAccountRepository.getUserCart(userId);
155
		UserCart uc = userAccountRepository.getUserCart(userId);
155
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
156
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
Line 192... Line 193...
192
		insurancePolicy.setCustomerCity(insuranceModel.getCustomerCity());
193
		insurancePolicy.setCustomerCity(insuranceModel.getCustomerCity());
193
		insurancePolicy.setCustomerPinCode(insuranceModel.getCustomerPinCode());
194
		insurancePolicy.setCustomerPinCode(insuranceModel.getCustomerPinCode());
194
		insurancePolicy.setCustomerState(insuranceModel.getCustomerState());
195
		insurancePolicy.setCustomerState(insuranceModel.getCustomerState());
195
		insurancePolicyRepository.persist(insurancePolicy);
196
		insurancePolicyRepository.persist(insurancePolicy);
196
		insuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
197
		insuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
197
		String walletDescription = "Purchased Damage Protection policy " + insurancePolicy.getPolicyNumber() 
198
		String walletDescription = "Purchased Damage Protection policy " + insurancePolicy.getPolicyNumber() + " for "
198
			+ " for " + insurancePolicy.getCustomerFirstName();
199
				+ insurancePolicy.getCustomerFirstName();
199
		
200
 
200
		walletService.consumeAmountFromWallet(uc.getUserId(), insurancePolicy.getId(), 
201
		walletService.consumeAmountFromWallet(uc.getUserId(), insurancePolicy.getId(),
201
				WalletReferenceType.DAMAGE_PROTECTION, walletDescription, insurancePolicy.getSaleAmount(), LocalDateTime.now());
202
				WalletReferenceType.DAMAGE_PROTECTION, walletDescription, insurancePolicy.getSaleAmount(),
-
 
203
				LocalDateTime.now());
202
		
204
 
203
		try{
205
		try {
204
			InsuranceUtils.submitToGadgetCops(insuranceModel);
206
			InsuranceUtils.submitToGadgetCops(insuranceModel);
205
			insurancePolicy.setPosted(true);
207
			insurancePolicy.setPosted(true);
206
		}catch (ProfitMandiBusinessException profitMandiBusinessException) {
208
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
207
			LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
209
			LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(),
-
 
210
					profitMandiBusinessException);
208
			throw new ProfitMandiBusinessException("", "", "GDTCPSServerDown_1000");
211
			throw new ProfitMandiBusinessException("", "", "GDTCPSServerDown_1000");
209
		}
212
		}
210
		insurancePolicyRepository.persist(insurancePolicy);			
213
		insurancePolicyRepository.persist(insurancePolicy);
211
 
214
 
212
		PdfModel pdfModel = this.getInvoicePdfModel(insurancePolicy);
215
		InvoicePdfModel pdfModel = this.getInvoicePdfModel(insurancePolicy);
213
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
216
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
214
		PdfUtils.generateAndWrite(Arrays.asList(pdfModel), byteArrayOutputStream);
217
		PdfUtils.generateAndWrite(Arrays.asList(pdfModel), byteArrayOutputStream);
215
 
218
 
216
		Document deviceDocument = documentRepository.selectById(insuranceModel.getDeviceImageDocumentId());
219
		Document deviceDocument = documentRepository.selectById(insuranceModel.getDeviceImageDocumentId());
217
		File deviceImg = new File(deviceDocument.getPath() + deviceDocument.getName());
220
		File deviceImg = new File(deviceDocument.getPath() + deviceDocument.getName());
218
		Document invoiceDocument = documentRepository.selectById(insuranceModel.getDeviceImageDocumentId());
221
		Document invoiceDocument = documentRepository.selectById(insuranceModel.getDeviceImageDocumentId());
219
		File deviceInvoiceImg = new File(invoiceDocument.getPath() + invoiceDocument.getName());
222
		File deviceInvoiceImg = new File(invoiceDocument.getPath() + invoiceDocument.getName());
220
 
223
 
221
		List<File> attachments = this.savePolicyDocs(insurancePolicy.getPolicyNumber(), byteArrayOutputStream, deviceImg, deviceInvoiceImg);
224
		List<File> attachments = this.savePolicyDocs(insurancePolicy.getPolicyNumber(), byteArrayOutputStream,
-
 
225
				deviceImg, deviceInvoiceImg);
222
		String messageText = MessageFormat.format(
226
		String messageText = MessageFormat.format(
223
				"Dear {0}, Thank you for purchasing Damage Protection Plan. Your Policy number is {1}",
227
				"Dear {0}, Thank you for purchasing Damage Protection Plan. Your Policy number is {1}",
224
				insurancePolicy.getCustomerFirstName(), insurancePolicy.getPolicyNumber());
228
				insurancePolicy.getCustomerFirstName(), insurancePolicy.getPolicyNumber());
225
		//TODO: add template if needed
229
		// TODO: add template if needed
226
		otpProcessor.sendSms("", messageText, insurancePolicy.getCustomerMobileNumber());
230
		otpProcessor.sendSms("", messageText, insurancePolicy.getCustomerMobileNumber());
227
		messageText += "\n Please find your Invoice and Documents submitted by you.";
231
		messageText += "\n Please find your Invoice and Documents submitted by you.";
228
		String subject = "Your Gadget Cop damage Protection purchase is successful";
232
		String subject = "Your Gadget Cop damage Protection purchase is successful";
229
		this.sendMailWithAttachments(insuranceModel.getCustomerEmailId() , subject, messageText, attachments);
233
		this.sendMailWithAttachments(insuranceModel.getCustomerEmailId(), subject, messageText, attachments);
230
 
234
 
231
		float taxableInsuranceMargin = (insurancePolicy.getSaleAmount() - insurancePolicy.getPurchaseAmount()) / (1 + ProfitMandiConstants.INSURANCE_TAX_RATE / 100);
235
		float taxableInsuranceMargin = (insurancePolicy.getSaleAmount() - insurancePolicy.getPurchaseAmount())
-
 
236
				/ (1 + ProfitMandiConstants.INSURANCE_TAX_RATE / 100);
232
		walletService.addAmountToWallet(uc.getUserId(), insurancePolicy.getId(), WalletReferenceType.CASHBACK, "Cashback against insurance policy", 
237
		walletService.addAmountToWallet(uc.getUserId(), insurancePolicy.getId(), WalletReferenceType.CASHBACK,
233
				taxableInsuranceMargin, LocalDateTime.now());
238
				"Cashback against insurance policy", taxableInsuranceMargin, LocalDateTime.now());
234
		LOGGER.info("requested url : " + request.getRequestURL().toString());
239
		LOGGER.info("requested url : " + request.getRequestURL().toString());
235
		JSONObject jsonObject = new JSONObject();
240
		JSONObject jsonObject = new JSONObject();
236
		jsonObject.put("policyNumber", insurancePolicy.getPolicyNumber());
241
		jsonObject.put("policyNumber", insurancePolicy.getPolicyNumber());
237
		jsonObject.put("premiumCharged", insurancePolicy.getSaleAmount());
242
		jsonObject.put("premiumCharged", insurancePolicy.getSaleAmount());
238
		return responseSender.ok(jsonObject.toString());
243
		return responseSender.ok(jsonObject.toString());
239
	}
244
	}
240
	
-
 
241
	private void sendMailWithAttachments(String email, String subject, String body, List<File> attachments) throws Exception {
-
 
242
 
245
 
-
 
246
	private void sendMailWithAttachments(String email, String subject, String body, List<File> attachments)
-
 
247
			throws Exception {
-
 
248
 
243
    	MimeMessage message = mailSender.createMimeMessage();
249
		MimeMessage message = mailSender.createMimeMessage();
244
    	MimeMessageHelper helper = new MimeMessageHelper(message,true);
250
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
245
    	helper.setSubject(subject);
251
		helper.setSubject(subject);
246
    	helper.setText(body);
252
		helper.setText(body);
247
    	String[] cc = {"backup@shop2020.in", "gadgetcops.01@gmail.com"};
253
		String[] cc = { "backup@shop2020.in", "gadgetcops.01@gmail.com" };
248
    	//String[] cc = {"amit.gupta@shop2020.in"};
254
		// String[] cc = {"amit.gupta@shop2020.in"};
249
    	helper.setCc(cc);
255
		helper.setCc(cc);
250
    	helper.setTo(email);
256
		helper.setTo(email);
251
    	InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "ProfitMandi Admin");
257
		InternetAddress senderAddress = new InternetAddress("noreply@smartdukaan.com", "ProfitMandi Admin");
252
    	helper.setTo("help@smartdukaan.com");
258
		helper.setTo("help@smartdukaan.com");
253
    	helper.setFrom(senderAddress);
259
		helper.setFrom(senderAddress);
254
    	for (File file : attachments) {
260
		for (File file : attachments) {
255
    		helper.addAttachment(file.getName(), file);
261
			helper.addAttachment(file.getName(), file);
256
    	}
262
		}
257
    	mailSender.send(message);
263
		mailSender.send(message);
258
		
264
 
259
	}
265
	}
260
 
266
 
261
	private List<File> savePolicyDocs(String policyNumber, ByteArrayOutputStream pdfInvoiceStream, File deviceImg,
267
	private List<File> savePolicyDocs(String policyNumber, ByteArrayOutputStream pdfInvoiceStream, File deviceImg,
262
			File deviceInvoiceImg) throws Exception {
268
			File deviceInvoiceImg) throws Exception {
263
		// save file to gadgetCops/policyname
269
		// save file to gadgetCops/policyname
Line 276... Line 282...
276
			e.printStackTrace();
282
			e.printStackTrace();
277
		} finally {
283
		} finally {
278
			outStream.close();
284
			outStream.close();
279
			pdfInvoiceStream.close();
285
			pdfInvoiceStream.close();
280
		}
286
		}
281
		
287
 
282
		File pdfInvoice = new File(policyFolderPath + File.separator + "invoice.pdf");
288
		File pdfInvoice = new File(policyFolderPath + File.separator + "invoice.pdf");
283
		return Arrays.asList(pdfInvoice, destDeviceImg, destDeviceInvoiceImg);
289
		return Arrays.asList(pdfInvoice, destDeviceImg, destDeviceInvoiceImg);
284
	}
290
	}
285
 
291
 
286
	public String getFormattedDate(LocalDateTime localDate) {
292
	public String getFormattedDate(LocalDateTime localDate) {
287
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-YYYY HH:mm");
293
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-YYYY HH:mm");
288
		return localDate.format(formatter);
294
		return localDate.format(formatter);
289
	}
295
	}
290
 
296
 
291
	private PdfModel getInvoicePdfModel(InsurancePolicy insurancePolicy) throws ProfitMandiBusinessException {
297
	private InvoicePdfModel getInvoicePdfModel(InsurancePolicy insurancePolicy) throws ProfitMandiBusinessException {
292
 
298
 
293
		PdfModel pdfModel = new PdfModel();
299
		InvoicePdfModel pdfModel = new InvoicePdfModel();
294
		pdfModel.setAuther("profitmandi");
300
		pdfModel.setAuther("profitmandi");
295
		pdfModel.setTitle("Retailer Invoice");
301
		pdfModel.setTitle("Retailer Invoice");
296
		pdfModel.setInvoiceDate(getFormattedDate(insurancePolicy.getCreateTimestamp()));
302
		pdfModel.setInvoiceDate(getFormattedDate(insurancePolicy.getCreateTimestamp()));
297
 
303
 
298
		// insurance calculation
304
		// insurance calculation
Line 344... Line 350...
344
		// Gadget cop mobile
350
		// Gadget cop mobile
345
		CustomRetailer customRetailer = new CustomRetailer();
351
		CustomRetailer customRetailer = new CustomRetailer();
346
		customRetailer.setBusinessName(damageProtectionProvider.getName());
352
		customRetailer.setBusinessName(damageProtectionProvider.getName());
347
		customRetailer.setMobileNumber(damageProtectionProvider.getMobileNumber());
353
		customRetailer.setMobileNumber(damageProtectionProvider.getMobileNumber());
348
		customRetailer.setGstNumber(damageProtectionProvider.getGstNumber());
354
		customRetailer.setGstNumber(damageProtectionProvider.getGstNumber());
349
		//customRetailer.setAddress(address);
355
		// customRetailer.setAddress(address);
350
		
356
 
351
		CustomAddress providerAddress = new CustomAddress();
357
		CustomAddress providerAddress = new CustomAddress();
352
		providerAddress.setCity(damageProtectionProvider.getCity());
358
		providerAddress.setCity(damageProtectionProvider.getCity());
353
		providerAddress.setLine1(damageProtectionProvider.getLine1());
359
		providerAddress.setLine1(damageProtectionProvider.getLine1());
354
		providerAddress.setLine2(damageProtectionProvider.getLine2());
360
		providerAddress.setLine2(damageProtectionProvider.getLine2());
355
		providerAddress.setPinCode(damageProtectionProvider.getPin());
361
		providerAddress.setPinCode(damageProtectionProvider.getPin());
356
		providerAddress.setPhoneNumber(damageProtectionProvider.getMobileNumber());
362
		providerAddress.setPhoneNumber(damageProtectionProvider.getMobileNumber());
357
		providerAddress.setState(damageProtectionProvider.getState());
363
		providerAddress.setState(damageProtectionProvider.getState());
358
		
364
 
359
		customRetailer.setAddress(providerAddress);
365
		customRetailer.setAddress(providerAddress);
360
		pdfModel.setRetailer(customRetailer);
366
		pdfModel.setRetailer(customRetailer);
361
 
367
 
362
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
368
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
363
		pdfModel.setOrderItems(customerFofoOrderItems);
369
		pdfModel.setOrderItems(customerFofoOrderItems);