Subversion Repositories SmartDukaan

Rev

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