Subversion Repositories SmartDukaan

Rev

Rev 33720 | Rev 34081 | 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
        LocalDateTime endDate = LocalDateTime.now();
155
 
156
 
157
        List<UpSaleAgentCollection> upSaleAgentCollections = upSaleAgentCollectionRepository.selectByAgentId(user.getId());
158
        double totalProductSaleAmount = upSaleAgentCollections.stream()
159
                .mapToDouble(UpSaleAgentCollection::getProductSaleAmount)
160
                .sum();
161
 
162
        try {
163
            // Fetch all rescheduled calls and filter them in-memory
164
            List<UpSaleCall> upSaleCalls = upSaleCallRepository.selectAllByDispostion(UpSaleCallStatus.RESCHEDULED);
165
            List<UpSaleCall> filteredUpSaleCalls = upSaleCalls.stream()
166
                    .filter(call -> call.getRescheduledTimestamp() != null && call.getRescheduledTimestamp().isBefore(endDate))
167
                    .collect(Collectors.toList());
168
 
169
 
170
            if (!filteredUpSaleCalls.isEmpty()) {
171
                for (UpSaleCall upSaleCall : filteredUpSaleCalls) {
172
                    FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(upSaleCall.getOriginalOrderId());
173
 
174
                    Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
175
                    if (fofoIds.contains(fofoOrder.getFofoId())) {
176
                        if (customer != null) {
177
                            upSaleCall.setStatus(UpSaleCallStatus.FETCHED);
178
                            upSaleCall.setRescheduledTimestamp(null);
179
 
180
                            LOGGER.info("Processing Rescheduled UpSaleCall {}", upSaleCall);
181
 
182
                            List<Map<String, Object>> itemDetails = new ArrayList<>();
183
                            List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
184
 
185
                            for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
186
                                Item item = itemRepository.selectById(fofoOrderItem.getItemId());
187
                                if (item.isSmartPhone()) {
188
                                    Map<String, List<MobileInsurancePlan>> plans = this.getPlans(fofoOrderItem.getSellingPrice(), item.getId());
189
                                    Map<String, Object> itemDetail = new HashMap<>();
190
                                    itemDetail.put("item", item);
191
                                    itemDetail.put("fofoOrderItem", fofoOrderItem);
192
                                    itemDetail.put("plans", plans);
193
                                    itemDetails.add(itemDetail);
194
                                }
195
                            }
196
 
197
                            Set<Integer> fofoOrderItemIds = fofoOrderItems.stream().map(FofoOrderItem::getId).collect(Collectors.toSet());
198
                            List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
199
 
200
                            Map<Integer, List<FofoLineItem>> fofoLineItemMap = fofoLineItems.stream()
201
                                    .collect(Collectors.groupingBy(FofoLineItem::getFofoOrderItemId));
202
 
203
                            List<UpSaleCallStatus> upSaleCallStatuses = new ArrayList<>(Arrays.asList(UpSaleCallStatus.values()));
204
 
205
                            model.addAttribute("upSaleCallStatuses", upSaleCallStatuses);
206
                            model.addAttribute("fofoOrder", fofoOrder);
207
                            model.addAttribute("customer", customer);
208
                            model.addAttribute("itemDetails", itemDetails);
209
                            model.addAttribute("fofoLineItemMap", fofoLineItemMap);
210
                            model.addAttribute("upsaleCallId", upSaleCall.getId());
211
                            model.addAttribute("stateNames",
212
                                    stateRepository.selectAll().stream().map(x -> x.getName()).collect(Collectors.toList()));
213
                            model.addAttribute("totalProductSaleAmount", totalProductSaleAmount);
214
 
215
                            return "up-sale-call";
216
                        }
217
                    }
218
                }
219
            }
220
        } catch (Exception e) {
221
            // If no rescheduled calls found, fall back to original logic
33720 ranu 222
            UpSaleOrder TMinus2UpsaleOrder = this.getTMinus2UpSaleOrderByFofoIds(fofoIds);
33715 ranu 223
 
33720 ranu 224
            TMinus2UpsaleOrder.setFetched(true);
33719 ranu 225
 
33720 ranu 226
            LOGGER.info("last48hourLatestOrder {}", TMinus2UpsaleOrder);
227
            if (TMinus2UpsaleOrder != null) {
228
                boolean exists = upSaleCallRepository.existsOrderId(TMinus2UpsaleOrder.getOrderId());
33715 ranu 229
                if (!exists) {
33720 ranu 230
                    FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(TMinus2UpsaleOrder.getOrderId());
33715 ranu 231
                    if (fofoIds.contains(fofoOrder.getFofoId())) {
232
                        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
233
                        if (customer != null) {
234
                            String mobile = customer.getMobileNumber();
33720 ranu 235
                            UpSaleCall upSaleCall = new UpSaleCall();
236
                            upSaleCall.setAgentId(user.getId());
237
                            upSaleCall.setMobile(mobile);
238
                            upSaleCall.setOriginalOrderId(fofoOrder.getId());
239
                            upSaleCall.setStatus(UpSaleCallStatus.FETCHED);
240
                            upSaleCall.setCreatedTimestamp(LocalDateTime.now());
241
                            upSaleCallRepository.persist(upSaleCall);
33715 ranu 242
 
33720 ranu 243
                            LOGGER.info("Processing UpSaleOrder {}", TMinus2UpsaleOrder);
33715 ranu 244
 
33720 ranu 245
                            List<Map<String, Object>> itemDetails = new ArrayList<>();
246
                            List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
33715 ranu 247
 
33720 ranu 248
                            for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
249
                                Item item = itemRepository.selectById(fofoOrderItem.getItemId());
250
                                if (item.isSmartPhone()) {
251
                                    float sellingPrice = tagListingRepository.selectByItemId(item.getId()).getSellingPrice();
252
                                    Map<String, List<MobileInsurancePlan>> plans = this.getPlans(fofoOrderItem.getSellingPrice(), item.getId());
253
                                    Map<String, Object> itemDetail = new HashMap<>();
254
                                    itemDetail.put("item", item);
255
                                    itemDetail.put("fofoOrderItem", fofoOrderItem);
256
                                    itemDetail.put("plans", plans);
257
                                    itemDetails.add(itemDetail);
33715 ranu 258
                                }
33720 ranu 259
                            }
33715 ranu 260
 
33720 ranu 261
                            Set<Integer> fofoOrderItemIds = fofoOrderItems.stream().map(FofoOrderItem::getId).collect(Collectors.toSet());
262
                            List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
33715 ranu 263
 
33720 ranu 264
                            Map<Integer, List<FofoLineItem>> fofoLineItemMap = fofoLineItems.stream()
265
                                    .collect(Collectors.groupingBy(FofoLineItem::getFofoOrderItemId));
33715 ranu 266
 
33720 ranu 267
                            List<UpSaleCallStatus> upSaleCallStatuses = new ArrayList<>(Arrays.asList(UpSaleCallStatus.values()));
33715 ranu 268
 
33720 ranu 269
                            model.addAttribute("upSaleCallStatuses", upSaleCallStatuses);
270
                            model.addAttribute("fofoOrder", fofoOrder);
271
                            model.addAttribute("customer", customer);
272
                            model.addAttribute("itemDetails", itemDetails);
273
                            model.addAttribute("fofoLineItemMap", fofoLineItemMap);
274
                            model.addAttribute("upsaleCallId", upSaleCall.getId());
275
                            model.addAttribute("stateNames",
276
                                    stateRepository.selectAll().stream().map(State::getName).collect(Collectors.toList()));
277
                            model.addAttribute("totalProductSaleAmount", totalProductSaleAmount);
33715 ranu 278
 
33720 ranu 279
                            return "up-sale-call";
33719 ranu 280
 
33715 ranu 281
                        }
282
                    }
283
                }
33720 ranu 284
            }
33719 ranu 285
 
33715 ranu 286
        }
287
 
288
 
289
        LOGGER.info("No valid UpSaleOrder found for up-sale call.");
290
        model.addAttribute("totalProductSaleAmount", totalProductSaleAmount);
291
        model.addAttribute("message", "No valid UpSaleOrder found.");
292
        return "up-sale-call";
293
    }
294
 
33720 ranu 295
    UpSaleOrder getTMinus2UpSaleOrderByFofoIds(Set<Integer> fofoIds) {
33719 ranu 296
        LocalDateTime startDateTime = LocalDateTime.now().minusDays(2); // 48 hours ago
33720 ranu 297
        return upSaleOrderRepository.getTMinus2UpSaleOrderByFofoIds(fofoIds, startDateTime);
33719 ranu 298
    }
299
 
33715 ranu 300
    @RequestMapping(value = "/generatePaymentLink", method = RequestMethod.POST)
301
    public ResponseEntity<String> generatePaymentLink(HttpServletRequest request, Model model, @RequestBody PaymentLinkDetailModel paymentLinkDetailModel) {
302
        double amount;
303
        LOGGER.info("paymnetlinkmodel {}", paymentLinkDetailModel);
304
        try {
305
            String paymentLink = razorpayPaymentService.createPaymentLink(paymentLinkDetailModel);
306
 
307
            LOGGER.info("paymentLink {}", paymentLink);
308
            String message = "Dear Customer,\n" +
309
                    "Here is a payment link for your recent purchased product.\n" +
310
                    "Please do your payment with this link\n" +
311
                    paymentLink + "\n" +
312
                    "Team SmartDukaan";
313
            LOGGER.info("message- {}", message);
314
            notificationService.sendPaymentWhatsappMessage(paymentLinkDetailModel.getMobile(), message);
33968 ranu 315
//            notificationService.sendPaymentWhatsappMessage("7082253510", message);
33715 ranu 316
 
317
//            model.addAttribute("message", "Payment link generated and sent successfully!");
318
            return responseSender.ok(true);
319
        } catch (Exception e) {
320
//            model.addAttribute("message", "Failed to generate payment link: " + e.getMessage());
321
            return responseSender.ok(false);
322
        }
323
 
324
 
325
    }
326
 
327
    private Map<String, List<MobileInsurancePlan>> getPlans(float sellingPrice, int itemId)
328
            throws ProfitMandiBusinessException {
329
        try {
330
            Map<String, List<MobileInsurancePlan>> productDurationPlans = new HashMap<>();
331
            productDurationPlans = insuranceService.getAllPlans(itemId,
332
                    sellingPrice, false);
333
 
334
            return productDurationPlans;
335
        } catch (Exception e) {
336
            LOGGER.info(e, e);
337
            throw new ProfitMandiBusinessException("Fetch Insurance Plans", "Insurance",
338
                    "Could not fetch insurance Plans");
339
        }
340
 
341
    }
342
 
343
    @RequestMapping(value = "/upsell/clickToCall/{toMobile}/{upsellCallId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
344
    public ResponseEntity<?> upsellClickToCall(HttpServletRequest request, @PathVariable String toMobile, @PathVariable int upsellCallId) throws Exception {
345
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
346
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
347
        kommunoService.upsellClickToCallKommuno(toMobile, loginDetails.getEmailId(), upsellCallId);
348
        return responseSender.ok(true);
349
    }
350
 
351
    @RequestMapping(value = "/upsell/disposition/{upsellCallId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
352
    public ResponseEntity<?> upsellDisposition(HttpServletRequest request,
353
                                               @PathVariable String upsellCallId,
354
                                               @RequestParam(name = "disposition", required = false) UpSaleCallStatus disposition,
355
                                               @RequestParam(name = "scheduleTime", required = false) String scheduleTime) throws Exception {
356
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
357
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
358
 
359
        UpsellCallDetail upsellCallDetail = upsellCallDetailRepository.selectByUpSellCallId(upsellCallId);
360
        LOGGER.info("upsellCallDetail {}", upsellCallDetail);
361
        upsellCallDetail.setAgentId(user.getEmailId());
362
        upsellCallDetail.setDisposition(disposition);
363
        upsellCallDetail.setRemark(disposition.getValue());
364
 
365
 
366
        if (scheduleTime != null && !scheduleTime.isEmpty()) {
367
            UpSaleCall upSaleCall = upSaleCallRepository.selectById(Integer.parseInt(upsellCallId));
368
            Instant instant = Instant.parse(scheduleTime);
369
            LocalDateTime scheduledDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
370
            upSaleCall.setRescheduledTimestamp(scheduledDateTime);
371
            upSaleCall.setStatus(disposition);
372
        }
373
 
374
        // Generate session id with 16 digits as kommuno service
375
        Long newId = (long) upsellCallDetail.getId();
33968 ranu 376
        String sessionId = String.format("%014d", newId);
33715 ranu 377
        upsellCallDetail.setDiallerSessionId(sessionId);
378
 
379
//        fill diposition on kommuno service
380
        kommunoService.upsellFillDispositionWithKommuno(disposition.getValue(), sessionId);
381
 
382
        return responseSender.ok(true);
383
    }
384
 
385
    @RequestMapping(value = "/generatePlanDetail", method = RequestMethod.POST)
386
    public String generatePlanDetail(HttpServletRequest request, Model model, @RequestBody PaymentLinkDetailModel paymentLinkDetailModel) throws Exception {
387
        FofoOrderItem foi = fofoOrderItemRepository.selectById(Integer.parseInt(paymentLinkDetailModel.getOrderItemId()));
388
 
389
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(Integer.parseInt(paymentLinkDetailModel.getOrderId()));
390
        float deviceSellingPrice = tagListingRepository.selectByItemId(foi.getItemId()).getSellingPrice();
391
        MobileInsurancePlan mobileInsurancePlan = insuranceService.getPlanById(paymentLinkDetailModel.getPlanId(), foi.getSellingPrice(), paymentLinkDetailModel.getPlanName());
392
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
393
 
394
        model.addAttribute("fofoOrder", fofoOrder);
395
        model.addAttribute("fofoOrderItem", foi);
396
        model.addAttribute("deviceSellinnPrice", deviceSellingPrice);
397
        model.addAttribute("mobileInsurancePlan", mobileInsurancePlan);
398
        model.addAttribute("serialNumber", paymentLinkDetailModel.getSerialNumber());
399
        model.addAttribute("customer", customer);
400
        model.addAttribute("customerAddress", customer.getCustomerAddress());
401
        return "upsale-create-insurance-model";
402
    }
403
 
404
    @RequestMapping(value = "/create-insurance", method = RequestMethod.POST)
405
    public ResponseEntity<?> createInsurance(HttpServletRequest request, @RequestBody InsuranceModel insuranceModel, Model model) throws Exception {
406
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
407
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
408
        LOGGER.info("request at uri {} body {}", request.getRequestURI(), insuranceModel);
409
        FofoOrderItem foi = fofoOrderItemRepository.selectById(insuranceModel.getFofoOrderItemId());
410
        float deviceSellingPrice = tagListingRepository.selectByItemId(foi.getItemId()).getSellingPrice();
411
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
412
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoOrder.getFofoId());
413
 
414
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
415
        LOGGER.info("customer {}", customer);
416
        LOGGER.info("customerAddress {}", customer.getCustomerAddress());
417
        if (fofoOrder.getCustomerAddressId() == 0) {
418
            throw new Exception("Please select a address or add new address");
419
        }
420
        customer.setDob(insuranceModel.getDob());
421
 
422
        fofoOrder.setDateOfBirth(insuranceModel.getDob());
423
        insuranceModel.setBrand(foi.getBrand());
424
        insuranceModel.setMfgDate(insuranceModel.getWmfgDate().atStartOfDay());
425
        insuranceModel.setColor(foi.getColor());
426
        insuranceModel.setModelName(String.join(" ", foi.getModelName(), foi.getModelNumber()));
427
        insuranceModel.setDeviceSellingPrice(deviceSellingPrice);
428
 
429
        InsurancePolicy insurancePolicy = insuranceService.createInsurance(fofoOrder, insuranceModel, true);
430
        String documentNumber = orderService.getInvoiceNumber(fofoOrder.getFofoId(), fs.getCode());
431
        insurancePolicy.setInvoiceNumber(documentNumber);
432
        insurancePolicy.setDeviceInvoiceNumber(fofoOrder.getInvoiceNumber());
433
 
434
        FofoOrder fo = this.createAndGetFofoOrder(customer.getId(), fofoOrder.getCustomerGstNumber(), fofoOrder.getFofoId(), insurancePolicy.getInvoiceNumber(), insuranceModel.getInsuranceAmount(), fofoOrder.getCustomerAddressId());
435
 
436
        this.createPaymentOptions(fo, insuranceModel.getPaymentOptions());
437
 
438
//        agent collection persistance
439
 
440
        UpSaleAgentCollection upSaleAgentCollection = new UpSaleAgentCollection();
441
        upSaleAgentCollection.setAgentId(user.getId());
442
        upSaleAgentCollection.setOrderId(fofoOrder.getId());
443
        upSaleAgentCollection.setProductId(insuranceModel.getInsuranceId());
444
        upSaleAgentCollection.setInsurancePolicyId(insurancePolicy.getId());
445
        upSaleAgentCollection.setProductSaleAmount(insurancePolicy.getSaleAmount());
446
//        if insurance plan is selling than is insurance will be true
447
        upSaleAgentCollection.setInsurance(true);
448
        upSaleAgentCollection.setCreatedTimestamp(LocalDateTime.now());
449
        upSaleAgentCollectionRepository.persist(upSaleAgentCollection);
450
 
451
        return responseSender.ok(true);
452
    }
453
 
454
    private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions) throws ProfitMandiBusinessException {
455
        for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
456
            if (customPaymentOption.getAmount() > 0) {
457
                PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
458
                paymentOptionTransaction.setReferenceId(fofoOrder.getId());
459
                paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
460
                paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.INSURANCE);
461
                paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
462
                paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
463
                paymentOptionTransactionRepository.persist(paymentOptionTransaction);
464
            }
465
        }
466
    }
467
 
468
    private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, String documentNumber, float totalAmount, int customerAddressId) {
469
        FofoOrder fofoOrder = new FofoOrder();
470
        fofoOrder.setCustomerGstNumber(customerGstNumber);
471
        fofoOrder.setCustomerId(customerId);
472
        fofoOrder.setFofoId(fofoId);
473
        fofoOrder.setInvoiceNumber(documentNumber);
474
        fofoOrder.setTotalAmount(totalAmount);
475
        fofoOrder.setCustomerAddressId(customerAddressId);
476
        fofoOrderRepository.persist(fofoOrder);
477
        return fofoOrder;
478
    }
479
 
480
    @RequestMapping(value = "/customer/addaddress", method = RequestMethod.POST)
481
    public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestParam int customerId,
482
                                        @RequestBody CustomAddress customAddress) {
483
        CustomerAddress customerAddress = this.toCustomerAddress(customerId, customAddress);
484
        customerAddressRepository.persist(customerAddress);
485
        return responseSender.ok(this.toCustomAddress(customerAddress));
486
 
487
    }
488
 
489
    private CustomAddress toCustomAddress(CustomerAddress customerAddress) {
490
        CustomAddress customAddress = new CustomAddress();
491
        customAddress.setCity(customerAddress.getCity());
492
        customAddress.setCountry(customerAddress.getCountry());
493
        customAddress.setLandmark(customerAddress.getLandmark());
494
        customAddress.setLine1(customerAddress.getLine1());
495
        customAddress.setLine2(customerAddress.getLine2());
496
        customAddress.setName(customerAddress.getName());
497
        customAddress.setLastName(customerAddress.getLastName());
498
        customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
499
        customAddress.setPinCode(customerAddress.getPinCode());
500
        customAddress.setState(customerAddress.getState());
501
        customAddress.setId(customerAddress.getId());
502
        return customAddress;
503
    }
504
 
505
    private CustomerAddress toCustomerAddress(int customerId, CustomAddress customAddress) {
506
        CustomerAddress customerAddress = new CustomerAddress();
507
        customerAddress.setCustomerId(customerId);
508
        customerAddress.setName(customAddress.getName());
509
        customerAddress.setLastName(customAddress.getLastName());
510
        customerAddress.setLine1(customAddress.getLine1());
511
        customerAddress.setLine2(customAddress.getLine2());
512
        customerAddress.setLandmark(customAddress.getLandmark());
513
        customerAddress.setCity(customAddress.getCity());
514
        customerAddress.setPinCode(customAddress.getPinCode());
515
        customerAddress.setState(customAddress.getState());
516
        customerAddress.setCountry(customAddress.getCountry());
517
        customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
518
 
519
        return customerAddress;
520
    }
521
 
522
 
523
    @RequestMapping(value = "/update-fofoOrder-addressId", method = RequestMethod.POST)
524
    public ResponseEntity<?> updateFofoOrderAddresId(HttpServletRequest request, @RequestParam(name = "orderId", defaultValue = "0") int orderId, @RequestParam(name = "addressId", defaultValue = "0") int addressId, Model model) throws Exception {
525
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
526
        fofoOrder.setCustomerAddressId(addressId);
527
        return responseSender.ok(true);
528
    }
529
 
530
 
531
}