Subversion Repositories SmartDukaan

Rev

Rev 33717 | Rev 33720 | 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
222
 
33719 ranu 223
            UpSaleOrder last48hourLatestOrder = this.getOldestUpSaleOrderFromLast48Hours(fofoIds);
224
 
225
            last48hourLatestOrder.setFetched(true);
226
 
227
            LOGGER.info("last48hourLatestOrder {}", last48hourLatestOrder);
228
 
229
            boolean exists = upSaleCallRepository.existsOrderId(last48hourLatestOrder.getOrderId());
33715 ranu 230
                if (!exists) {
33719 ranu 231
                    FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(last48hourLatestOrder.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();
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);
243
 
33719 ranu 244
                            LOGGER.info("Processing UpSaleOrder {}", last48hourLatestOrder);
33715 ranu 245
 
246
                                List<Map<String, Object>> itemDetails = new ArrayList<>();
247
                                List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(fofoOrder.getId());
248
 
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);
259
                                    }
260
                                }
261
 
262
                                Set<Integer> fofoOrderItemIds = fofoOrderItems.stream().map(FofoOrderItem::getId).collect(Collectors.toSet());
263
                                List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
264
 
265
                                Map<Integer, List<FofoLineItem>> fofoLineItemMap = fofoLineItems.stream()
266
                                        .collect(Collectors.groupingBy(FofoLineItem::getFofoOrderItemId));
267
 
268
                                List<UpSaleCallStatus> upSaleCallStatuses = new ArrayList<>(Arrays.asList(UpSaleCallStatus.values()));
269
 
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);
279
 
280
                                return "up-sale-call";
33719 ranu 281
 
33715 ranu 282
                        }
283
                    }
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
 
33719 ranu 295
    UpSaleOrder getOldestUpSaleOrderFromLast48Hours(Set<Integer> fofoIds) {
296
        LocalDateTime startDateTime = LocalDateTime.now().minusDays(2); // 48 hours ago
297
        return upSaleOrderRepository.findOldestUpSaleOrderByFofoIdsLast48Hours(fofoIds, startDateTime);
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);
315
 
316
//            model.addAttribute("message", "Payment link generated and sent successfully!");
317
            return responseSender.ok(true);
318
        } catch (Exception e) {
319
//            model.addAttribute("message", "Failed to generate payment link: " + e.getMessage());
320
            return responseSender.ok(false);
321
        }
322
 
323
 
324
    }
325
 
326
    private Map<String, List<MobileInsurancePlan>> getPlans(float sellingPrice, int itemId)
327
            throws ProfitMandiBusinessException {
328
        try {
329
            Map<String, List<MobileInsurancePlan>> productDurationPlans = new HashMap<>();
330
            productDurationPlans = insuranceService.getAllPlans(itemId,
331
                    sellingPrice, false);
332
 
333
            return productDurationPlans;
334
        } catch (Exception e) {
335
            LOGGER.info(e, e);
336
            throw new ProfitMandiBusinessException("Fetch Insurance Plans", "Insurance",
337
                    "Could not fetch insurance Plans");
338
        }
339
 
340
    }
341
 
342
    @RequestMapping(value = "/upsell/clickToCall/{toMobile}/{upsellCallId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
343
    public ResponseEntity<?> upsellClickToCall(HttpServletRequest request, @PathVariable String toMobile, @PathVariable int upsellCallId) throws Exception {
344
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
345
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
346
        kommunoService.upsellClickToCallKommuno(toMobile, loginDetails.getEmailId(), upsellCallId);
347
        return responseSender.ok(true);
348
    }
349
 
350
    @RequestMapping(value = "/upsell/disposition/{upsellCallId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
351
    public ResponseEntity<?> upsellDisposition(HttpServletRequest request,
352
                                               @PathVariable String upsellCallId,
353
                                               @RequestParam(name = "disposition", required = false) UpSaleCallStatus disposition,
354
                                               @RequestParam(name = "scheduleTime", required = false) String scheduleTime) throws Exception {
355
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
356
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
357
 
358
        UpsellCallDetail upsellCallDetail = upsellCallDetailRepository.selectByUpSellCallId(upsellCallId);
359
        LOGGER.info("upsellCallDetail {}", upsellCallDetail);
360
        upsellCallDetail.setAgentId(user.getEmailId());
361
        upsellCallDetail.setDisposition(disposition);
362
        upsellCallDetail.setRemark(disposition.getValue());
363
 
364
 
365
        if (scheduleTime != null && !scheduleTime.isEmpty()) {
366
            UpSaleCall upSaleCall = upSaleCallRepository.selectById(Integer.parseInt(upsellCallId));
367
            Instant instant = Instant.parse(scheduleTime);
368
            LocalDateTime scheduledDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
369
            upSaleCall.setRescheduledTimestamp(scheduledDateTime);
370
            upSaleCall.setStatus(disposition);
371
        }
372
 
373
        // Generate session id with 16 digits as kommuno service
374
        Long newId = (long) upsellCallDetail.getId();
375
        String sessionId = String.format("%015d", newId);
376
        upsellCallDetail.setDiallerSessionId(sessionId);
377
 
378
//        fill diposition on kommuno service
379
        kommunoService.upsellFillDispositionWithKommuno(disposition.getValue(), sessionId);
380
 
381
        return responseSender.ok(true);
382
    }
383
 
384
    @RequestMapping(value = "/generatePlanDetail", method = RequestMethod.POST)
385
    public String generatePlanDetail(HttpServletRequest request, Model model, @RequestBody PaymentLinkDetailModel paymentLinkDetailModel) throws Exception {
386
        FofoOrderItem foi = fofoOrderItemRepository.selectById(Integer.parseInt(paymentLinkDetailModel.getOrderItemId()));
387
 
388
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(Integer.parseInt(paymentLinkDetailModel.getOrderId()));
389
        float deviceSellingPrice = tagListingRepository.selectByItemId(foi.getItemId()).getSellingPrice();
390
        MobileInsurancePlan mobileInsurancePlan = insuranceService.getPlanById(paymentLinkDetailModel.getPlanId(), foi.getSellingPrice(), paymentLinkDetailModel.getPlanName());
391
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
392
 
393
        model.addAttribute("fofoOrder", fofoOrder);
394
        model.addAttribute("fofoOrderItem", foi);
395
        model.addAttribute("deviceSellinnPrice", deviceSellingPrice);
396
        model.addAttribute("mobileInsurancePlan", mobileInsurancePlan);
397
        model.addAttribute("serialNumber", paymentLinkDetailModel.getSerialNumber());
398
        model.addAttribute("customer", customer);
399
        model.addAttribute("customerAddress", customer.getCustomerAddress());
400
        return "upsale-create-insurance-model";
401
    }
402
 
403
    @RequestMapping(value = "/create-insurance", method = RequestMethod.POST)
404
    public ResponseEntity<?> createInsurance(HttpServletRequest request, @RequestBody InsuranceModel insuranceModel, Model model) throws Exception {
405
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
406
        AuthUser user = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
407
        LOGGER.info("request at uri {} body {}", request.getRequestURI(), insuranceModel);
408
        FofoOrderItem foi = fofoOrderItemRepository.selectById(insuranceModel.getFofoOrderItemId());
409
        float deviceSellingPrice = tagListingRepository.selectByItemId(foi.getItemId()).getSellingPrice();
410
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
411
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoOrder.getFofoId());
412
 
413
        Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
414
        LOGGER.info("customer {}", customer);
415
        LOGGER.info("customerAddress {}", customer.getCustomerAddress());
416
        if (fofoOrder.getCustomerAddressId() == 0) {
417
            throw new Exception("Please select a address or add new address");
418
        }
419
        customer.setDob(insuranceModel.getDob());
420
 
421
        fofoOrder.setDateOfBirth(insuranceModel.getDob());
422
        insuranceModel.setBrand(foi.getBrand());
423
        insuranceModel.setMfgDate(insuranceModel.getWmfgDate().atStartOfDay());
424
        insuranceModel.setColor(foi.getColor());
425
        insuranceModel.setModelName(String.join(" ", foi.getModelName(), foi.getModelNumber()));
426
        insuranceModel.setDeviceSellingPrice(deviceSellingPrice);
427
 
428
        InsurancePolicy insurancePolicy = insuranceService.createInsurance(fofoOrder, insuranceModel, true);
429
        String documentNumber = orderService.getInvoiceNumber(fofoOrder.getFofoId(), fs.getCode());
430
        insurancePolicy.setInvoiceNumber(documentNumber);
431
        insurancePolicy.setDeviceInvoiceNumber(fofoOrder.getInvoiceNumber());
432
 
433
        FofoOrder fo = this.createAndGetFofoOrder(customer.getId(), fofoOrder.getCustomerGstNumber(), fofoOrder.getFofoId(), insurancePolicy.getInvoiceNumber(), insuranceModel.getInsuranceAmount(), fofoOrder.getCustomerAddressId());
434
 
435
        this.createPaymentOptions(fo, insuranceModel.getPaymentOptions());
436
 
437
//        agent collection persistance
438
 
439
        UpSaleAgentCollection upSaleAgentCollection = new UpSaleAgentCollection();
440
        upSaleAgentCollection.setAgentId(user.getId());
441
        upSaleAgentCollection.setOrderId(fofoOrder.getId());
442
        upSaleAgentCollection.setProductId(insuranceModel.getInsuranceId());
443
        upSaleAgentCollection.setInsurancePolicyId(insurancePolicy.getId());
444
        upSaleAgentCollection.setProductSaleAmount(insurancePolicy.getSaleAmount());
445
//        if insurance plan is selling than is insurance will be true
446
        upSaleAgentCollection.setInsurance(true);
447
        upSaleAgentCollection.setCreatedTimestamp(LocalDateTime.now());
448
        upSaleAgentCollectionRepository.persist(upSaleAgentCollection);
449
 
450
        return responseSender.ok(true);
451
    }
452
 
453
    private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions) throws ProfitMandiBusinessException {
454
        for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
455
            if (customPaymentOption.getAmount() > 0) {
456
                PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
457
                paymentOptionTransaction.setReferenceId(fofoOrder.getId());
458
                paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
459
                paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.INSURANCE);
460
                paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
461
                paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
462
                paymentOptionTransactionRepository.persist(paymentOptionTransaction);
463
            }
464
        }
465
    }
466
 
467
    private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, String documentNumber, float totalAmount, int customerAddressId) {
468
        FofoOrder fofoOrder = new FofoOrder();
469
        fofoOrder.setCustomerGstNumber(customerGstNumber);
470
        fofoOrder.setCustomerId(customerId);
471
        fofoOrder.setFofoId(fofoId);
472
        fofoOrder.setInvoiceNumber(documentNumber);
473
        fofoOrder.setTotalAmount(totalAmount);
474
        fofoOrder.setCustomerAddressId(customerAddressId);
475
        fofoOrderRepository.persist(fofoOrder);
476
        return fofoOrder;
477
    }
478
 
479
    @RequestMapping(value = "/customer/addaddress", method = RequestMethod.POST)
480
    public ResponseEntity<?> addAddress(HttpServletRequest request, @RequestParam int customerId,
481
                                        @RequestBody CustomAddress customAddress) {
482
        CustomerAddress customerAddress = this.toCustomerAddress(customerId, customAddress);
483
        customerAddressRepository.persist(customerAddress);
484
        return responseSender.ok(this.toCustomAddress(customerAddress));
485
 
486
    }
487
 
488
    private CustomAddress toCustomAddress(CustomerAddress customerAddress) {
489
        CustomAddress customAddress = new CustomAddress();
490
        customAddress.setCity(customerAddress.getCity());
491
        customAddress.setCountry(customerAddress.getCountry());
492
        customAddress.setLandmark(customerAddress.getLandmark());
493
        customAddress.setLine1(customerAddress.getLine1());
494
        customAddress.setLine2(customerAddress.getLine2());
495
        customAddress.setName(customerAddress.getName());
496
        customAddress.setLastName(customerAddress.getLastName());
497
        customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
498
        customAddress.setPinCode(customerAddress.getPinCode());
499
        customAddress.setState(customerAddress.getState());
500
        customAddress.setId(customerAddress.getId());
501
        return customAddress;
502
    }
503
 
504
    private CustomerAddress toCustomerAddress(int customerId, CustomAddress customAddress) {
505
        CustomerAddress customerAddress = new CustomerAddress();
506
        customerAddress.setCustomerId(customerId);
507
        customerAddress.setName(customAddress.getName());
508
        customerAddress.setLastName(customAddress.getLastName());
509
        customerAddress.setLine1(customAddress.getLine1());
510
        customerAddress.setLine2(customAddress.getLine2());
511
        customerAddress.setLandmark(customAddress.getLandmark());
512
        customerAddress.setCity(customAddress.getCity());
513
        customerAddress.setPinCode(customAddress.getPinCode());
514
        customerAddress.setState(customAddress.getState());
515
        customerAddress.setCountry(customAddress.getCountry());
516
        customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
517
 
518
        return customerAddress;
519
    }
520
 
521
 
522
    @RequestMapping(value = "/update-fofoOrder-addressId", method = RequestMethod.POST)
523
    public ResponseEntity<?> updateFofoOrderAddresId(HttpServletRequest request, @RequestParam(name = "orderId", defaultValue = "0") int orderId, @RequestParam(name = "addressId", defaultValue = "0") int addressId, Model model) throws Exception {
524
        FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
525
        fofoOrder.setCustomerAddressId(addressId);
526
        return responseSender.ok(true);
527
    }
528
 
529
 
530
}