Subversion Repositories SmartDukaan

Rev

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