Subversion Repositories SmartDukaan

Rev

Rev 36363 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
33715 ranu 1
package com.spice.profitmandi.web.controller;
2
 
3
 
4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
5
import com.spice.profitmandi.common.model.CustomAddress;
6
import com.spice.profitmandi.common.model.CustomPaymentOption;
7
import com.spice.profitmandi.common.model.InsuranceModel;
33717 ranu 8
import com.spice.profitmandi.common.model.ProfitMandiConstants;
34111 ranu 9
import com.spice.profitmandi.common.util.FileUtil;
33715 ranu 10
import com.spice.profitmandi.common.web.util.ResponseSender;
11
import com.spice.profitmandi.dao.entity.auth.AuthUser;
12
import com.spice.profitmandi.dao.entity.catalog.Item;
13
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
14
import com.spice.profitmandi.dao.entity.dtr.PaymentOptionTransaction;
15
import com.spice.profitmandi.dao.entity.fofo.*;
16
import com.spice.profitmandi.dao.entity.inventory.State;
34117 ranu 17
import com.spice.profitmandi.dao.entity.user.User;
33715 ranu 18
import com.spice.profitmandi.dao.enumuration.dtr.PaymentOptionReferenceType;
19
import com.spice.profitmandi.dao.enumuration.transaction.UpSaleCallStatus;
20
import com.spice.profitmandi.dao.model.PaymentLinkDetailModel;
34111 ranu 21
import com.spice.profitmandi.dao.model.UpsellingReportModel;
33715 ranu 22
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
23
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
24
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
25
import com.spice.profitmandi.dao.repository.cs.CsService;
26
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
27
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
28
import com.spice.profitmandi.dao.repository.dtr.PaymentOptionTransactionRepository;
29
import com.spice.profitmandi.dao.repository.fofo.*;
30
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
34117 ranu 31
import com.spice.profitmandi.dao.repository.user.UserRepository;
33715 ranu 32
import com.spice.profitmandi.service.NotificationService;
33
import com.spice.profitmandi.service.authentication.RoleManager;
34
import com.spice.profitmandi.service.integrations.RazorpayPaymentService;
34481 ranu 35
import com.spice.profitmandi.service.integrations.kommuno.RecordingService;
33715 ranu 36
import com.spice.profitmandi.service.integrations.zest.InsuranceService;
37
import com.spice.profitmandi.service.integrations.zest.MobileInsurancePlan;
38
import com.spice.profitmandi.service.order.OrderService;
39
import com.spice.profitmandi.web.model.LoginDetails;
40
import com.spice.profitmandi.web.util.CookiesProcessor;
41
import com.spice.profitmandi.web.util.MVCResponseSender;
42
import org.apache.logging.log4j.LogManager;
43
import org.apache.logging.log4j.Logger;
44
import org.springframework.beans.factory.annotation.Autowired;
45
import org.springframework.http.MediaType;
46
import org.springframework.http.ResponseEntity;
47
import org.springframework.stereotype.Controller;
48
import org.springframework.transaction.annotation.Transactional;
49
import org.springframework.ui.Model;
50
import org.springframework.web.bind.annotation.*;
51
 
52
import javax.servlet.http.HttpServletRequest;
33719 ranu 53
import java.time.Instant;
34111 ranu 54
import java.time.LocalDate;
33719 ranu 55
import java.time.LocalDateTime;
56
import java.time.ZoneId;
34111 ranu 57
import java.time.format.DateTimeFormatter;
33715 ranu 58
import java.util.*;
59
import java.util.stream.Collectors;
60
 
61
 
62
@Controller
63
@Transactional(rollbackFor = Throwable.class)
64
public class UpSaleController {
65
    private static final Logger LOGGER = LogManager.getLogger(UpSaleController.class);
66
    @Autowired
67
    AuthRepository authRepository;
68
    @Autowired
69
    UpsellRazorpayPaymentStatusRepository upsellRazorpayPaymentStatusRepository;
70
    @Autowired
71
    private CookiesProcessor cookiesProcessor;
72
    @Autowired
73
    private RoleManager roleManager;
74
    @Autowired
75
    private FofoOrderRepository fofoOrderRepository;
76
    @Autowired
77
    private InsurancePolicyRepository insurancePolicyRepository;
78
    @Autowired
79
    private CustomerRepository customerRepository;
80
    @Autowired
81
    private UpSaleCallRepository upSaleCallRepository;
82
    @Autowired
83
    private UpSaleOrderRepository upSaleOrderRepository;
84
    @Autowired
85
    private MVCResponseSender mvcResponseSender;
86
    @Autowired
87
    private InsuranceService insuranceService;
88
    @Autowired
89
    private FofoOrderItemRepository fofoOrderItemRepository;
90
    @Autowired
91
    private ResponseSender responseSender;
92
    @Autowired
93
    private StateRepository stateRepository;
94
    @Autowired
95
    private NotificationService notificationService;
96
    @Autowired
97
    private ItemRepository itemRepository;
98
    @Autowired
99
    private RazorpayPaymentService razorpayPaymentService;
100
    @Autowired
101
    private TagListingRepository tagListingRepository;
102
    @Autowired
103
    private PaymentOptionTransactionRepository paymentOptionTransactionRepository;
104
    @Autowired
105
    private OrderService orderService;
106
    @Autowired
107
    private FofoLineItemRepository fofoLineItemRepository;
108
    @Autowired
109
    private UpSaleAgentCollectionRepository upSaleAgentCollectionRepository;
110
    @Autowired
34481 ranu 111
    private RecordingService recordingService;
33715 ranu 112
    @Autowired
113
    private UpSellCallDetailRepository upsellCallDetailRepository;
114
 
115
    @Autowired
116
    private CsService csService;
34117 ranu 117
 
33715 ranu 118
    @Autowired
119
    private FofoStoreRepository fofoStoreRepository;
34117 ranu 120
 
33715 ranu 121
    @Autowired
34117 ranu 122
    private UserRepository userRepository;
123
 
124
    @Autowired
33715 ranu 125
    private CustomerAddressRepository customerAddressRepository;
126
 
127
    @RequestMapping(value = "/upsaleProductslist", method = RequestMethod.GET)
128
    public String upsaleProductslist(HttpServletRequest request, Model model) throws Exception {
129
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
130
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
131
        List<UpSaleAgentCollection> upSaleAgentCollections = upSaleAgentCollectionRepository.selectByAgentId(user.getId());
132
        // Calculate the total product sale amount
133
        double totalProductSaleAmount = upSaleAgentCollections.stream()
134
                .mapToDouble(UpSaleAgentCollection::getProductSaleAmount)
135
                .sum();
136
 
137
        // Add the total amount to the model
138
 
139
        List<UpSaleCallStatus> upSaleCallStatuses = new ArrayList<>(Arrays.asList(UpSaleCallStatus.values()));
140
        LOGGER.info("upSaleCallStatuses {}", upSaleCallStatuses);
141
 
142
        model.addAttribute("upSaleCallStatuses", upSaleCallStatuses);
143
        model.addAttribute("totalProductSaleAmount", totalProductSaleAmount);
144
        model.addAttribute("upSaleAgentCollections", upSaleAgentCollections);
145
        return "up-sale-call";
146
    }
147
 
148
    @RequestMapping(value = "/razorpapPaymentStatus", method = RequestMethod.GET)
149
    public String razorpapPaymentStatusAgainstOrderID(HttpServletRequest request, Model model, @RequestParam int orderId) throws Exception {
150
        List<UpsellRazorpayPaymentStatus> upSellRazorpayPaymentStatusList = upsellRazorpayPaymentStatusRepository.selectByOrderId(orderId);
151
        LOGGER.info("upSellRazorpayPaymentStatusList {}", upSellRazorpayPaymentStatusList);
152
        model.addAttribute("upSellRazorpayPaymentStatusList", upSellRazorpayPaymentStatusList);
153
 
154
        return "upsell-payment-confirmation";
155
    }
156
 
157
    @RequestMapping(value = "/fetchMobileNumberForUpSale", method = RequestMethod.GET)
158
    public String fetchMobileNumberForUpSale(HttpServletRequest request, Model model) throws Exception {
159
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
160
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
161
 
33717 ranu 162
        Map<String, Set<Integer>> pp = csService.getAuthUserPartnerIdMappingByCategoryIds(Arrays.asList(ProfitMandiConstants.UPSELLING), true);
163
        Set<Integer> fofoIds = new HashSet<>(pp.get(user.getEmailId()));
33715 ranu 164
 
165
        List<UpSaleAgentCollection> upSaleAgentCollections = upSaleAgentCollectionRepository.selectByAgentId(user.getId());
166
        double totalProductSaleAmount = upSaleAgentCollections.stream()
167
                .mapToDouble(UpSaleAgentCollection::getProductSaleAmount)
168
                .sum();
169
 
170
        try {
171
            // Fetch all rescheduled calls and filter them in-memory
172
            List<UpSaleCall> upSaleCalls = upSaleCallRepository.selectAllByDispostion(UpSaleCallStatus.RESCHEDULED);
34081 ranu 173
            LOGGER.info("UpSaleCall {}", upSaleCalls);
34082 ranu 174
 
33715 ranu 175
            List<UpSaleCall> filteredUpSaleCalls = upSaleCalls.stream()
34082 ranu 176
                    .filter(call -> call.getRescheduledTimestamp() != null
177
                            && call.getRescheduledTimestamp().isBefore(LocalDateTime.now())
178
                            && call.getCreatedTimestamp() != null
179
                            && call.getCreatedTimestamp().isAfter(LocalDateTime.now().minusHours(48)))
33715 ranu 180
                    .collect(Collectors.toList());
181
 
182
            if (!filteredUpSaleCalls.isEmpty()) {
183
                for (UpSaleCall upSaleCall : filteredUpSaleCalls) {
184
                    FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(upSaleCall.getOriginalOrderId());
34117 ranu 185
                    User fofoUser = userRepository.selectById(fofoOrder.getFofoId());
33715 ranu 186
 
187
                    Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
188
                    if (fofoIds.contains(fofoOrder.getFofoId())) {
189
                        if (customer != null) {
190
                            upSaleCall.setStatus(UpSaleCallStatus.FETCHED);
191
                            upSaleCall.setRescheduledTimestamp(null);
192
 
193
                            List<Map<String, Object>> itemDetails = new ArrayList<>();
194
                            List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
195
 
196
                            for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
197
                                Item item = itemRepository.selectById(fofoOrderItem.getItemId());
198
                                if (item.isSmartPhone()) {
199
                                    Map<String, List<MobileInsurancePlan>> plans = this.getPlans(fofoOrderItem.getSellingPrice(), item.getId());
200
                                    Map<String, Object> itemDetail = new HashMap<>();
201
                                    itemDetail.put("item", item);
202
                                    itemDetail.put("fofoOrderItem", fofoOrderItem);
203
                                    itemDetail.put("plans", plans);
204
                                    itemDetails.add(itemDetail);
205
                                }
206
                            }
207
 
208
                            Set<Integer> fofoOrderItemIds = fofoOrderItems.stream().map(FofoOrderItem::getId).collect(Collectors.toSet());
209
                            List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
210
 
211
                            Map<Integer, List<FofoLineItem>> fofoLineItemMap = fofoLineItems.stream()
212
                                    .collect(Collectors.groupingBy(FofoLineItem::getFofoOrderItemId));
213
 
214
                            List<UpSaleCallStatus> upSaleCallStatuses = new ArrayList<>(Arrays.asList(UpSaleCallStatus.values()));
215
 
216
                            model.addAttribute("upSaleCallStatuses", upSaleCallStatuses);
217
                            model.addAttribute("fofoOrder", fofoOrder);
34117 ranu 218
                            model.addAttribute("fofoUser", fofoUser);
33715 ranu 219
                            model.addAttribute("customer", customer);
220
                            model.addAttribute("itemDetails", itemDetails);
221
                            model.addAttribute("fofoLineItemMap", fofoLineItemMap);
222
                            model.addAttribute("upsaleCallId", upSaleCall.getId());
223
                            model.addAttribute("stateNames",
224
                                    stateRepository.selectAll().stream().map(x -> x.getName()).collect(Collectors.toList()));
225
                            model.addAttribute("totalProductSaleAmount", totalProductSaleAmount);
226
 
227
                            return "up-sale-call";
228
                        }
229
                    }
230
                }
34082 ranu 231
            } else {
232
                throw new RuntimeException("No filtered calls available for processing");
33715 ranu 233
            }
234
        } catch (Exception e) {
235
            // If no rescheduled calls found, fall back to original logic
33720 ranu 236
            UpSaleOrder TMinus2UpsaleOrder = this.getTMinus2UpSaleOrderByFofoIds(fofoIds);
33715 ranu 237
 
33720 ranu 238
            TMinus2UpsaleOrder.setFetched(true);
33719 ranu 239
 
33720 ranu 240
            LOGGER.info("last48hourLatestOrder {}", TMinus2UpsaleOrder);
241
            if (TMinus2UpsaleOrder != null) {
242
                boolean exists = upSaleCallRepository.existsOrderId(TMinus2UpsaleOrder.getOrderId());
33715 ranu 243
                if (!exists) {
33720 ranu 244
                    FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(TMinus2UpsaleOrder.getOrderId());
34117 ranu 245
                    User fofoUser = userRepository.selectById(fofoOrder.getFofoId());
33715 ranu 246
                    if (fofoIds.contains(fofoOrder.getFofoId())) {
247
                        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
248
                        if (customer != null) {
249
                            String mobile = customer.getMobileNumber();
33720 ranu 250
                            UpSaleCall upSaleCall = new UpSaleCall();
251
                            upSaleCall.setAgentId(user.getId());
252
                            upSaleCall.setMobile(mobile);
253
                            upSaleCall.setOriginalOrderId(fofoOrder.getId());
254
                            upSaleCall.setStatus(UpSaleCallStatus.FETCHED);
255
                            upSaleCall.setCreatedTimestamp(LocalDateTime.now());
256
                            upSaleCallRepository.persist(upSaleCall);
33715 ranu 257
 
33720 ranu 258
                            LOGGER.info("Processing UpSaleOrder {}", TMinus2UpsaleOrder);
33715 ranu 259
 
33720 ranu 260
                            List<Map<String, Object>> itemDetails = new ArrayList<>();
261
                            List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
33715 ranu 262
 
33720 ranu 263
                            for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
264
                                Item item = itemRepository.selectById(fofoOrderItem.getItemId());
265
                                if (item.isSmartPhone()) {
266
                                    float sellingPrice = tagListingRepository.selectByItemId(item.getId()).getSellingPrice();
267
                                    Map<String, List<MobileInsurancePlan>> plans = this.getPlans(fofoOrderItem.getSellingPrice(), item.getId());
268
                                    Map<String, Object> itemDetail = new HashMap<>();
269
                                    itemDetail.put("item", item);
270
                                    itemDetail.put("fofoOrderItem", fofoOrderItem);
271
                                    itemDetail.put("plans", plans);
272
                                    itemDetails.add(itemDetail);
33715 ranu 273
                                }
33720 ranu 274
                            }
33715 ranu 275
 
33720 ranu 276
                            Set<Integer> fofoOrderItemIds = fofoOrderItems.stream().map(FofoOrderItem::getId).collect(Collectors.toSet());
277
                            List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
33715 ranu 278
 
33720 ranu 279
                            Map<Integer, List<FofoLineItem>> fofoLineItemMap = fofoLineItems.stream()
280
                                    .collect(Collectors.groupingBy(FofoLineItem::getFofoOrderItemId));
33715 ranu 281
 
33720 ranu 282
                            List<UpSaleCallStatus> upSaleCallStatuses = new ArrayList<>(Arrays.asList(UpSaleCallStatus.values()));
33715 ranu 283
 
33720 ranu 284
                            model.addAttribute("upSaleCallStatuses", upSaleCallStatuses);
285
                            model.addAttribute("fofoOrder", fofoOrder);
34117 ranu 286
                            model.addAttribute("fofoUser", fofoUser);
33720 ranu 287
                            model.addAttribute("customer", customer);
288
                            model.addAttribute("itemDetails", itemDetails);
289
                            model.addAttribute("fofoLineItemMap", fofoLineItemMap);
290
                            model.addAttribute("upsaleCallId", upSaleCall.getId());
291
                            model.addAttribute("stateNames",
292
                                    stateRepository.selectAll().stream().map(State::getName).collect(Collectors.toList()));
293
                            model.addAttribute("totalProductSaleAmount", totalProductSaleAmount);
33715 ranu 294
 
33720 ranu 295
                            return "up-sale-call";
33719 ranu 296
 
33715 ranu 297
                        }
298
                    }
299
                }
33720 ranu 300
            }
33719 ranu 301
 
33715 ranu 302
        }
303
 
304
 
305
        LOGGER.info("No valid UpSaleOrder found for up-sale call.");
306
        model.addAttribute("totalProductSaleAmount", totalProductSaleAmount);
307
        model.addAttribute("message", "No valid UpSaleOrder found.");
34082 ranu 308
 
33715 ranu 309
        return "up-sale-call";
310
    }
311
 
33720 ranu 312
    UpSaleOrder getTMinus2UpSaleOrderByFofoIds(Set<Integer> fofoIds) {
33719 ranu 313
        LocalDateTime startDateTime = LocalDateTime.now().minusDays(2); // 48 hours ago
33720 ranu 314
        return upSaleOrderRepository.getTMinus2UpSaleOrderByFofoIds(fofoIds, startDateTime);
33719 ranu 315
    }
316
 
33715 ranu 317
    @RequestMapping(value = "/generatePaymentLink", method = RequestMethod.POST)
318
    public ResponseEntity<String> generatePaymentLink(HttpServletRequest request, Model model, @RequestBody PaymentLinkDetailModel paymentLinkDetailModel) {
319
        double amount;
320
        LOGGER.info("paymnetlinkmodel {}", paymentLinkDetailModel);
321
        try {
322
            String paymentLink = razorpayPaymentService.createPaymentLink(paymentLinkDetailModel);
323
 
324
            LOGGER.info("paymentLink {}", paymentLink);
37409 vikas 325
            notificationService.sendPaymentLink(paymentLinkDetailModel.getMobile(), paymentLink);
33715 ranu 326
 
327
//            model.addAttribute("message", "Payment link generated and sent successfully!");
328
            return responseSender.ok(true);
329
        } catch (Exception e) {
330
//            model.addAttribute("message", "Failed to generate payment link: " + e.getMessage());
331
            return responseSender.ok(false);
332
        }
333
 
334
 
335
    }
336
 
337
    private Map<String, List<MobileInsurancePlan>> getPlans(float sellingPrice, int itemId)
338
            throws ProfitMandiBusinessException {
339
        try {
340
            Map<String, List<MobileInsurancePlan>> productDurationPlans = new HashMap<>();
341
            productDurationPlans = insuranceService.getAllPlans(itemId,
342
                    sellingPrice, false);
343
 
344
            return productDurationPlans;
345
        } catch (Exception e) {
346
            LOGGER.info(e, e);
347
            throw new ProfitMandiBusinessException("Fetch Insurance Plans", "Insurance",
348
                    "Could not fetch insurance Plans");
349
        }
350
 
351
    }
352
 
353
    @RequestMapping(value = "/upsell/clickToCall/{toMobile}/{upsellCallId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
354
    public ResponseEntity<?> upsellClickToCall(HttpServletRequest request, @PathVariable String toMobile, @PathVariable int upsellCallId) throws Exception {
355
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
356
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
34481 ranu 357
        recordingService.upsellClickToCallKommuno(toMobile, loginDetails.getEmailId(), upsellCallId);
33715 ranu 358
        return responseSender.ok(true);
359
    }
360
 
361
    @RequestMapping(value = "/upsell/disposition/{upsellCallId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
362
    public ResponseEntity<?> upsellDisposition(HttpServletRequest request,
363
                                               @PathVariable String upsellCallId,
364
                                               @RequestParam(name = "disposition", required = false) UpSaleCallStatus disposition,
365
                                               @RequestParam(name = "scheduleTime", required = false) String scheduleTime) throws Exception {
366
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
367
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
368
 
369
        UpsellCallDetail upsellCallDetail = upsellCallDetailRepository.selectByUpSellCallId(upsellCallId);
370
        LOGGER.info("upsellCallDetail {}", upsellCallDetail);
371
        upsellCallDetail.setAgentId(user.getEmailId());
372
        upsellCallDetail.setDisposition(disposition);
373
        upsellCallDetail.setRemark(disposition.getValue());
374
 
375
 
376
        if (scheduleTime != null && !scheduleTime.isEmpty()) {
377
            UpSaleCall upSaleCall = upSaleCallRepository.selectById(Integer.parseInt(upsellCallId));
378
            Instant instant = Instant.parse(scheduleTime);
379
            LocalDateTime scheduledDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
380
            upSaleCall.setRescheduledTimestamp(scheduledDateTime);
381
            upSaleCall.setStatus(disposition);
382
        }
383
 
384
        // Generate session id with 16 digits as kommuno service
385
        Long newId = (long) upsellCallDetail.getId();
33968 ranu 386
        String sessionId = String.format("%014d", newId);
33715 ranu 387
        upsellCallDetail.setDiallerSessionId(sessionId);
388
 
389
//        fill diposition on kommuno service
34481 ranu 390
        recordingService.upsellFillDispositionWithKommuno(disposition.getValue(), sessionId);
33715 ranu 391
 
392
        return responseSender.ok(true);
393
    }
394
 
395
    @RequestMapping(value = "/generatePlanDetail", method = RequestMethod.POST)
396
    public String generatePlanDetail(HttpServletRequest request, Model model, @RequestBody PaymentLinkDetailModel paymentLinkDetailModel) throws Exception {
397
        FofoOrderItem foi = fofoOrderItemRepository.selectById(Integer.parseInt(paymentLinkDetailModel.getOrderItemId()));
398
 
399
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(Integer.parseInt(paymentLinkDetailModel.getOrderId()));
400
        float deviceSellingPrice = tagListingRepository.selectByItemId(foi.getItemId()).getSellingPrice();
401
        MobileInsurancePlan mobileInsurancePlan = insuranceService.getPlanById(paymentLinkDetailModel.getPlanId(), foi.getSellingPrice(), paymentLinkDetailModel.getPlanName());
402
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
403
 
404
        model.addAttribute("fofoOrder", fofoOrder);
405
        model.addAttribute("fofoOrderItem", foi);
406
        model.addAttribute("deviceSellinnPrice", deviceSellingPrice);
407
        model.addAttribute("mobileInsurancePlan", mobileInsurancePlan);
408
        model.addAttribute("serialNumber", paymentLinkDetailModel.getSerialNumber());
409
        model.addAttribute("customer", customer);
410
        model.addAttribute("customerAddress", customer.getCustomerAddress());
411
        return "upsale-create-insurance-model";
412
    }
413
 
414
    @RequestMapping(value = "/create-insurance", method = RequestMethod.POST)
415
    public ResponseEntity<?> createInsurance(HttpServletRequest request, @RequestBody InsuranceModel insuranceModel, Model model) throws Exception {
416
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
417
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
418
        LOGGER.info("request at uri {} body {}", request.getRequestURI(), insuranceModel);
419
        FofoOrderItem foi = fofoOrderItemRepository.selectById(insuranceModel.getFofoOrderItemId());
420
        float deviceSellingPrice = tagListingRepository.selectByItemId(foi.getItemId()).getSellingPrice();
421
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
422
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoOrder.getFofoId());
423
 
424
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
425
        LOGGER.info("customer {}", customer);
426
        LOGGER.info("customerAddress {}", customer.getCustomerAddress());
427
        if (fofoOrder.getCustomerAddressId() == 0) {
428
            throw new Exception("Please select a address or add new address");
429
        }
430
        customer.setDob(insuranceModel.getDob());
431
 
432
        fofoOrder.setDateOfBirth(insuranceModel.getDob());
433
        insuranceModel.setBrand(foi.getBrand());
434
        insuranceModel.setMfgDate(insuranceModel.getWmfgDate().atStartOfDay());
435
        insuranceModel.setColor(foi.getColor());
34197 ranu 436
        insuranceModel.setInsuranceUId(insuranceModel.getInsuranceId());
437
        insuranceModel.setInsuranceId(String.valueOf(insuranceService.getOneAssistPremiumByVariantId(insuranceModel.getInsuranceId()).getId()));
33715 ranu 438
        insuranceModel.setModelName(String.join(" ", foi.getModelName(), foi.getModelNumber()));
439
        insuranceModel.setDeviceSellingPrice(deviceSellingPrice);
440
 
441
        InsurancePolicy insurancePolicy = insuranceService.createInsurance(fofoOrder, insuranceModel, true);
442
        String documentNumber = orderService.getInvoiceNumber(fofoOrder.getFofoId(), fs.getCode());
443
        insurancePolicy.setInvoiceNumber(documentNumber);
444
        insurancePolicy.setDeviceInvoiceNumber(fofoOrder.getInvoiceNumber());
445
 
446
        FofoOrder fo = this.createAndGetFofoOrder(customer.getId(), fofoOrder.getCustomerGstNumber(), fofoOrder.getFofoId(), insurancePolicy.getInvoiceNumber(), insuranceModel.getInsuranceAmount(), fofoOrder.getCustomerAddressId());
447
 
448
        this.createPaymentOptions(fo, insuranceModel.getPaymentOptions());
449
 
450
//        agent collection persistance
451
 
452
        UpSaleAgentCollection upSaleAgentCollection = new UpSaleAgentCollection();
453
        upSaleAgentCollection.setAgentId(user.getId());
454
        upSaleAgentCollection.setOrderId(fofoOrder.getId());
455
        upSaleAgentCollection.setProductId(insuranceModel.getInsuranceId());
456
        upSaleAgentCollection.setInsurancePolicyId(insurancePolicy.getId());
457
        upSaleAgentCollection.setProductSaleAmount(insurancePolicy.getSaleAmount());
458
//        if insurance plan is selling than is insurance will be true
459
        upSaleAgentCollection.setInsurance(true);
460
        upSaleAgentCollection.setCreatedTimestamp(LocalDateTime.now());
461
        upSaleAgentCollectionRepository.persist(upSaleAgentCollection);
462
 
463
        return responseSender.ok(true);
464
    }
465
 
466
    private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions) throws ProfitMandiBusinessException {
467
        for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
468
            if (customPaymentOption.getAmount() > 0) {
469
                PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
470
                paymentOptionTransaction.setReferenceId(fofoOrder.getId());
471
                paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
472
                paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.INSURANCE);
473
                paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
474
                paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
475
                paymentOptionTransactionRepository.persist(paymentOptionTransaction);
476
            }
477
        }
478
    }
479
 
480
    private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, String documentNumber, float totalAmount, int customerAddressId) {
36363 amit 481
        // Idempotency: fast-path return if the row already exists for this (fofo, invoice).
482
        // Protects against concurrent duplicate inserts (client retry / upstream webhook retry).
483
        FofoOrder existing = findExistingFofoOrder(fofoId, documentNumber);
484
        if (existing != null) return existing;
485
 
33715 ranu 486
        FofoOrder fofoOrder = new FofoOrder();
487
        fofoOrder.setCustomerGstNumber(customerGstNumber);
488
        fofoOrder.setCustomerId(customerId);
489
        fofoOrder.setFofoId(fofoId);
490
        fofoOrder.setInvoiceNumber(documentNumber);
491
        fofoOrder.setTotalAmount(totalAmount);
492
        fofoOrder.setCustomerAddressId(customerAddressId);
36363 amit 493
        try {
494
            fofoOrderRepository.persist(fofoOrder);
495
        } catch (org.springframework.dao.DataIntegrityViolationException dup) {
496
            // Lost a narrow race between our select and insert — re-fetch the winner's row.
497
            // Requires uk_fofo_order_fofo_invoice unique key to trigger this exception.
498
            FofoOrder winner = findExistingFofoOrder(fofoId, documentNumber);
499
            if (winner != null) return winner;
500
            throw dup;
501
        }
33715 ranu 502
        return fofoOrder;
503
    }
504
 
36363 amit 505
    private FofoOrder findExistingFofoOrder(int fofoId, String invoiceNumber) {
506
        try {
507
            return fofoOrderRepository.selectByFofoIdAndInvoiceNumber(fofoId, invoiceNumber);
508
        } catch (ProfitMandiBusinessException ignored) {
509
            return null;
510
        }
511
    }
512
 
33715 ranu 513
    @RequestMapping(value = "/customer/addaddress", method = RequestMethod.POST)
514
    public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestParam int customerId,
515
                                        @RequestBody CustomAddress customAddress) {
516
        CustomerAddress customerAddress = this.toCustomerAddress(customerId, customAddress);
517
        customerAddressRepository.persist(customerAddress);
518
        return responseSender.ok(this.toCustomAddress(customerAddress));
519
 
520
    }
521
 
522
    private CustomAddress toCustomAddress(CustomerAddress customerAddress) {
523
        CustomAddress customAddress = new CustomAddress();
524
        customAddress.setCity(customerAddress.getCity());
525
        customAddress.setCountry(customerAddress.getCountry());
526
        customAddress.setLandmark(customerAddress.getLandmark());
527
        customAddress.setLine1(customerAddress.getLine1());
528
        customAddress.setLine2(customerAddress.getLine2());
529
        customAddress.setName(customerAddress.getName());
530
        customAddress.setLastName(customerAddress.getLastName());
531
        customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
532
        customAddress.setPinCode(customerAddress.getPinCode());
533
        customAddress.setState(customerAddress.getState());
534
        customAddress.setId(customerAddress.getId());
535
        return customAddress;
536
    }
537
 
538
    private CustomerAddress toCustomerAddress(int customerId, CustomAddress customAddress) {
539
        CustomerAddress customerAddress = new CustomerAddress();
540
        customerAddress.setCustomerId(customerId);
541
        customerAddress.setName(customAddress.getName());
542
        customerAddress.setLastName(customAddress.getLastName());
543
        customerAddress.setLine1(customAddress.getLine1());
544
        customerAddress.setLine2(customAddress.getLine2());
545
        customerAddress.setLandmark(customAddress.getLandmark());
546
        customerAddress.setCity(customAddress.getCity());
547
        customerAddress.setPinCode(customAddress.getPinCode());
548
        customerAddress.setState(customAddress.getState());
549
        customerAddress.setCountry(customAddress.getCountry());
550
        customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
551
 
552
        return customerAddress;
553
    }
554
 
555
 
556
    @RequestMapping(value = "/update-fofoOrder-addressId", method = RequestMethod.POST)
557
    public ResponseEntity<?> updateFofoOrderAddresId(HttpServletRequest request, @RequestParam(name = "orderId", defaultValue = "0") int orderId, @RequestParam(name = "addressId", defaultValue = "0") int addressId, Model model) throws Exception {
558
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
559
        fofoOrder.setCustomerAddressId(addressId);
560
        return responseSender.ok(true);
561
    }
562
 
34111 ranu 563
    @RequestMapping(value = "/downloadUpsellingReport", method = RequestMethod.GET)
564
    public ResponseEntity<?> downloadUpsellingReport(HttpServletRequest request,
565
                                                     @RequestParam(name = "startDate") LocalDateTime startDate,
566
                                                     @RequestParam(name = "endDate") LocalDateTime endDate, Model model)
567
            throws Exception {
33715 ranu 568
 
34111 ranu 569
        List<List<?>> rows = new ArrayList<>();
570
 
571
        LocalDate startLocalDate = startDate.toLocalDate();
572
        LocalDate endLocalDate = endDate.toLocalDate();
573
 
574
        List<UpsellingReportModel> upsellingReportModels = upSaleCallRepository.getUpsellingReport(startLocalDate, endLocalDate.plusDays(1));
575
 
576
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
577
 
578
        for (
579
                UpsellingReportModel report : upsellingReportModels) {
580
 
581
            rows.add(Arrays.asList(
582
                    report.getAgentEmail(),
34117 ranu 583
                    report.getPartnerName(),
34133 ranu 584
                    report.getPartnerMobile(),
34134 ranu 585
                    report.getState(),
34133 ranu 586
                    report.getPartnerName(),
34111 ranu 587
                    report.getOrderId(),
588
                    report.getCustomerNumber(),
589
                    report.getCallingDate(),
34131 ranu 590
                    report.getDisposition(),
591
                    report.getRemark(),
34111 ranu 592
                    report.getPaymentStatus(),
593
                    report.getInsuranceStatus(),
594
                    report.getPolicySoldAmount(),
595
                    report.getInvoiceNumber(),
596
                    report.getSerialNumber()
597
            ));
598
 
599
        }
600
 
601
 
602
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
34134 ranu 603
                .getCSVByteStream(Arrays.asList("Agent Email", "Partner Name", "Partner Mobile Number", "Partner State", "Order Id", "Customer Mobile Number", "Calling Date", "Disposition", "Remark", "Payment Status", "Insurance Status", "Policy Sold Amount", "Invoice Number", "Serial Number"), rows);
34111 ranu 604
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, " Upselling Report");
605
 
606
        return responseEntity;
607
 
608
    }
609
 
610
    @RequestMapping(value = "/getUpsellingReport", method = RequestMethod.GET)
611
    public String getUpsellingReport(
612
            HttpServletRequest request,
613
            @RequestParam(name = "startDate") LocalDateTime startDate,
614
            @RequestParam(name = "endDate") LocalDateTime endDate, Model model
615
    ) throws Exception {
616
 
617
        LocalDate startLocalDate = startDate.toLocalDate();
618
        LocalDate endLocalDate = endDate.toLocalDate();
619
 
620
        List<UpsellingReportModel> upsellingReportModels = upSaleCallRepository.getUpsellingReport(startLocalDate, endLocalDate.plusDays(1));
621
 
622
        model.addAttribute("upsellingReportModels", upsellingReportModels);
623
 
624
        return "upselling-report";
625
    }
626
 
627
    @RequestMapping(value = "/upsellingCallingList", method = RequestMethod.GET)
628
    public String upsellingCallingList(
629
            HttpServletRequest request, Model model) throws Exception {
630
 
631
        return "upselling-calling-list";
632
    }
633
 
33715 ranu 634
}