Subversion Repositories SmartDukaan

Rev

Rev 34111 | Rev 34131 | Go to most recent revision | 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;
35
import com.spice.profitmandi.service.integrations.kommuno.KommunoService;
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
111
    private KommunoService kommunoService;
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());
364
        kommunoService.upsellClickToCallKommuno(toMobile, loginDetails.getEmailId(), upsellCallId);
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
397
        kommunoService.upsellFillDispositionWithKommuno(disposition.getValue(), sessionId);
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());
443
        insuranceModel.setModelName(String.join(" ", foi.getModelName(), foi.getModelNumber()));
444
        insuranceModel.setDeviceSellingPrice(deviceSellingPrice);
445
 
446
        InsurancePolicy insurancePolicy = insuranceService.createInsurance(fofoOrder, insuranceModel, true);
447
        String documentNumber = orderService.getInvoiceNumber(fofoOrder.getFofoId(), fs.getCode());
448
        insurancePolicy.setInvoiceNumber(documentNumber);
449
        insurancePolicy.setDeviceInvoiceNumber(fofoOrder.getInvoiceNumber());
450
 
451
        FofoOrder fo = this.createAndGetFofoOrder(customer.getId(), fofoOrder.getCustomerGstNumber(), fofoOrder.getFofoId(), insurancePolicy.getInvoiceNumber(), insuranceModel.getInsuranceAmount(), fofoOrder.getCustomerAddressId());
452
 
453
        this.createPaymentOptions(fo, insuranceModel.getPaymentOptions());
454
 
455
//        agent collection persistance
456
 
457
        UpSaleAgentCollection upSaleAgentCollection = new UpSaleAgentCollection();
458
        upSaleAgentCollection.setAgentId(user.getId());
459
        upSaleAgentCollection.setOrderId(fofoOrder.getId());
460
        upSaleAgentCollection.setProductId(insuranceModel.getInsuranceId());
461
        upSaleAgentCollection.setInsurancePolicyId(insurancePolicy.getId());
462
        upSaleAgentCollection.setProductSaleAmount(insurancePolicy.getSaleAmount());
463
//        if insurance plan is selling than is insurance will be true
464
        upSaleAgentCollection.setInsurance(true);
465
        upSaleAgentCollection.setCreatedTimestamp(LocalDateTime.now());
466
        upSaleAgentCollectionRepository.persist(upSaleAgentCollection);
467
 
468
        return responseSender.ok(true);
469
    }
470
 
471
    private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions) throws ProfitMandiBusinessException {
472
        for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
473
            if (customPaymentOption.getAmount() > 0) {
474
                PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
475
                paymentOptionTransaction.setReferenceId(fofoOrder.getId());
476
                paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
477
                paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.INSURANCE);
478
                paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
479
                paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
480
                paymentOptionTransactionRepository.persist(paymentOptionTransaction);
481
            }
482
        }
483
    }
484
 
485
    private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, String documentNumber, float totalAmount, int customerAddressId) {
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);
493
        fofoOrderRepository.persist(fofoOrder);
494
        return fofoOrder;
495
    }
496
 
497
    @RequestMapping(value = "/customer/addaddress", method = RequestMethod.POST)
498
    public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestParam int customerId,
499
                                        @RequestBody CustomAddress customAddress) {
500
        CustomerAddress customerAddress = this.toCustomerAddress(customerId, customAddress);
501
        customerAddressRepository.persist(customerAddress);
502
        return responseSender.ok(this.toCustomAddress(customerAddress));
503
 
504
    }
505
 
506
    private CustomAddress toCustomAddress(CustomerAddress customerAddress) {
507
        CustomAddress customAddress = new CustomAddress();
508
        customAddress.setCity(customerAddress.getCity());
509
        customAddress.setCountry(customerAddress.getCountry());
510
        customAddress.setLandmark(customerAddress.getLandmark());
511
        customAddress.setLine1(customerAddress.getLine1());
512
        customAddress.setLine2(customerAddress.getLine2());
513
        customAddress.setName(customerAddress.getName());
514
        customAddress.setLastName(customerAddress.getLastName());
515
        customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
516
        customAddress.setPinCode(customerAddress.getPinCode());
517
        customAddress.setState(customerAddress.getState());
518
        customAddress.setId(customerAddress.getId());
519
        return customAddress;
520
    }
521
 
522
    private CustomerAddress toCustomerAddress(int customerId, CustomAddress customAddress) {
523
        CustomerAddress customerAddress = new CustomerAddress();
524
        customerAddress.setCustomerId(customerId);
525
        customerAddress.setName(customAddress.getName());
526
        customerAddress.setLastName(customAddress.getLastName());
527
        customerAddress.setLine1(customAddress.getLine1());
528
        customerAddress.setLine2(customAddress.getLine2());
529
        customerAddress.setLandmark(customAddress.getLandmark());
530
        customerAddress.setCity(customAddress.getCity());
531
        customerAddress.setPinCode(customAddress.getPinCode());
532
        customerAddress.setState(customAddress.getState());
533
        customerAddress.setCountry(customAddress.getCountry());
534
        customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
535
 
536
        return customerAddress;
537
    }
538
 
539
 
540
    @RequestMapping(value = "/update-fofoOrder-addressId", method = RequestMethod.POST)
541
    public ResponseEntity<?> updateFofoOrderAddresId(HttpServletRequest request, @RequestParam(name = "orderId", defaultValue = "0") int orderId, @RequestParam(name = "addressId", defaultValue = "0") int addressId, Model model) throws Exception {
542
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
543
        fofoOrder.setCustomerAddressId(addressId);
544
        return responseSender.ok(true);
545
    }
546
 
34111 ranu 547
    @RequestMapping(value = "/downloadUpsellingReport", method = RequestMethod.GET)
548
    public ResponseEntity<?> downloadUpsellingReport(HttpServletRequest request,
549
                                                     @RequestParam(name = "startDate") LocalDateTime startDate,
550
                                                     @RequestParam(name = "endDate") LocalDateTime endDate, Model model)
551
            throws Exception {
33715 ranu 552
 
34111 ranu 553
        List<List<?>> rows = new ArrayList<>();
554
 
555
        LocalDate startLocalDate = startDate.toLocalDate();
556
        LocalDate endLocalDate = endDate.toLocalDate();
557
 
558
        List<UpsellingReportModel> upsellingReportModels = upSaleCallRepository.getUpsellingReport(startLocalDate, endLocalDate.plusDays(1));
559
 
560
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
561
 
562
        for (
563
                UpsellingReportModel report : upsellingReportModels) {
564
 
565
            rows.add(Arrays.asList(
566
                    report.getAgentEmail(),
34117 ranu 567
                    report.getPartnerName(),
34111 ranu 568
                    report.getOrderId(),
569
                    report.getCustomerNumber(),
570
                    report.getCallingDate(),
571
                    report.getPaymentStatus(),
572
                    report.getInsuranceStatus(),
573
                    report.getPolicySoldAmount(),
574
                    report.getInvoiceNumber(),
575
                    report.getSerialNumber()
576
            ));
577
 
578
        }
579
 
580
 
581
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
34117 ranu 582
                .getCSVByteStream(Arrays.asList("Agent Email", "Partner Name", "Order Id", "Customer Mobile Number", "Calling Date", "Payment Status", "Insurance Status", "Policy Sold Amount", "Invoice Number", "Serial Number"), rows);
34111 ranu 583
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, " Upselling Report");
584
 
585
        return responseEntity;
586
 
587
    }
588
 
589
    @RequestMapping(value = "/getUpsellingReport", method = RequestMethod.GET)
590
    public String getUpsellingReport(
591
            HttpServletRequest request,
592
            @RequestParam(name = "startDate") LocalDateTime startDate,
593
            @RequestParam(name = "endDate") LocalDateTime endDate, Model model
594
    ) throws Exception {
595
 
596
        LocalDate startLocalDate = startDate.toLocalDate();
597
        LocalDate endLocalDate = endDate.toLocalDate();
598
 
599
        List<UpsellingReportModel> upsellingReportModels = upSaleCallRepository.getUpsellingReport(startLocalDate, endLocalDate.plusDays(1));
600
 
601
        model.addAttribute("upsellingReportModels", upsellingReportModels);
602
 
603
        return "upselling-report";
604
    }
605
 
606
    @RequestMapping(value = "/upsellingCallingList", method = RequestMethod.GET)
607
    public String upsellingCallingList(
608
            HttpServletRequest request, Model model) throws Exception {
609
 
610
        return "upselling-calling-list";
611
    }
612
 
33715 ranu 613
}