Subversion Repositories SmartDukaan

Rev

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