Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
32916 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
35624 ranu 3
import com.fasterxml.jackson.databind.ObjectMapper;
33715 ranu 4
import com.razorpay.Utils;
33672 ranu 5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
33581 ranu 6
import com.spice.profitmandi.common.web.util.ResponseSender;
33715 ranu 7
import com.spice.profitmandi.dao.entity.fofo.Customer;
8
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
33672 ranu 9
import com.spice.profitmandi.dao.entity.fofo.UpsellRazorpayPaymentStatus;
33595 ranu 10
import com.spice.profitmandi.dao.repository.cs.AgentRecordingRepository;
33715 ranu 11
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
12
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
33672 ranu 13
import com.spice.profitmandi.dao.repository.fofo.UpsellRazorpayPaymentStatusRepository;
34481 ranu 14
import com.spice.profitmandi.service.integrations.kommuno.RecordingService;
32929 amit.gupta 15
import com.spice.profitmandi.service.integrations.smartping.SmartPingService;
16
import com.spice.profitmandi.service.integrations.smartping.model.CallDetailModel;
34481 ranu 17
import com.spice.profitmandi.service.integrations.smartping.model.PushCallLogModel;
32916 amit.gupta 18
import com.spice.profitmandi.web.util.MVCResponseSender;
19
import org.apache.logging.log4j.LogManager;
20
import org.apache.logging.log4j.Logger;
33715 ranu 21
import org.json.JSONObject;
32916 amit.gupta 22
import org.springframework.beans.factory.annotation.Autowired;
33672 ranu 23
import org.springframework.beans.factory.annotation.Value;
24
import org.springframework.http.HttpStatus;
33581 ranu 25
import org.springframework.http.MediaType;
26
import org.springframework.http.ResponseEntity;
32916 amit.gupta 27
import org.springframework.stereotype.Controller;
35624 ranu 28
import org.springframework.transaction.annotation.Transactional;
32916 amit.gupta 29
import org.springframework.ui.Model;
35660 ranu 30
import org.springframework.web.bind.annotation.ModelAttribute;
31
import org.springframework.web.bind.annotation.RequestBody;
32
import org.springframework.web.bind.annotation.RequestMapping;
33
import org.springframework.web.bind.annotation.RequestMethod;
32916 amit.gupta 34
 
35
import javax.servlet.http.HttpServletRequest;
36
 
37
@Controller
35458 amit 38
@Transactional(rollbackFor = Throwable.class)
32916 amit.gupta 39
public class WebHookController {
40
 
41
    @Autowired
42
    MVCResponseSender mvcResponseSender;
43
 
33581 ranu 44
    @Autowired
45
    private ResponseSender<?> responseSender;
46
 
33715 ranu 47
    @Autowired
48
    private FofoOrderRepository fofoOrderRepository;
49
 
50
    @Autowired
51
    private CustomerRepository customerRepository;
52
 
32916 amit.gupta 53
    private static final Logger LOGGER = LogManager.getLogger(WebHookController.class);
54
 
32919 amit.gupta 55
    @Autowired
32929 amit.gupta 56
    SmartPingService smartPingService;
32916 amit.gupta 57
 
33595 ranu 58
    @Autowired
34481 ranu 59
    RecordingService recordingService;
33602 ranu 60
 
61
    @Autowired
33595 ranu 62
    AgentRecordingRepository agentRecordingRepository;
63
 
33581 ranu 64
 
35654 ranu 65
    /*
35624 ranu 66
     * URL: POST /click2call/report-handler/recording-url
67
     * Content-Type: application/x-www-form-urlencoded
68
     * Third-party: Knowlarity
69
     */
33590 ranu 70
    @RequestMapping(value = "/click2call/report-handler/recording-url", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
33591 ranu 71
    public ResponseEntity<?> click2callReportHandlerUpdateRecordingUrlPost(HttpServletRequest request, Model model, @ModelAttribute CallDetailModel callDetail) throws Exception {
35624 ranu 72
        // Log raw parameters from Knowlarity before processing, so we can see exactly what they sent
73
        LOGGER.info("recording-url raw params from Knowlarity: {}", request.getParameterMap());
74
        try {
75
            LOGGER.info("update call detail (mapped): {}", callDetail);
76
            recordingService.updateAgentRecordingUrl(callDetail);
77
        } catch (Exception e) {
78
            LOGGER.error("Error processing recording-url webhook. Raw params: {}", request.getParameterMap(), e);
79
        }
33581 ranu 80
        return responseSender.ok(true);
81
    }
33672 ranu 82
 
35624 ranu 83
    /**
84
     * Knowlarity Click2Call Webhook - Push Call Log.
85
     */
35660 ranu 86
    @RequestMapping(value = "/click2call/push-call-log-handler", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
87
    public ResponseEntity<?> click2callPushLogHandler(HttpServletRequest request, @RequestBody String rawBody) throws Exception {
35624 ranu 88
        // Log raw JSON body from Knowlarity before processing, so we can see exactly what they sent
89
        LOGGER.info("push-call-log raw JSON from Knowlarity: {}", rawBody);
90
        try {
91
            ObjectMapper objectMapper = new ObjectMapper();
92
            PushCallLogModel pushCallLogModel = objectMapper.readValue(rawBody, PushCallLogModel.class);
93
            LOGGER.info("update call detail - push log (mapped): {}", pushCallLogModel);
94
            recordingService.updateAgentCallLog(pushCallLogModel);
95
        } catch (Exception e) {
96
            LOGGER.error("Error processing push-call-log webhook. Raw JSON: {}", rawBody, e);
97
        }
34530 ranu 98
        return responseSender.ok("true");
34481 ranu 99
    }
33672 ranu 100
 
34481 ranu 101
 
33672 ranu 102
    @Value("${razorpay.account.keySecret}")
103
    private String razorpaySecret;
104
    @Autowired
105
    private UpsellRazorpayPaymentStatusRepository upsellRazorpayPaymentStatusRepository;
106
 
33684 ranu 107
    @RequestMapping(value = "/upsellPayment/callback", method = RequestMethod.GET)
33715 ranu 108
    public ResponseEntity<?> handleCallback(HttpServletRequest request) {
33672 ranu 109
        try {
33688 ranu 110
            // Retrieve the Razorpay parameters from the query string
33684 ranu 111
            String paymentId = request.getParameter("razorpay_payment_id");
33688 ranu 112
            String razorpaySignature = request.getParameter("razorpay_signature");
33693 ranu 113
            String paymentLinkId = request.getParameter("razorpay_payment_link_id");
33715 ranu 114
            String paymentLinkStatus = request.getParameter("razorpay_payment_link_status");
115
            String paymentLinkReferenceId = request.getParameter("razorpay_payment_link_reference_id");
33693 ranu 116
 
33684 ranu 117
            String orderId = request.getParameter("orderId");
118
            String insuranceAmount = request.getParameter("insuranceAmount");
119
 
33688 ranu 120
            // Check for required parameters
121
            if (paymentId == null || razorpaySignature == null || orderId == null || insuranceAmount == null) {
33684 ranu 122
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Missing required parameters");
123
            }
124
 
33715 ranu 125
            JSONObject options = new JSONObject();
126
            options.put("payment_link_reference_id", paymentLinkReferenceId);
127
            options.put("razorpay_payment_id", paymentId);
128
            options.put("payment_link_status", paymentLinkStatus);
129
            options.put("payment_link_id", paymentLinkId);
130
            options.put("razorpay_signature", razorpaySignature);
33684 ranu 131
 
33715 ranu 132
            boolean status = Utils.verifyPaymentLink(options, razorpaySecret);
33693 ranu 133
 
33715 ranu 134
            LOGGER.info("status signature {}", status);
135
 
136
            if (!status) {
33672 ranu 137
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid signature");
138
            }
33715 ranu 139
            FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(Integer.parseInt(orderId));
140
            Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
141
            // Handle the payment status (you may need to add more logic depending on the status)
142
            updatePaymentStatus(paymentId, paymentLinkReferenceId, "captured", orderId, insuranceAmount);
33672 ranu 143
 
33715 ranu 144
            // Construct the HTML response
145
            String htmlResponse = "<html>" +
146
                    "<head>" +
147
                    "<style>" +
148
                    "  .container { background-color: #f0f0f0; padding: 20px; text-align: center; border-radius: 8px;max-width:600px;width:auto;margin:10px auto; }" +
149
                    "  .success-icon { color: green; font-size:30px; margin-right: 10px;border-radius: 50%;border: 2px solid;padding: 1px 7px; }" +
150
                    "  .message { font-size: 18px; margin-top: 10px; }" +
151
                    "</style>" +
152
                    "</head>" +
153
                    "<body>" +
154
                    "  <div class='container'>" +
155
                    "    <span class='success-icon'>&#10003;</span>" +
156
                    "    <div class='message'>" +
157
                    "      Hi " + customer.getFirstName() + ",<br>" +
158
                    "      Your payment of " + insuranceAmount + " was successfully completed.<br>" +
159
                    "      Your payment ID is: " + paymentId + "." +
160
                    "    </div>" +
161
                    "  </div>" +
162
                    "</body>" +
163
                    "</html>";
33689 ranu 164
 
33715 ranu 165
            return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(htmlResponse);
166
 
33672 ranu 167
        } catch (Exception e) {
168
            e.printStackTrace();
33715 ranu 169
 
33672 ranu 170
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing callback");
171
        }
172
    }
173
 
33684 ranu 174
 
33715 ranu 175
    private void updatePaymentStatus(String paymentId, String paymentLinkReferenceId, String status, String orderId, String amount) throws ProfitMandiBusinessException {
176
        int id = Integer.parseInt(paymentLinkReferenceId.replaceFirst("^0+(?!$)", ""));
177
        UpsellRazorpayPaymentStatus upsellRazorpayPaymentStatus = upsellRazorpayPaymentStatusRepository.selectById(id);
33672 ranu 178
        upsellRazorpayPaymentStatus.setPaymentId(paymentId);
33715 ranu 179
        upsellRazorpayPaymentStatus.setReferenceId(paymentLinkReferenceId);
33672 ranu 180
        upsellRazorpayPaymentStatus.setPaymentStatus(status);
33682 ranu 181
        upsellRazorpayPaymentStatus.setPayment(Float.parseFloat(amount));
33672 ranu 182
    }
32916 amit.gupta 183
}