Subversion Repositories SmartDukaan

Rev

Rev 34197 | 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);
325
            String message = "Dear Customer,\n" +
326
                    "Here is a payment link for your recent purchased product.\n" +
327
                    "Please do your payment with this link\n" +
328
                    paymentLink + "\n" +
329
                    "Team SmartDukaan";
330
            LOGGER.info("message- {}", message);
331
            notificationService.sendPaymentWhatsappMessage(paymentLinkDetailModel.getMobile(), message);
33968 ranu 332
//            notificationService.sendPaymentWhatsappMessage("7082253510", message);
33715 ranu 333
 
334
//            model.addAttribute("message", "Payment link generated and sent successfully!");
335
            return responseSender.ok(true);
336
        } catch (Exception e) {
337
//            model.addAttribute("message", "Failed to generate payment link: " + e.getMessage());
338
            return responseSender.ok(false);
339
        }
340
 
341
 
342
    }
343
 
344
    private Map<String, List<MobileInsurancePlan>> getPlans(float sellingPrice, int itemId)
345
            throws ProfitMandiBusinessException {
346
        try {
347
            Map<String, List<MobileInsurancePlan>> productDurationPlans = new HashMap<>();
348
            productDurationPlans = insuranceService.getAllPlans(itemId,
349
                    sellingPrice, false);
350
 
351
            return productDurationPlans;
352
        } catch (Exception e) {
353
            LOGGER.info(e, e);
354
            throw new ProfitMandiBusinessException("Fetch Insurance Plans", "Insurance",
355
                    "Could not fetch insurance Plans");
356
        }
357
 
358
    }
359
 
360
    @RequestMapping(value = "/upsell/clickToCall/{toMobile}/{upsellCallId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
361
    public ResponseEntity<?> upsellClickToCall(HttpServletRequest request, @PathVariable String toMobile, @PathVariable int upsellCallId) throws Exception {
362
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
363
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
34481 ranu 364
        recordingService.upsellClickToCallKommuno(toMobile, loginDetails.getEmailId(), upsellCallId);
33715 ranu 365
        return responseSender.ok(true);
366
    }
367
 
368
    @RequestMapping(value = "/upsell/disposition/{upsellCallId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
369
    public ResponseEntity<?> upsellDisposition(HttpServletRequest request,
370
                                               @PathVariable String upsellCallId,
371
                                               @RequestParam(name = "disposition", required = false) UpSaleCallStatus disposition,
372
                                               @RequestParam(name = "scheduleTime", required = false) String scheduleTime) throws Exception {
373
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
374
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
375
 
376
        UpsellCallDetail upsellCallDetail = upsellCallDetailRepository.selectByUpSellCallId(upsellCallId);
377
        LOGGER.info("upsellCallDetail {}", upsellCallDetail);
378
        upsellCallDetail.setAgentId(user.getEmailId());
379
        upsellCallDetail.setDisposition(disposition);
380
        upsellCallDetail.setRemark(disposition.getValue());
381
 
382
 
383
        if (scheduleTime != null && !scheduleTime.isEmpty()) {
384
            UpSaleCall upSaleCall = upSaleCallRepository.selectById(Integer.parseInt(upsellCallId));
385
            Instant instant = Instant.parse(scheduleTime);
386
            LocalDateTime scheduledDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
387
            upSaleCall.setRescheduledTimestamp(scheduledDateTime);
388
            upSaleCall.setStatus(disposition);
389
        }
390
 
391
        // Generate session id with 16 digits as kommuno service
392
        Long newId = (long) upsellCallDetail.getId();
33968 ranu 393
        String sessionId = String.format("%014d", newId);
33715 ranu 394
        upsellCallDetail.setDiallerSessionId(sessionId);
395
 
396
//        fill diposition on kommuno service
34481 ranu 397
        recordingService.upsellFillDispositionWithKommuno(disposition.getValue(), sessionId);
33715 ranu 398
 
399
        return responseSender.ok(true);
400
    }
401
 
402
    @RequestMapping(value = "/generatePlanDetail", method = RequestMethod.POST)
403
    public String generatePlanDetail(HttpServletRequest request, Model model, @RequestBody PaymentLinkDetailModel paymentLinkDetailModel) throws Exception {
404
        FofoOrderItem foi = fofoOrderItemRepository.selectById(Integer.parseInt(paymentLinkDetailModel.getOrderItemId()));
405
 
406
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(Integer.parseInt(paymentLinkDetailModel.getOrderId()));
407
        float deviceSellingPrice = tagListingRepository.selectByItemId(foi.getItemId()).getSellingPrice();
408
        MobileInsurancePlan mobileInsurancePlan = insuranceService.getPlanById(paymentLinkDetailModel.getPlanId(), foi.getSellingPrice(), paymentLinkDetailModel.getPlanName());
409
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
410
 
411
        model.addAttribute("fofoOrder", fofoOrder);
412
        model.addAttribute("fofoOrderItem", foi);
413
        model.addAttribute("deviceSellinnPrice", deviceSellingPrice);
414
        model.addAttribute("mobileInsurancePlan", mobileInsurancePlan);
415
        model.addAttribute("serialNumber", paymentLinkDetailModel.getSerialNumber());
416
        model.addAttribute("customer", customer);
417
        model.addAttribute("customerAddress", customer.getCustomerAddress());
418
        return "upsale-create-insurance-model";
419
    }
420
 
421
    @RequestMapping(value = "/create-insurance", method = RequestMethod.POST)
422
    public ResponseEntity<?> createInsurance(HttpServletRequest request, @RequestBody InsuranceModel insuranceModel, Model model) throws Exception {
423
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
424
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
425
        LOGGER.info("request at uri {} body {}", request.getRequestURI(), insuranceModel);
426
        FofoOrderItem foi = fofoOrderItemRepository.selectById(insuranceModel.getFofoOrderItemId());
427
        float deviceSellingPrice = tagListingRepository.selectByItemId(foi.getItemId()).getSellingPrice();
428
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
429
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoOrder.getFofoId());
430
 
431
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
432
        LOGGER.info("customer {}", customer);
433
        LOGGER.info("customerAddress {}", customer.getCustomerAddress());
434
        if (fofoOrder.getCustomerAddressId() == 0) {
435
            throw new Exception("Please select a address or add new address");
436
        }
437
        customer.setDob(insuranceModel.getDob());
438
 
439
        fofoOrder.setDateOfBirth(insuranceModel.getDob());
440
        insuranceModel.setBrand(foi.getBrand());
441
        insuranceModel.setMfgDate(insuranceModel.getWmfgDate().atStartOfDay());
442
        insuranceModel.setColor(foi.getColor());
34197 ranu 443
        insuranceModel.setInsuranceUId(insuranceModel.getInsuranceId());
444
        insuranceModel.setInsuranceId(String.valueOf(insuranceService.getOneAssistPremiumByVariantId(insuranceModel.getInsuranceId()).getId()));
33715 ranu 445
        insuranceModel.setModelName(String.join(" ", foi.getModelName(), foi.getModelNumber()));
446
        insuranceModel.setDeviceSellingPrice(deviceSellingPrice);
447
 
448
        InsurancePolicy insurancePolicy = insuranceService.createInsurance(fofoOrder, insuranceModel, true);
449
        String documentNumber = orderService.getInvoiceNumber(fofoOrder.getFofoId(), fs.getCode());
450
        insurancePolicy.setInvoiceNumber(documentNumber);
451
        insurancePolicy.setDeviceInvoiceNumber(fofoOrder.getInvoiceNumber());
452
 
453
        FofoOrder fo = this.createAndGetFofoOrder(customer.getId(), fofoOrder.getCustomerGstNumber(), fofoOrder.getFofoId(), insurancePolicy.getInvoiceNumber(), insuranceModel.getInsuranceAmount(), fofoOrder.getCustomerAddressId());
454
 
455
        this.createPaymentOptions(fo, insuranceModel.getPaymentOptions());
456
 
457
//        agent collection persistance
458
 
459
        UpSaleAgentCollection upSaleAgentCollection = new UpSaleAgentCollection();
460
        upSaleAgentCollection.setAgentId(user.getId());
461
        upSaleAgentCollection.setOrderId(fofoOrder.getId());
462
        upSaleAgentCollection.setProductId(insuranceModel.getInsuranceId());
463
        upSaleAgentCollection.setInsurancePolicyId(insurancePolicy.getId());
464
        upSaleAgentCollection.setProductSaleAmount(insurancePolicy.getSaleAmount());
465
//        if insurance plan is selling than is insurance will be true
466
        upSaleAgentCollection.setInsurance(true);
467
        upSaleAgentCollection.setCreatedTimestamp(LocalDateTime.now());
468
        upSaleAgentCollectionRepository.persist(upSaleAgentCollection);
469
 
470
        return responseSender.ok(true);
471
    }
472
 
473
    private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions) throws ProfitMandiBusinessException {
474
        for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
475
            if (customPaymentOption.getAmount() > 0) {
476
                PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
477
                paymentOptionTransaction.setReferenceId(fofoOrder.getId());
478
                paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
479
                paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.INSURANCE);
480
                paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
481
                paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
482
                paymentOptionTransactionRepository.persist(paymentOptionTransaction);
483
            }
484
        }
485
    }
486
 
487
    private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, String documentNumber, float totalAmount, int customerAddressId) {
488
        FofoOrder fofoOrder = new FofoOrder();
489
        fofoOrder.setCustomerGstNumber(customerGstNumber);
490
        fofoOrder.setCustomerId(customerId);
491
        fofoOrder.setFofoId(fofoId);
492
        fofoOrder.setInvoiceNumber(documentNumber);
493
        fofoOrder.setTotalAmount(totalAmount);
494
        fofoOrder.setCustomerAddressId(customerAddressId);
495
        fofoOrderRepository.persist(fofoOrder);
496
        return fofoOrder;
497
    }
498
 
499
    @RequestMapping(value = "/customer/addaddress", method = RequestMethod.POST)
500
    public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestParam int customerId,
501
                                        @RequestBody CustomAddress customAddress) {
502
        CustomerAddress customerAddress = this.toCustomerAddress(customerId, customAddress);
503
        customerAddressRepository.persist(customerAddress);
504
        return responseSender.ok(this.toCustomAddress(customerAddress));
505
 
506
    }
507
 
508
    private CustomAddress toCustomAddress(CustomerAddress customerAddress) {
509
        CustomAddress customAddress = new CustomAddress();
510
        customAddress.setCity(customerAddress.getCity());
511
        customAddress.setCountry(customerAddress.getCountry());
512
        customAddress.setLandmark(customerAddress.getLandmark());
513
        customAddress.setLine1(customerAddress.getLine1());
514
        customAddress.setLine2(customerAddress.getLine2());
515
        customAddress.setName(customerAddress.getName());
516
        customAddress.setLastName(customerAddress.getLastName());
517
        customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
518
        customAddress.setPinCode(customerAddress.getPinCode());
519
        customAddress.setState(customerAddress.getState());
520
        customAddress.setId(customerAddress.getId());
521
        return customAddress;
522
    }
523
 
524
    private CustomerAddress toCustomerAddress(int customerId, CustomAddress customAddress) {
525
        CustomerAddress customerAddress = new CustomerAddress();
526
        customerAddress.setCustomerId(customerId);
527
        customerAddress.setName(customAddress.getName());
528
        customerAddress.setLastName(customAddress.getLastName());
529
        customerAddress.setLine1(customAddress.getLine1());
530
        customerAddress.setLine2(customAddress.getLine2());
531
        customerAddress.setLandmark(customAddress.getLandmark());
532
        customerAddress.setCity(customAddress.getCity());
533
        customerAddress.setPinCode(customAddress.getPinCode());
534
        customerAddress.setState(customAddress.getState());
535
        customerAddress.setCountry(customAddress.getCountry());
536
        customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
537
 
538
        return customerAddress;
539
    }
540
 
541
 
542
    @RequestMapping(value = "/update-fofoOrder-addressId", method = RequestMethod.POST)
543
    public ResponseEntity<?> updateFofoOrderAddresId(HttpServletRequest request, @RequestParam(name = "orderId", defaultValue = "0") int orderId, @RequestParam(name = "addressId", defaultValue = "0") int addressId, Model model) throws Exception {
544
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
545
        fofoOrder.setCustomerAddressId(addressId);
546
        return responseSender.ok(true);
547
    }
548
 
34111 ranu 549
    @RequestMapping(value = "/downloadUpsellingReport", method = RequestMethod.GET)
550
    public ResponseEntity<?> downloadUpsellingReport(HttpServletRequest request,
551
                                                     @RequestParam(name = "startDate") LocalDateTime startDate,
552
                                                     @RequestParam(name = "endDate") LocalDateTime endDate, Model model)
553
            throws Exception {
33715 ranu 554
 
34111 ranu 555
        List<List<?>> rows = new ArrayList<>();
556
 
557
        LocalDate startLocalDate = startDate.toLocalDate();
558
        LocalDate endLocalDate = endDate.toLocalDate();
559
 
560
        List<UpsellingReportModel> upsellingReportModels = upSaleCallRepository.getUpsellingReport(startLocalDate, endLocalDate.plusDays(1));
561
 
562
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
563
 
564
        for (
565
                UpsellingReportModel report : upsellingReportModels) {
566
 
567
            rows.add(Arrays.asList(
568
                    report.getAgentEmail(),
34117 ranu 569
                    report.getPartnerName(),
34133 ranu 570
                    report.getPartnerMobile(),
34134 ranu 571
                    report.getState(),
34133 ranu 572
                    report.getPartnerName(),
34111 ranu 573
                    report.getOrderId(),
574
                    report.getCustomerNumber(),
575
                    report.getCallingDate(),
34131 ranu 576
                    report.getDisposition(),
577
                    report.getRemark(),
34111 ranu 578
                    report.getPaymentStatus(),
579
                    report.getInsuranceStatus(),
580
                    report.getPolicySoldAmount(),
581
                    report.getInvoiceNumber(),
582
                    report.getSerialNumber()
583
            ));
584
 
585
        }
586
 
587
 
588
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
34134 ranu 589
                .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 590
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, " Upselling Report");
591
 
592
        return responseEntity;
593
 
594
    }
595
 
596
    @RequestMapping(value = "/getUpsellingReport", method = RequestMethod.GET)
597
    public String getUpsellingReport(
598
            HttpServletRequest request,
599
            @RequestParam(name = "startDate") LocalDateTime startDate,
600
            @RequestParam(name = "endDate") LocalDateTime endDate, Model model
601
    ) throws Exception {
602
 
603
        LocalDate startLocalDate = startDate.toLocalDate();
604
        LocalDate endLocalDate = endDate.toLocalDate();
605
 
606
        List<UpsellingReportModel> upsellingReportModels = upSaleCallRepository.getUpsellingReport(startLocalDate, endLocalDate.plusDays(1));
607
 
608
        model.addAttribute("upsellingReportModels", upsellingReportModels);
609
 
610
        return "upselling-report";
611
    }
612
 
613
    @RequestMapping(value = "/upsellingCallingList", method = RequestMethod.GET)
614
    public String upsellingCallingList(
615
            HttpServletRequest request, Model model) throws Exception {
616
 
617
        return "upselling-calling-list";
618
    }
619
 
33715 ranu 620
}