Subversion Repositories SmartDukaan

Rev

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