Subversion Repositories SmartDukaan

Rev

Rev 33809 | Rev 33815 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
23612 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.spice.profitmandi.common.enumuration.ReporticoProject;
4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
33102 tejus.loha 5
import com.spice.profitmandi.common.model.CustomRetailer;
28106 amit.gupta 6
import com.spice.profitmandi.common.model.ReporticoUrlInfo;
23612 amit.gupta 7
import com.spice.profitmandi.common.services.ReporticoService;
30162 manish 8
import com.spice.profitmandi.common.util.FileUtil;
33102 tejus.loha 9
import com.spice.profitmandi.common.util.FormattingUtils;
26298 tejbeer 10
import com.spice.profitmandi.dao.entity.auth.AuthUser;
33102 tejus.loha 11
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
12
import com.spice.profitmandi.dao.entity.fofo.PendingOrderItem;
33775 ranu 13
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
14
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
33102 tejus.loha 15
import com.spice.profitmandi.dao.model.*;
26298 tejbeer 16
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
17
import com.spice.profitmandi.dao.repository.cs.CsService;
28106 amit.gupta 18
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
23784 ashik.ali 19
import com.spice.profitmandi.dao.repository.dtr.RoleRepository;
33102 tejus.loha 20
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
21
import com.spice.profitmandi.dao.repository.fofo.PendingOrderItemRepository;
22
import com.spice.profitmandi.dao.repository.fofo.PendingOrderService;
33809 ranu 23
import com.spice.profitmandi.dao.repository.transaction.*;
23798 amit.gupta 24
import com.spice.profitmandi.service.authentication.RoleManager;
30162 manish 25
import com.spice.profitmandi.service.order.OrderService;
33775 ranu 26
import com.spice.profitmandi.service.transaction.TransactionService;
33102 tejus.loha 27
import com.spice.profitmandi.service.user.RetailerService;
33775 ranu 28
import com.spice.profitmandi.service.wallet.WalletService;
23612 amit.gupta 29
import com.spice.profitmandi.web.model.LoginDetails;
30
import com.spice.profitmandi.web.util.CookiesProcessor;
33775 ranu 31
import in.shop2020.model.v1.order.WalletReferenceType;
33092 tejus.loha 32
import org.apache.http.HttpResponse;
33
import org.apache.logging.log4j.LogManager;
34
import org.apache.logging.log4j.Logger;
35
import org.springframework.beans.factory.annotation.Autowired;
36
import org.springframework.core.io.InputStreamResource;
37
import org.springframework.http.HttpHeaders;
38
import org.springframework.http.HttpStatus;
39
import org.springframework.http.ResponseEntity;
40
import org.springframework.stereotype.Controller;
41
import org.springframework.transaction.annotation.Transactional;
42
import org.springframework.ui.Model;
43
import org.springframework.web.bind.annotation.*;
23612 amit.gupta 44
 
33092 tejus.loha 45
import javax.servlet.http.HttpServletRequest;
46
import java.io.IOException;
47
import java.time.LocalDate;
48
import java.time.LocalDateTime;
49
import java.time.LocalTime;
50
import java.time.format.DateTimeFormatter;
51
import java.util.*;
33102 tejus.loha 52
import java.util.stream.Collectors;
33092 tejus.loha 53
 
23612 amit.gupta 54
@Controller
26298 tejbeer 55
@Transactional(rollbackFor = Throwable.class)
23612 amit.gupta 56
public class ReportsController {
33143 tejus.loha 57
    private static final Logger LOGGER = LogManager.getLogger(OrderController.class);
58
    private static final Logger Logger = LogManager.getLogger(OrderController.class);
59
    @Autowired
60
    private RoleRepository roleRepository;
61
    @Autowired
62
    private FofoOrderRepository fofoOrderRepository;
63
    @Autowired
64
    private RetailerService retailerService;
65
    @Autowired
66
    private PendingOrderItemRepository pendingOrderItemRepository;
67
    @Autowired
68
    private PendingOrderService pendingOrderService;
69
    @Autowired
70
    private CookiesProcessor cookiesProcessor;
71
    @Autowired
72
    private FofoStoreRepository fofoStoreRepository;
73
    @Autowired
74
    private ReporticoService reporticoService;
75
    @Autowired
76
    private OrderRepository orderRepository;
77
    @Autowired
78
    private RoleManager roleManager;
79
    @Autowired
80
    private OrderService orderService;
81
    @Autowired
82
    private CsService csService;
83
    @Autowired
84
    private AuthRepository authRepository;
33775 ranu 85
    @Autowired
86
    private WalletService walletService;
87
    @Autowired
88
    private UserWalletHistoryRepository userWalletHistoryRepository;
89
    @Autowired
90
    private TransactionService transactionService;
33809 ranu 91
    @Autowired
92
    private LoanStatementRepository loanStatementRepository;
26298 tejbeer 93
 
33186 amit.gupta 94
    @PostMapping(value = "/reports/{projectName}/{fileName}")
33143 tejus.loha 95
    public ResponseEntity<?> fetchReport(HttpServletRequest request, @PathVariable String fileName,
33187 amit.gupta 96
                                         @PathVariable ReporticoProject projectName, @RequestBody Map<String, String> paramsMap)
33143 tejus.loha 97
            throws ProfitMandiBusinessException, UnsupportedOperationException, IOException {
98
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
99
        HttpResponse response;
100
        if (roleManager.isAdmin(loginDetails.getRoleIds())) {
33102 tejus.loha 101
 
33143 tejus.loha 102
            if (fileName.equalsIgnoreCase("LeadsReport")) {
103
                if (paramsMap == null) {
104
                    paramsMap = new HashMap<String, String>();
105
                }
106
                Map<Integer, List<Integer>> mapping = csService.getL2L1Mapping();
33102 tejus.loha 107
 
33143 tejus.loha 108
                AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
33102 tejus.loha 109
 
33143 tejus.loha 110
                List<Integer> authIds = mapping.get(authUser.getId());
111
                if (authIds == null) {
112
                    authIds = new ArrayList<>();
113
                }
114
                authIds.add(authUser.getId());
33102 tejus.loha 115
 
33143 tejus.loha 116
                paramsMap.put("authId", authIds + "");
117
            }
118
        } else {
119
            if (paramsMap == null) {
120
                paramsMap = new HashMap<String, String>();
121
            }
26298 tejbeer 122
 
33143 tejus.loha 123
            paramsMap.put("MANUAL_fofoId", loginDetails.getFofoId() + "");
23764 amit.gupta 124
 
33143 tejus.loha 125
        }
126
        response = getAdminReportFile(loginDetails.getEmailId(), projectName, fileName + ".xml", paramsMap);
127
        HttpHeaders headers = new HttpHeaders();
128
        InputStreamResource is = new InputStreamResource(response.getEntity().getContent());
129
        headers.set("Content-Type", "application/vnd.ms-excel");
130
        headers.set("Content-disposition", "inline; filename=report-" + fileName + ".csv");
131
        headers.setContentLength(response.getEntity().getContentLength());
132
        return new ResponseEntity<InputStreamResource>(is, headers, HttpStatus.OK);
133
    }
26298 tejbeer 134
 
33143 tejus.loha 135
    private HttpResponse getAdminReportFile(String email, ReporticoProject projectName, String fileName,
136
                                            Map<String, String> reportParams) throws ProfitMandiBusinessException, IOException {
137
        return reporticoService.getReportFile(projectName, fileName, reportParams);
138
    }
26298 tejbeer 139
 
33143 tejus.loha 140
    @RequestMapping(value = "/collectionSummary", method = RequestMethod.GET)
141
    public String getCollectionSummary(HttpServletRequest request,
142
                                       Model model) throws ProfitMandiBusinessException {
143
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
144
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
145
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
146
        LocalDateTime currentStartMonth = currentDate.minusDays(30).toLocalDate().atStartOfDay();
147
        List<CollectionSummary> collectionSummaryList = orderRepository.selectCollectionSummary(fofoDetails.getFofoId(), currentStartMonth, currentDate);
148
        Logger.info("CollectionSummaryList {}", collectionSummaryList);
149
        model.addAttribute("startDate", currentDate.minusDays(30).toLocalDate());
150
        model.addAttribute("endDate", LocalDate.now());
151
        model.addAttribute("collectionSummaryList", collectionSummaryList);
152
        model.addAttribute("isAdmin", isAdmin);
153
        return "partner-collection-summary";
154
    }
26298 tejbeer 155
 
33143 tejus.loha 156
    @RequestMapping(value = "/collectionSummaryFetchReportByDate", method = RequestMethod.GET)
157
    public String getcollectionSummaryFetchReport(HttpServletRequest request,
158
                                                  @RequestParam(defaultValue = "0") int fofoId,
159
                                                  @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
160
                                                  @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate, Model model)
161
            throws Exception {
162
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
163
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
164
        if (isAdmin) {
165
            startDate = LocalDate.now().minusDays(30);
166
            endDate = LocalDate.now();
167
        }
168
        model.addAttribute("startDate", startDate);
169
        model.addAttribute("endDate", endDate);
170
        model.addAttribute("isAdmin", isAdmin);
23612 amit.gupta 171
 
26298 tejbeer 172
 
33143 tejus.loha 173
        if (isAdmin) {
174
            if (fofoId == 0) {
175
                //No need to send any data
176
                model.addAttribute("collectionSummaryList", new ArrayList<>());
177
                return "partner-collection-summary";
178
            } else {
179
                List<CollectionSummary> collectionSummaryList = orderRepository
180
                        .selectCollectionSummary(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
181
                model.addAttribute("collectionSummaryList", collectionSummaryList);
182
                return "partner-collection-summary";
183
            }
184
        } else {
185
            fofoId = fofoDetails.getFofoId();
186
            List<CollectionSummary> collectionSummaryList = orderRepository
187
                    .selectCollectionSummary(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
188
            model.addAttribute("collectionSummaryList", collectionSummaryList);
189
            return "partner-collection-summary";
26298 tejbeer 190
 
33143 tejus.loha 191
        }
192
    }
26298 tejbeer 193
 
33143 tejus.loha 194
    @RequestMapping(value = "/downloadCollectionSummary", method = RequestMethod.GET)
195
    public ResponseEntity<?> getDownloadCollectionSummary(HttpServletRequest request,
196
                                                          @RequestParam(defaultValue = "0") int fofoId,
197
                                                          @RequestParam(name = "startDate") LocalDate startDate,
198
                                                          @RequestParam(name = "endDate") LocalDate endDate, Model model) throws Exception {
199
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
200
        List<List<?>> rows = new ArrayList<>();
201
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
202
        List<CollectionSummary> collectionSummaryList = null;
203
        if (isAdmin) {
204
            if (fofoId == 0) {
205
                collectionSummaryList = new ArrayList<>();
206
            } else {
207
                collectionSummaryList = orderRepository.selectCollectionSummary(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
208
            }
209
        } else {
210
            collectionSummaryList = orderRepository.selectCollectionSummary(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
211
        }
212
        Logger.info("CollectionSummaryList {}", collectionSummaryList);
213
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
214
        for (CollectionSummary cs : collectionSummaryList) {
215
            rows.add(Arrays.asList(cs.getDate().format(
216
                            dateTimeFormatter), cs.getReferenceType(), cs.getCash(), cs.getPinelabs(), cs.getBajajFinserv(), cs.getHomeCredit(), cs.getPaytm(),
217
                    cs.getCapitalFirst(), cs.getZestMoney(), cs.getSamsungSure(), cs.getTotalAmount()));
218
        }
219
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
220
                .getCSVByteStream(Arrays.asList("Date", "Reference Type", "Cash", "Pinelabs", "Bajaj Finservice", "Home Credit", "Paymt",
221
                        "Capital First", "Zest Money", "Samsung Sure", "Total Amount"), rows);
222
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Collection Summary Report");
26298 tejbeer 223
 
33143 tejus.loha 224
        return responseEntity;
225
    }
26298 tejbeer 226
 
33143 tejus.loha 227
    @RequestMapping(value = "/franchiseeSalesReport", method = RequestMethod.GET)
228
    public String getFranchiseeSalesReport(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
229
                                           @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate)
230
            throws ProfitMandiBusinessException {
231
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
232
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
233
        if (startDate == null) {
234
            startDate = LocalDate.now().minusDays(30);
26298 tejbeer 235
 
33143 tejus.loha 236
        }
237
        endDate = LocalDate.now();
238
        model.addAttribute("startDate", startDate);
239
        model.addAttribute("endDate", endDate);
240
        model.addAttribute("isAdmin", isAdmin);
241
        LOGGER.info("q {}, starDate - {}, endDate - {}", fofoId, startDate, endDate);
242
        if (isAdmin) {
243
            if (fofoId == 0) {
244
                //No need to pull any data
245
                model.addAttribute("focoSaleReportList", new ArrayList<>());
246
                return "foco-sale-report";
23637 amit.gupta 247
 
33143 tejus.loha 248
            }
249
        } else {
250
            fofoId = loginDetails.getFofoId();
251
        }
33102 tejus.loha 252
 
253
 
33143 tejus.loha 254
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
33067 shampa 255
 
33143 tejus.loha 256
        List<FocoSaleReportModel> focoSaleReportList = fofoOrderRepository.selectFocoSaleReport(fofoId, fs.getCode(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
257
        model.addAttribute("focoSaleReportList", focoSaleReportList);
258
        return "foco-sale-report";
259
    }
33067 shampa 260
 
33143 tejus.loha 261
    @RequestMapping(value = "/franchiseeSalesFetchReportByDate", method = RequestMethod.GET)
262
    public String getfranchiseeSalesFetchReport(HttpServletRequest request, Model model,
263
                                                @RequestParam(defaultValue = "0") int fofoId,
264
                                                @RequestParam(required = false) LocalDate startDate,
265
                                                @RequestParam(required = false) LocalDate endDate)
266
            throws Exception {
267
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
268
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
269
        if (startDate == null) {
33067 shampa 270
 
33143 tejus.loha 271
            startDate = LocalDate.now().minusDays(30);
272
            endDate = LocalDate.now();
273
        }
274
        model.addAttribute("startDate", startDate);
275
        model.addAttribute("endDate", endDate);
276
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 277
 
33143 tejus.loha 278
        // List<List<?>> rows = new ArrayList<>();
30162 manish 279
 
33143 tejus.loha 280
        LOGGER.info("q {}, starDate - {}, endDate - {}", fofoId, startDate, endDate);
281
        if (isAdmin) {
282
            if (fofoId == 0) {
283
                //no need any data
284
                model.addAttribute("focoSaleReportList", new ArrayList<>());
285
                return "foco-sale-report";
286
            }
287
        } else {
288
            fofoId = loginDetails.getFofoId();
289
        }
290
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
291
        List<FocoSaleReportModel> focoSaleReportList = fofoOrderRepository.selectFocoSaleReport(fofoId, fs.getCode(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
292
        model.addAttribute("focoSaleReportList", focoSaleReportList);
293
        return "foco-sale-report";
294
    }
30162 manish 295
 
296
 
33143 tejus.loha 297
    @RequestMapping(value = "/downloadFranchiseeSales", method = RequestMethod.GET)
298
    public ResponseEntity<?> getdownloadFranchiseeSales(HttpServletRequest request,
299
                                                        @RequestParam(defaultValue = "0") int fofoId,
300
                                                        @RequestParam(name = "startDate") LocalDate startDate,
301
                                                        @RequestParam(name = "endDate") LocalDate endDate,
302
                                                        Model model)
303
            throws Exception {
304
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 305
 
33143 tejus.loha 306
        List<List<?>> rows = new ArrayList<>();
307
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
308
        List<FocoSaleReportModel> focoSaleReportList = null;
309
        FofoStore fs = null;
310
        if (isAdmin) {
311
            fs = fofoStoreRepository.selectByRetailerId(fofoId);
312
            if (fofoId == 0) {
313
                focoSaleReportList = new ArrayList<>();
314
            } else {
33102 tejus.loha 315
 
33143 tejus.loha 316
                focoSaleReportList = fofoOrderRepository.selectFocoSaleReport(fofoId,
317
                        fs.getCode(), startDate.atStartOfDay(), endDate.atStartOfDay());
318
            }
33102 tejus.loha 319
 
33143 tejus.loha 320
        } else {
321
            fs = fofoStoreRepository.selectByRetailerId(fofoDetails.getFofoId());
33102 tejus.loha 322
 
33143 tejus.loha 323
            focoSaleReportList = fofoOrderRepository.selectFocoSaleReport(fofoDetails.getFofoId(),
324
                    fs.getCode(), startDate.atStartOfDay(), endDate.atStartOfDay());
325
        }
326
        LOGGER.info("FocoSaleReportList {}", focoSaleReportList);
327
        String partnerName = null;
328
        for (FocoSaleReportModel fsr : focoSaleReportList) {
329
            partnerName = fsr.getName();
330
            rows.add(Arrays.asList(fsr.getCode(), fsr.getName(), fsr.getCity(), fsr.getState(), fsr.getRegion(),
331
                    fsr.getItemId(), fsr.getBrand(), fsr.getModelName(), fsr.getModelNumber(), fsr.getColor(),
332
                    fsr.getQuantity(), fsr.getDp(), fsr.getSellingPrice(), fsr.getMop(), fsr.getSerialNumber(),
333
                    FormattingUtils.format(fsr.getCreateDate()), fsr.getCustomerName(), fsr.getCustomerPhone(),
334
                    fsr.getCustomerCity(), fsr.getCustomerPincode(), fsr.getInvoiceNumber(), fsr.getPurchaseReference(),
335
                    fsr.getCustomerGstNumber(), FormattingUtils.format(fsr.getCancelledTimestamp()),
336
                    FormattingUtils.format(fsr.getGrnCompleteDate()), fsr.getHygieneRating(), fsr.getRating(),
337
                    fsr.getStatus(), fsr.getRemark(), FormattingUtils.format(fsr.getCreatedTimestamp()),
338
                    FormattingUtils.format(fsr.getDisposedTimestamp()),
339
                    FormattingUtils.format(fsr.getNextTimestamp()),
340
                    FormattingUtils.format(fsr.getActivationTimestamp()),
341
                    FormattingUtils.format(fsr.getActivationTimestamp()), fsr.getLabel()));
33102 tejus.loha 342
 
33143 tejus.loha 343
        }
33102 tejus.loha 344
 
33143 tejus.loha 345
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
346
                Arrays.asList("Code", "Name", "City", "State", "Region", "Item Id", "Brand", "Model Name",
347
                        "Model Number", "Color", "Quantity", "Dp", "Selling_Price", "mop", "Serial Number",
348
                        "Create Date", "Customer Name", "Customer Phone", "Customer City", " Customer Pincode",
349
                        "Invoice  Number", "Purchase Reference", "Customer Gst Number", " Cancelled Timestamp",
350
                        "GRN Complete Date", "Hygiene Rating", "Rating", "Status", "Remark", "Created Timestamp",
351
                        "Disposed Timestamp", " Next Timestamp", "Activation Timestamp", "Create Timestamp", "Label"),
352
                rows);
33102 tejus.loha 353
 
33143 tejus.loha 354
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, partnerName + " Franchisee Sales Report");
33102 tejus.loha 355
 
33143 tejus.loha 356
        return responseEntity;
33102 tejus.loha 357
 
33143 tejus.loha 358
    }
33102 tejus.loha 359
 
33143 tejus.loha 360
    @RequestMapping(value = "/downloadWalletSummaryReport", method = RequestMethod.GET)
361
    public ResponseEntity<?> getDownloadWalletSummaryReport(HttpServletRequest request,
362
                                                            @RequestParam(defaultValue = "0", name = "fofoId") int fofoId,
363
                                                            @RequestParam(name = "startDate") LocalDate startDate,
364
                                                            @RequestParam(name = "endDate") LocalDate endDate, Model model)
365
            throws Exception {
33102 tejus.loha 366
 
33143 tejus.loha 367
        List<List<?>> rows = new ArrayList<>();
368
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
369
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
370
        List<WalletSummaryReportModel> walletSummartList = null;
371
        if (isAdmin) {
372
            if (fofoId == 0)
373
                walletSummartList = new ArrayList<>();
374
            else
375
                walletSummartList = fofoOrderRepository.selectWalletSummaryReport(
376
                        fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
377
        } else {
33102 tejus.loha 378
 
33143 tejus.loha 379
            walletSummartList = fofoOrderRepository.selectWalletSummaryReport(
380
                    fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
381
        }
382
        LOGGER.info("walletSummartList {}", fofoId);
383
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
384
        String partnerDetail = null;
33108 tejus.loha 385
 
33143 tejus.loha 386
        for (WalletSummaryReportModel walletSummary : walletSummartList) {
387
            partnerDetail = walletSummary.getName() + "(" + walletSummary.getCode() + "-" + walletSummary.getPhone() + ")" + "-" + walletSummary.getEmail();
33102 tejus.loha 388
 
33143 tejus.loha 389
            rows.add(Arrays.asList(
390
                    walletSummary.getId(),
391
                    //walletSummary.getCode(),
392
                    //walletSummary.getName(),
393
                    //walletSummary.getEmail(),
394
                    //walletSummary.getPhone(),
395
                    walletSummary.getAmount(),
396
                    walletSummary.getRefundableAmount(),
397
                    walletSummary.getReference(),
398
                    walletSummary.getReferenceType(),
399
                    FormattingUtils.format(walletSummary.getBusinessTimestamp()),
400
                    walletSummary.getDescription()
401
            ));
33102 tejus.loha 402
 
33143 tejus.loha 403
        }
33102 tejus.loha 404
 
33143 tejus.loha 405
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
406
                .getCSVByteStream(Arrays.asList("Id",
33126 tejus.loha 407
//						"Code",
408
//						"Name",
409
//						"Email",
410
//						"Phone",
33143 tejus.loha 411
                        "Amount", "Refundable_amount",
412
                        "Reference", "Reference_type", "Business_timestamp", "Description"), rows);
413
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, partnerDetail + " Wallet Statement Report");
33102 tejus.loha 414
 
33143 tejus.loha 415
        return responseEntity;
33102 tejus.loha 416
 
33143 tejus.loha 417
    }
33102 tejus.loha 418
 
33143 tejus.loha 419
    @RequestMapping(value = "/walletSummaryFetchReportByDate", method = RequestMethod.GET)
420
    public String getwalletSummaryFetchReport(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
421
                                              @RequestParam(required = false) LocalDate startDate,
422
                                              @RequestParam(required = false) LocalDate endDate)
423
            throws Exception {
424
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
425
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
426
        if (startDate == null) {
427
            startDate = LocalDate.now().minusDays(30);
428
        }
429
        endDate = LocalDate.now();
430
        model.addAttribute("startDate", startDate);
431
        model.addAttribute("endDate", endDate);
432
        model.addAttribute("isAdmin", isAdmin);
433
        if (isAdmin) {
434
            if (fofoId == 0) {
435
                //No need to send any data
436
                model.addAttribute("walletSummartList", new ArrayList<>());
33102 tejus.loha 437
 
33143 tejus.loha 438
                return "wallet-summary-report";
439
            } else {
440
                List<WalletSummaryReportModel> walletSummartList = fofoOrderRepository
441
                        .selectWalletSummaryReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
442
                model.addAttribute("walletSummartList", walletSummartList);
33102 tejus.loha 443
 
33143 tejus.loha 444
                return "wallet-summary-report";
445
            }
33102 tejus.loha 446
 
33143 tejus.loha 447
        } else {
33102 tejus.loha 448
 
449
 
33143 tejus.loha 450
            FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
451
            List<WalletSummaryReportModel> walletSummartList = fofoOrderRepository
452
                    .selectWalletSummaryReport(loginDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
453
            //LOGGER.info("walletSummartList {}", walletSummartList);
33102 tejus.loha 454
 
33143 tejus.loha 455
            model.addAttribute("walletSummartList", walletSummartList);
33102 tejus.loha 456
 
33143 tejus.loha 457
            return "wallet-summary-report";
458
        }
459
    }
33102 tejus.loha 460
 
33143 tejus.loha 461
    @RequestMapping(value = "/walletSummaryReport", method = RequestMethod.GET)
462
    public String getWalletSummaryReport(HttpServletRequest request, Model model) throws Exception {
463
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
464
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
465
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
466
        LocalDateTime currentStartMonth = currentDate.minusDays(30).toLocalDate().atStartOfDay();
33102 tejus.loha 467
 
33143 tejus.loha 468
        List<WalletSummaryReportModel> walletSummartList = fofoOrderRepository
469
                .selectWalletSummaryReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
470
        LOGGER.info("walletSummartList {}", walletSummartList);
33102 tejus.loha 471
 
33143 tejus.loha 472
        model.addAttribute("startDate", currentDate.minusDays(30).toLocalDate());
473
        model.addAttribute("endDate", LocalDate.now());
474
        model.addAttribute("walletSummartList", walletSummartList);
475
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 476
 
33143 tejus.loha 477
        return "wallet-summary-report";
478
    }
33102 tejus.loha 479
 
33143 tejus.loha 480
    @RequestMapping(value = "/pendingIndentReport", method = RequestMethod.GET)
481
    public String getPendingIndentReport(HttpServletRequest request, Model model) throws Exception {
482
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
483
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33102 tejus.loha 484
 
33143 tejus.loha 485
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
486
        LocalDateTime currentStartMonth = currentDate.minusMonths(2).toLocalDate().atStartOfDay();
33102 tejus.loha 487
 
33143 tejus.loha 488
        List<PendingIndentReportModel> pendingIndentReports = fofoOrderRepository
489
                .selectPendingIndentReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
490
        LOGGER.info("pendingIndentReports {}", pendingIndentReports);
33102 tejus.loha 491
 
33143 tejus.loha 492
        model.addAttribute("startDate", currentDate.minusMonths(2).toLocalDate());
493
        model.addAttribute("endDate", LocalDate.now());
494
        model.addAttribute("pendingIndentReports", pendingIndentReports);
495
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 496
 
497
 
33143 tejus.loha 498
        return "pending-indent-report";
499
    }
33102 tejus.loha 500
 
33143 tejus.loha 501
    @RequestMapping(value = "/pendingIndentFetchReportByDate", method = RequestMethod.GET)
502
    public String getpendingIndentFetchReport(
503
            HttpServletRequest request,
504
            @RequestParam(defaultValue = "0") int fofoId,
505
            @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
506
            @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate,
507
            Model model
508
    ) throws Exception {
509
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
510
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
511
        if (startDate == null) {
512
            startDate = LocalDate.now().minusDays(30);
513
            endDate = LocalDate.now();
514
        }
515
        model.addAttribute("startDate", startDate);
516
        model.addAttribute("endDate", endDate);
517
        model.addAttribute("isAdmin", isAdmin);
518
        if (isAdmin) {
519
            if (fofoId == 0) {
520
                model.addAttribute("pendingIndentReports", new ArrayList<>());
521
                return "pending-indent-report";
522
            } else {
523
                List<PendingIndentReportModel> pendingIndentReports = fofoOrderRepository
524
                        .selectPendingIndentReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
525
                model.addAttribute("pendingIndentReports", pendingIndentReports);
526
                return "pending-indent-report";
527
            }
528
        } else {
529
            LocalDateTime currentDate = LocalDate.now().atStartOfDay();
530
            List<PendingIndentReportModel> pendingIndentReports = fofoOrderRepository
531
                    .selectPendingIndentReport(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
532
            model.addAttribute("pendingIndentReports", pendingIndentReports);
533
            return "pending-indent-report";
33102 tejus.loha 534
 
33143 tejus.loha 535
        }
536
    }
33102 tejus.loha 537
 
538
 
33143 tejus.loha 539
    @RequestMapping(value = "/pendingIndentReportDownload", method = RequestMethod.GET)
540
    public ResponseEntity<?> getPendingIndentReportDownload(HttpServletRequest request,
541
                                                            @RequestParam(defaultValue = "0") int fofoId,
542
                                                            @RequestParam(name = "startDate") LocalDate startDate,
543
                                                            @RequestParam(name = "endDate") LocalDate endDate, Model model)
544
            throws Exception {
545
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
546
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33102 tejus.loha 547
        /*LocalDateTime currentDate = LocalDate.now().atStartOfDay();
548
        LocalDateTime currentStartMonth = currentDate.minusMonths(2).toLocalDate().atStartOfDay();*/
33143 tejus.loha 549
        List<PendingIndentReportModel> pendingIndentReports = null;
550
        List<List<?>> rows = new ArrayList<>();
551
        if (isAdmin) {
552
            if (fofoId == 0)
553
                pendingIndentReports = new ArrayList<>();
554
            else
555
                pendingIndentReports = fofoOrderRepository
556
                        .selectPendingIndentReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
557
        } else {
558
            pendingIndentReports = fofoOrderRepository
559
                    .selectPendingIndentReport(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 560
 
33143 tejus.loha 561
        }
562
        LOGGER.info("pendingIndentReports {}", pendingIndentReports);
563
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
33102 tejus.loha 564
 
33143 tejus.loha 565
        for (PendingIndentReportModel pir : pendingIndentReports) {
33102 tejus.loha 566
 
33143 tejus.loha 567
            rows.add(Arrays.asList(pir.getTransactionId(), pir.getOrderId(),
568
                    pir.getCreatTimestamp().format(dateTimeFormatter), pir.getItemId(), pir.getBrand(),
569
                    pir.getModelName(), pir.getModelNumber(), pir.getColor(), pir.getQuantity(), pir.getUnitPrice(),
570
                    pir.getWalletAmount(), pir.getStatus(), pir.getInvoiceNumber(),
571
                    pir.getBillingTimestamp() == null ? "" : pir.getBillingTimestamp().format(dateTimeFormatter)));
33102 tejus.loha 572
 
33143 tejus.loha 573
        }
33102 tejus.loha 574
 
33143 tejus.loha 575
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList(
576
                "Transaction Id", "Order Id", "Created_At", "Item_Id", "Brand", "Model Name", "Model Number", "Color",
577
                "Quantity", "Unit Price", "Wallet Deduction", "Status", "Invoice Number", "Billing Timestamp"), rows);
33102 tejus.loha 578
 
33143 tejus.loha 579
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Order Status Summary Report");
33102 tejus.loha 580
 
33143 tejus.loha 581
        return responseEntity;
582
    }
33102 tejus.loha 583
 
33143 tejus.loha 584
    @RequestMapping(value = "/schemePayoutReport", method = RequestMethod.GET)
585
    public String getschemePayoutReport(HttpServletRequest request, Model model,
586
                                        @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate)
587
            throws ProfitMandiBusinessException {
33102 tejus.loha 588
 
33143 tejus.loha 589
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
590
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
591
        if (startDate == null) {
592
            startDate = LocalDate.now().minusDays(30);
593
            endDate = LocalDate.now();
594
        }
595
        model.addAttribute("startDate", startDate);
596
        model.addAttribute("endDate", endDate);
597
        model.addAttribute("isAdmin", isAdmin);
598
        //LOGGER.info("schemePayoutReports {}", schemePayoutReports);
599
        List<SchemePayoutReportModel> schemePayoutReports = fofoOrderRepository
600
                .selectSchemePayoutReport(loginDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
601
        model.addAttribute("schemePayoutReports", schemePayoutReports);
602
        return "scheme-payout-report";
33102 tejus.loha 603
 
33143 tejus.loha 604
    }
33102 tejus.loha 605
 
33143 tejus.loha 606
    @RequestMapping(value = "/schemePayoutFetchReportByDate", method = RequestMethod.GET)
607
    public String getschemePayoutFetchReportByDate(
608
            HttpServletRequest request,
609
            Model model,
610
            @RequestParam(defaultValue = "0") int fofoId,
611
            @RequestParam(required = false) LocalDate startDate,
612
            @RequestParam(required = false) LocalDate endDate)
613
            throws ProfitMandiBusinessException {
614
        //LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
615
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
616
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
617
        if (startDate == null) {
618
            startDate = LocalDate.now().minusDays(30);
619
            endDate = LocalDate.now();
620
        }
621
        model.addAttribute("startDate", startDate);
622
        model.addAttribute("endDate", endDate);
623
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 624
 
33143 tejus.loha 625
        LOGGER.info("q {}, starDate - {}, endDate - {}", fofoId, startDate, endDate);
626
        if (isAdmin) {
627
            if (fofoId == 0) {
628
                //No need to pull any data
629
                model.addAttribute("schemePayoutReports", new ArrayList<>());
630
                return "scheme-payout-report";
33102 tejus.loha 631
 
33143 tejus.loha 632
            } else {
633
                List<SchemePayoutReportModel> schemePayoutReports = fofoOrderRepository
634
                        .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 635
 
33143 tejus.loha 636
                model.addAttribute("schemePayoutReports", schemePayoutReports);
637
                return "scheme-payout-report";
638
            }
639
        } else {
640
            fofoId = loginDetails.getFofoId();
33102 tejus.loha 641
 
33143 tejus.loha 642
            List<SchemePayoutReportModel> schemePayoutReports = fofoOrderRepository
643
                    .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 644
 
33143 tejus.loha 645
            model.addAttribute("schemePayoutReports", schemePayoutReports);
646
            return "scheme-payout-report";
647
        }
33102 tejus.loha 648
 
33143 tejus.loha 649
    }
33102 tejus.loha 650
 
33143 tejus.loha 651
    @RequestMapping(value = "/offerPayoutReport", method = RequestMethod.GET)
652
    public String getOfferPayoutReport(HttpServletRequest request, Model model, @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate) throws Exception {
653
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
654
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33102 tejus.loha 655
 
33143 tejus.loha 656
        if (startDate == null) {
657
            startDate = LocalDate.now().minusDays(30);
658
            endDate = LocalDate.now();
659
        }
660
        model.addAttribute("startDate", startDate);
661
        model.addAttribute("endDate", endDate);
33102 tejus.loha 662
 
663
 
33143 tejus.loha 664
        List<OfferPayoutDumpReportModel> offerPayoutDumpReports = fofoOrderRepository
665
                .selectOfferPayoutDumpReport(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
666
        LOGGER.info("offerPayoutDumpReports {}", offerPayoutDumpReports);
33102 tejus.loha 667
 
33143 tejus.loha 668
        model.addAttribute("offerPayoutDumpReports", offerPayoutDumpReports);
669
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 670
 
33143 tejus.loha 671
        return "offer-payout-dump-report";
672
    }
33102 tejus.loha 673
 
33143 tejus.loha 674
    @RequestMapping(value = "/offerPayoutFetchReportByDate", method = RequestMethod.GET)
675
    public String getofferPayoutFetchReportByDate(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
676
                                                  @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate)
677
            throws ProfitMandiBusinessException {
33102 tejus.loha 678
 
33143 tejus.loha 679
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
680
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
681
        if (startDate == null) {
682
            startDate = LocalDate.now().minusDays(30);
683
            endDate = LocalDate.now();
684
        }
685
        model.addAttribute("startDate", startDate);
686
        model.addAttribute("endDate", endDate);
687
        model.addAttribute("isAdmin", isAdmin);
688
        LOGGER.info("q {}, starDate - {}, endDate - {}", fofoId, startDate, endDate);
689
        if (isAdmin) {
690
            if (fofoId == 0) {
691
                //No need to pull any data
692
                model.addAttribute("offerPayoutReports", new ArrayList<>());
693
                return "offer-payout-dump-report";
33102 tejus.loha 694
 
33143 tejus.loha 695
            } else {
696
                List<OfferPayoutDumpReportModel> offerPayoutDumpReports = fofoOrderRepository
697
                        .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 698
 
33143 tejus.loha 699
                model.addAttribute("offerPayoutDumpReports", offerPayoutDumpReports);
33102 tejus.loha 700
 
701
 
33143 tejus.loha 702
                return "offer-payout-dump-report";
33102 tejus.loha 703
 
33143 tejus.loha 704
            }
705
        } else {
706
            fofoId = loginDetails.getFofoId();
707
            List<OfferPayoutDumpReportModel> offerPayoutDumpReports = fofoOrderRepository
708
                    .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 709
 
33143 tejus.loha 710
            model.addAttribute("offerPayoutDumpReports", offerPayoutDumpReports);
33102 tejus.loha 711
 
712
 
33143 tejus.loha 713
            return "offer-payout-dump-report";
714
        }
715
    }
33102 tejus.loha 716
 
717
 
33143 tejus.loha 718
    @RequestMapping(value = "/selectPartnerBillingSummaryReport", method = RequestMethod.GET)
719
    public String getselectPartnerBillingSummaryReport(HttpServletRequest request, Model model) throws Exception {
720
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 721
 
33143 tejus.loha 722
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
723
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 724
 
33143 tejus.loha 725
        List<PartnerBillingSummaryModel> partnerBillingSummaryReports = fofoOrderRepository
726
                .selectPartnerBillingSummaryReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
33102 tejus.loha 727
 
33143 tejus.loha 728
        model.addAttribute("startDate", currentDate.minusMonths(3).toLocalDate());
729
        model.addAttribute("endDate", LocalDate.now());
730
        model.addAttribute("partnerBillingSummaryReports", partnerBillingSummaryReports);
33102 tejus.loha 731
 
33143 tejus.loha 732
        return "partner-billing-summary-report";
733
    }
33102 tejus.loha 734
 
33143 tejus.loha 735
    @RequestMapping(value = "/priceDropReport", method = RequestMethod.GET)
736
    public String getSelectPriceDropReport(HttpServletRequest request, @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
737
                                           @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate, Model model) throws Exception {
738
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
739
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
740
        if (startDate == null) {
741
            startDate = LocalDate.now().minusDays(30);
742
            endDate = LocalDate.now();
743
        }
744
        model.addAttribute("startDate", startDate);
745
        model.addAttribute("endDate", endDate);
746
        model.addAttribute("isAdmin", isAdmin);
747
        List<PriceDropReportModel> priceDropReports = orderRepository.selectPriceDropReport(fofoDetails.getFofoId(),
748
                startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 749
 
33143 tejus.loha 750
        model.addAttribute("priceDropReports", priceDropReports);
33102 tejus.loha 751
 
33143 tejus.loha 752
        return "price-drop-report";
753
    }
33102 tejus.loha 754
 
33143 tejus.loha 755
    @RequestMapping(value = "/priceDropFetchReportByDate", method = RequestMethod.GET)
756
    public String getpriceDropFetchReportByDate(HttpServletRequest request,
757
                                                @RequestParam(defaultValue = "0") int fofoId,
758
                                                @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
759
                                                @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate, Model model)
760
            throws Exception {
33102 tejus.loha 761
 
33143 tejus.loha 762
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
763
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
764
        if (startDate == null) {
765
            startDate = LocalDate.now().minusDays(30);
766
            endDate = LocalDate.now();
767
        }
768
        model.addAttribute("startDate", startDate);
769
        model.addAttribute("endDate", endDate);
770
        model.addAttribute("isAdmin", isAdmin);
771
        if (isAdmin) {
772
            if (fofoId == 0) {
773
                model.addAttribute("priceDropReports", new ArrayList<>());
774
                return "price-drop-report";
775
            } else {
776
                List<PriceDropReportModel> priceDropReports = orderRepository.selectPriceDropReport(fofoId,
777
                        startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
778
                model.addAttribute("priceDropReports", priceDropReports);
779
                return "price-drop-report";
780
            }
33102 tejus.loha 781
 
33143 tejus.loha 782
        } else {
783
            List<PriceDropReportModel> priceDropReports = orderRepository.selectPriceDropReport(fofoDetails.getFofoId(),
784
                    startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
785
            model.addAttribute("priceDropReports", priceDropReports);
786
            return "price-drop-report";
787
        }
788
    }
33102 tejus.loha 789
 
790
 
33143 tejus.loha 791
    @RequestMapping(value = "/downloadPriceDropReport", method = RequestMethod.GET)
792
    public ResponseEntity<?> getSelectDownloadPriceDropReport(HttpServletRequest request,
793
                                                              @RequestParam(defaultValue = "0") int fofoId,
794
                                                              @RequestParam(name = "startDate") LocalDate startDate,
795
                                                              @RequestParam(name = "endDate") LocalDate endDate, Model model)
796
            throws Exception {
797
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
798
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
799
        List<List<?>> rows = new ArrayList<>();
800
        List<PriceDropReportModel> priceDropReports = null;
801
        if (isAdmin) {
802
            if (fofoId == 0)
803
                priceDropReports = new ArrayList<>();
804
            else
805
                priceDropReports = orderRepository.selectPriceDropReport(fofoId,
806
                        startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
807
        } else {
808
            fofoId = fofoDetails.getFofoId();
809
            priceDropReports = orderRepository.selectPriceDropReport(fofoId,
810
                    startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
811
        }
812
        for (PriceDropReportModel pdr : priceDropReports) {
33102 tejus.loha 813
 
33143 tejus.loha 814
            rows.add(Arrays.asList(pdr.getCode(), pdr.getId(), pdr.getBrand(), pdr.getModelName(), pdr.getModelNumber(),
815
                    FormattingUtils.formatDate(pdr.getAffectedOn()), pdr.getAmount(), FormattingUtils.format(pdr.getCreditTimestamp()), pdr.getImei(), pdr.getStatus(),
816
                    FormattingUtils.format(pdr.getRejectedTimestamp()), pdr.getRejectionReason()));
33102 tejus.loha 817
 
33143 tejus.loha 818
        }
819
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
820
                .getCSVByteStream(Arrays.asList("code", "Price_Drop_Id", "brand", "model_name", "model_number",
821
                        "affected_on", "amount", "Credit Date", "Imei", "status", "Rejected Date", "Rejected Reason"), rows);
33102 tejus.loha 822
 
33143 tejus.loha 823
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "price drop report");
33102 tejus.loha 824
 
33143 tejus.loha 825
        return responseEntity;
33102 tejus.loha 826
 
33143 tejus.loha 827
    }
33102 tejus.loha 828
 
33143 tejus.loha 829
    @RequestMapping(value = "/downloadPartnerBillingSummaryReport", method = RequestMethod.GET)
830
    public ResponseEntity<?> getdownloadPartnerBillingSummaryReport(HttpServletRequest request,
831
                                                                    @RequestParam(name = "startDate") LocalDate startDate,
832
                                                                    @RequestParam(name = "endDate") LocalDate endDate, Model model)
833
            throws Exception {
33102 tejus.loha 834
 
33143 tejus.loha 835
        List<List<?>> rows = new ArrayList<>();
836
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 837
 
33143 tejus.loha 838
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
839
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 840
 
33143 tejus.loha 841
        List<PartnerBillingSummaryModel> partnerBillingSummaryReports = fofoOrderRepository
842
                .selectPartnerBillingSummaryReport(fofoDetails.getFofoId(), startDate.atStartOfDay(),
843
                        endDate.atTime(LocalTime.MAX));
33102 tejus.loha 844
 
33143 tejus.loha 845
        for (PartnerBillingSummaryModel pbsr : partnerBillingSummaryReports) {
33102 tejus.loha 846
 
33143 tejus.loha 847
            rows.add(Arrays.asList(pbsr.getId(),
848
                    FormattingUtils.format(pbsr.getCreateTimestamp()),
849
                    FormattingUtils.format(pbsr.getBillingTimestamp()),
850
                    FormattingUtils.format(pbsr.getDeliveryTimestamp()),
851
                    FormattingUtils.format(pbsr.getPartnerGrnTimestamp()),
852
                    pbsr.getTransactionId(),
853
                    pbsr.getLogisticsTransactionId(), pbsr.getAirwayBillNumber(), pbsr.getStatusSubGroup(),
854
                    pbsr.getStatusName(), pbsr.getRetailerId(), pbsr.getRetailerName(), pbsr.getItemId(),
855
                    pbsr.getBrand(), pbsr.getModelName(), pbsr.getModelNumber(), pbsr.getColor(), pbsr.getUnitPrice(),
856
                    pbsr.getQuantity(), pbsr.getTotalPrice(), pbsr.getInvoiceNumber(), pbsr.getSellerName(), pbsr.getGstNumber(), pbsr.getHsnCode(), pbsr.getIgstRate(),
857
                    pbsr.getCgstRate(), pbsr.getSgstRate()));
33102 tejus.loha 858
 
33143 tejus.loha 859
        }
33102 tejus.loha 860
 
33143 tejus.loha 861
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("OrderId",
862
                "Created On", "Billed On", "Delivered On", "Grned On", "Transaction_id", "master_order_id",
863
                "airwaybill_no", "statusSubGroupp", "statusName", "customer_id", "customer_name", "Item_Id", "brand",
864
                "model_name", "model_number", "color", "selling_price", "Quantity", "total_price", "invoice_number",
865
                "seller_name", "gst_number", "hsn_code", "igstrate", "cgstrate", "sgstrate"), rows);
33102 tejus.loha 866
 
33143 tejus.loha 867
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Billing Statement Report");
33102 tejus.loha 868
 
33143 tejus.loha 869
        return responseEntity;
33102 tejus.loha 870
 
871
 
33143 tejus.loha 872
    }
33102 tejus.loha 873
 
33143 tejus.loha 874
    @RequestMapping(value = "/invoiceSchemeOutSummaryReport", method = RequestMethod.GET)
875
    public String getInvoiceSchemeOutSummaryReport(HttpServletRequest request, Model model) throws Exception {
876
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 877
 
33143 tejus.loha 878
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
879
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 880
 
33143 tejus.loha 881
        List<FocoSchemeOutReportModel> focoSchemeOutReports = fofoOrderRepository
882
                .selectInvoiceSchemeOutSummaryReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
883
        LOGGER.info("focoSchemeOutReportModel {}", focoSchemeOutReports);
33102 tejus.loha 884
 
33143 tejus.loha 885
        model.addAttribute("startDate", currentDate.minusMonths(3).toLocalDate());
886
        model.addAttribute("endDate", LocalDate.now());
887
        model.addAttribute("focoSchemeOutReports", focoSchemeOutReports);
33102 tejus.loha 888
 
33143 tejus.loha 889
        return "invoicewise-scheme-out-report";
890
    }
33102 tejus.loha 891
 
33143 tejus.loha 892
    @RequestMapping(value = "/downloadInvoiceSchemeOutSummaryReport", method = RequestMethod.GET)
893
    public ResponseEntity<?> getDownloadInvoiceSchemeOutSummaryReport(HttpServletRequest request, Model model)
894
            throws Exception {
895
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 896
 
33143 tejus.loha 897
        List<List<?>> rows = new ArrayList<>();
898
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
899
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 900
 
33143 tejus.loha 901
        List<FocoSchemeOutReportModel> focoSchemeOutReports = fofoOrderRepository
902
                .selectInvoiceSchemeOutSummaryReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
903
        LOGGER.info("focoSchemeOutReportModel {}", focoSchemeOutReports);
33102 tejus.loha 904
 
33143 tejus.loha 905
        for (FocoSchemeOutReportModel fsor : focoSchemeOutReports) {
906
            rows.add(Arrays.asList(fsor.getInvoiceNumber(), fsor.getQuantity(), fsor.getBrand(), fsor.getModelName(),
907
                    fsor.getModelNumber(), fsor.getColor(), fsor.getAmount()));
33102 tejus.loha 908
 
33143 tejus.loha 909
        }
33102 tejus.loha 910
 
33143 tejus.loha 911
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
912
                Arrays.asList("InvoiceNumber", "Quantity", "Brand", "Model Name", "Model Number", "Color", "Amount"),
913
                rows);
33102 tejus.loha 914
 
33143 tejus.loha 915
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows,
916
                "invoice wise scheme out Summary Report");
33102 tejus.loha 917
 
33143 tejus.loha 918
        return responseEntity;
919
    }
33102 tejus.loha 920
 
33143 tejus.loha 921
    @RequestMapping(value = "/schemePayoutReportDownload", method = RequestMethod.GET)
922
    public ResponseEntity<?> getSchemePayoutReportDownload(HttpServletRequest request,
923
                                                           @RequestParam(defaultValue = "0") int fofoId,
924
                                                           @RequestParam(name = "startDate") LocalDate startDate,
925
                                                           @RequestParam(name = "endDate") LocalDate endDate, Model model)
926
            throws Exception {
927
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 928
 
33143 tejus.loha 929
        List<List<?>> rows = new ArrayList<>();
33102 tejus.loha 930
 
33143 tejus.loha 931
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33102 tejus.loha 932
 
33143 tejus.loha 933
        List<SchemePayoutReportModel> schemePayoutReports = null;
934
        if (isAdmin) {
935
            if (fofoId == 0)
936
                schemePayoutReports = new ArrayList<>();
937
            else
938
                schemePayoutReports = fofoOrderRepository
939
                        .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
940
        } else {
941
            fofoId = fofoDetails.getFofoId();
942
            schemePayoutReports = fofoOrderRepository
943
                    .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
944
        }
945
        LOGGER.info("schemePayoutReports {}", schemePayoutReports);
33102 tejus.loha 946
 
33143 tejus.loha 947
        for (SchemePayoutReportModel spr : schemePayoutReports) {
33102 tejus.loha 948
 
33143 tejus.loha 949
            rows.add(Arrays.asList(spr.getId(), spr.getSerialNumber(), spr.getBrand(), spr.getModelName(),
950
                    spr.getModelNumber(), spr.getColor(), spr.getSchemeInDp(), spr.getSchemeOutDp(), spr.getSchemeId(),
33646 amit.gupta 951
                    spr.getName(), spr.getType(), spr.getAmount(), spr.getAmountType(), spr.getSioAmount(), spr.getPurchaseReference(),
33656 amit.gupta 952
                    spr.getInvoiceNumber(), spr.getStatus(), spr.getStatusDescription(),
33646 amit.gupta 953
                    FormattingUtils.formatDateTime(spr.getCreateTimestamp()), FormattingUtils.formatDateTime(spr.getRolledBackTimestamp())));
33102 tejus.loha 954
 
33143 tejus.loha 955
        }
33646 amit.gupta 956
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("Item Id",
957
                "Serial No", "Brand", "Model Name", "Model Number", "Color", "Scheme In Dp", "Scheme Out Dp",
33656 amit.gupta 958
                "Scheme Id", "Name", "Scheme Type", "Amount", "Amount Type", "Amount Paid", "Purchase Invoice", "Sale Invoice", "Status",
33646 amit.gupta 959
                "Description", "Created on", "Reversed On"), rows);
33102 tejus.loha 960
 
33143 tejus.loha 961
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Scheme Payout Summary Report");
33102 tejus.loha 962
 
33143 tejus.loha 963
        return responseEntity;
964
    }
33102 tejus.loha 965
 
966
 
33143 tejus.loha 967
    @RequestMapping(value = "/offerPayoutDumpReportDownload", method = RequestMethod.GET)
968
    public ResponseEntity<?> getOfferPayoutDumpReportDownload(HttpServletRequest request,
969
                                                              @RequestParam(defaultValue = "0") int fofoId,
970
                                                              @RequestParam(name = "startDate") LocalDate startDate,
971
                                                              @RequestParam(name = "endDate") LocalDate endDate, Model model)
972
            throws Exception {
973
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
974
        List<List<?>> rows = new ArrayList<>();
975
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
976
        List<OfferPayoutDumpReportModel> offerPayoutReports = null;
977
        if (isAdmin) {
978
            if (fofoId == 0)
979
                offerPayoutReports = new ArrayList<>();
980
            else
981
                offerPayoutReports = fofoOrderRepository
982
                        .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
983
        } else {
984
            fofoId = fofoDetails.getFofoId();
985
            offerPayoutReports = fofoOrderRepository
986
                    .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
987
        }
33102 tejus.loha 988
 
989
 
33143 tejus.loha 990
        for (OfferPayoutDumpReportModel opdr : offerPayoutReports) {
33102 tejus.loha 991
 
33143 tejus.loha 992
            rows.add(Arrays.asList(opdr.getId(), opdr.getBrand(), opdr.getModelName(),
993
                    opdr.getModelNumber(), opdr.getColor(), opdr.getSerialNumber(), opdr.getOfferId(),
994
                    opdr.getName(), opdr.getType(),
995
                    opdr.getSlabAmount(), opdr.getAmount(), opdr.getDescription(),
996
                    opdr.getCreateTimestamp(), opdr.getRejectTimestamp()));
33102 tejus.loha 997
 
33143 tejus.loha 998
        }
999
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("Id",
1000
                "Brand", "Model Name", "Model Number", "Color", "Serial number",
1001
                "Offer Id", "Name", "Type", "Slab Amount", "Amount",
1002
                "Description", "Credited On", "Rejected On"), rows);
33102 tejus.loha 1003
 
33143 tejus.loha 1004
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Offer Payout Summary Report");
33102 tejus.loha 1005
 
33143 tejus.loha 1006
        return responseEntity;
1007
    }
33102 tejus.loha 1008
 
1009
 
33143 tejus.loha 1010
    @GetMapping("/getAllOnlineOrder")
1011
    public String getAllOrders(HttpServletRequest request, @RequestParam(required = false) LocalDate date, Model model)
1012
            throws ProfitMandiBusinessException {
1013
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1014
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1015
        if (date == null) {
1016
            date = LocalDate.now().minusDays(3);
1017
        }
33102 tejus.loha 1018
 
33143 tejus.loha 1019
        LOGGER.info("date" + date);
1020
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1021
                .collect(Collectors.toList());
33102 tejus.loha 1022
 
33143 tejus.loha 1023
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
33102 tejus.loha 1024
 
33143 tejus.loha 1025
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1026
                .filter(x -> x != null).collect(Collectors.toList()).stream()
1027
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
33102 tejus.loha 1028
 
33143 tejus.loha 1029
        model.addAttribute("customRetailersMap", customRetailersMap);
33102 tejus.loha 1030
 
33143 tejus.loha 1031
        List<PendingOrderItem> pendingOrderItem = null;
33102 tejus.loha 1032
 
33143 tejus.loha 1033
        pendingOrderItem = pendingOrderItemRepository.selectAll(date.atStartOfDay(), LocalDateTime.now());
33102 tejus.loha 1034
 
33143 tejus.loha 1035
        Map<String, Object> map = pendingOrderService.getItemOrders(pendingOrderItem, 0);
33102 tejus.loha 1036
 
33143 tejus.loha 1037
        model.addAttribute("pendingOrderItem", map.get("pendingOrderItem"));
1038
        model.addAttribute("partnerInventoryMap", map.get("partnerInventoryMap"));
1039
        model.addAttribute("date", date);
1040
        model.addAttribute("isAdmin", isAdmin);
1041
        return "online-all-order-item";
1042
    }
33102 tejus.loha 1043
 
33143 tejus.loha 1044
 
1045
    @RequestMapping(value = "/reports", method = RequestMethod.GET)
1046
    public String reports(HttpServletRequest httpServletRequest, Model model) throws ProfitMandiBusinessException, UnsupportedOperationException, IOException {
1047
        //LoginDetails loginDetails = cookiesProcessor.getCookiesObject(httpServletRequest);
1048
        Map<ReporticoProject, List<ReporticoUrlInfo>> returnMap = ReporticoProject.reporticoProjectMap;
28137 amit.gupta 1049
		/*if(fofoStoreRepository.getWarehousePartnerMap().get(7720).stream().filter(x->x.getId()==loginDetails.getFofoId()).count() > 0) {
28106 amit.gupta 1050
			Map<ReporticoProject, List<ReporticoUrlInfo>> returnMap1 = new HashMap<ReporticoProject, List<ReporticoUrlInfo>>();
1051
			returnMap1.put(ReporticoProject.FOCO, returnMap.get(ReporticoProject.FOCO));
1052
			returnMap1.put(ReporticoProject.FOCOR, returnMap.get(ReporticoProject.FOCOR).stream().skip(1).collect(Collectors.toList()));
28107 amit.gupta 1053
			returnMap = returnMap1;
28137 amit.gupta 1054
		}*/
33143 tejus.loha 1055
        model.addAttribute("reporticoProjectMap", returnMap);
1056
        return "reports";
1057
    }
33775 ranu 1058
 
1059
    @RequestMapping(value = "/account-statement", method = RequestMethod.GET)
1060
    public String accountStatement(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
1061
                                   @RequestParam(required = false) LocalDate startDate,
1062
                                   @RequestParam(required = false) LocalDate endDate)
1063
            throws Exception {
1064
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1065
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1066
 
1067
        model.addAttribute("isAdmin", isAdmin);
1068
 
1069
        return "partner-account-statement";
1070
 
1071
    }
1072
 
1073
    @RequestMapping(value = "/account-statement-report", method = RequestMethod.GET)
1074
    public String getPartnerAccountStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
1075
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
1076
        if (fofoId > 0) {
1077
            if (!isAdmin) {
1078
                throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
1079
            }
1080
        } else {
1081
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1082
        }
1083
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
1084
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
1085
        UserWallet uw = walletService.getUserWallet(fofoId);
1086
        LOGGER.info("Start date - {}, end Date - {}", startDate, endDate);
1087
 
1088
        List<UserWalletHistory> history = userWalletHistoryRepository.selectPaginatedByWalletId(uw.getId(), startDate, endDate, 0, 0);
1089
 
1090
        history = history.stream().filter(x -> !x.getReferenceType().equals(WalletReferenceType.PURCHASE))
1091
                .filter(x -> !WalletService.CN_WALLET_REFERENCES.contains(x.getReferenceType())).sorted(Comparator.comparing(UserWalletHistory::getId)).collect(Collectors.toList());
1092
        Map<LocalDate, List<UserWalletHistory>> dateWalletMap = history.stream().collect(Collectors.groupingBy(x -> x.getTimestamp().toLocalDate()));
1093
        CustomRetailer customRetailer = retailerService.getAllFofoRetailers().get(fofoId);
1094
        List<StatementDetailModel> billedStatementDetails = orderRepository.selectDetailsBetween(fofoId, startDate, endDate);
1095
        Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate, Optional.of(fofoId));
1096
        Map<Integer, Float> closingAmountMap = transactionService.getPendingIndentValueMap(endDate, Optional.of(fofoId));
1097
 
1098
        float openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
1099
        float closingPendingAmount = closingAmountMap.get(fofoId) == null ? 0 : closingAmountMap.get(fofoId);
1100
        LOGGER.info("Opening - {}, Closing - {}", openingPendingAmount, closingPendingAmount);
1101
 
1102
        double grandTotalDebit = 0;
1103
        double grandTotalCredit = 0;
1104
 
1105
        for (UserWalletHistory walletEntry : history) {
1106
            if (walletEntry.getAmount() < 0) {
1107
                grandTotalDebit += Math.abs(walletEntry.getAmount());
1108
            } else {
1109
                grandTotalCredit += walletEntry.getAmount();
1110
            }
1111
        }
1112
 
1113
        for (StatementDetailModel statement : billedStatementDetails) {
1114
            if (statement.getAmount() < 0) {
1115
                grandTotalCredit += Math.abs(statement.getAmount());
1116
            } else {
1117
                grandTotalDebit += statement.getAmount();
1118
            }
1119
        }
1120
 
1121
        model.addAttribute("billedStatementDetails", billedStatementDetails);
1122
        model.addAttribute("customRetailer", customRetailer);
1123
        model.addAttribute("wallethistory", history);
1124
        model.addAttribute("startDate", startDate);
1125
        model.addAttribute("endDate", endDate);
1126
        model.addAttribute("dateWalletMap", dateWalletMap);
1127
        model.addAttribute("openingBalance", (openingBalance + openingPendingAmount));
1128
        model.addAttribute("closingBalance", (closingBalance + closingPendingAmount));
1129
        model.addAttribute("grandTotalDebit", grandTotalDebit);
1130
        model.addAttribute("grandTotalCredit", grandTotalCredit);
1131
 
1132
        return "account-statement-list";
1133
    }
33809 ranu 1134
 
1135
    @RequestMapping(value = "/loan/loan-statement", method = RequestMethod.GET)
33814 ranu 1136
    public String loanStatement(HttpServletRequest request, Model model)
33809 ranu 1137
            throws Exception {
1138
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1139
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1140
 
1141
        model.addAttribute("isAdmin", isAdmin);
1142
 
1143
        return "partner-loan-statement";
1144
 
1145
    }
1146
 
1147
    @RequestMapping(value = "/loan/partner-loan-statement-report", method = RequestMethod.GET)
1148
    public String partnerLoanStatement(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
1149
                                       @RequestParam(required = false) LocalDateTime startDate,
1150
                                       @RequestParam(required = false) LocalDateTime endDate)
1151
            throws Exception {
1152
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1153
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1154
        int partnerId = 0;
1155
 
1156
        if (fofoId > 0) {
1157
            partnerId = fofoId;
1158
        } else {
1159
            partnerId = loginDetails.getFofoId();
1160
        }
1161
 
1162
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(partnerId);
1163
 
1164
        List<LoanStatementReportModel> loanStatementReportModels = loanStatementRepository.selectByDatesAndStoreCode(startDate, endDate, fofoStore.getCode());
1165
 
1166
        model.addAttribute("isAdmin", isAdmin);
1167
        model.addAttribute("loanStatementReportModels", loanStatementReportModels);
1168
 
1169
        return "partner-loan-statement-summary";
1170
 
1171
    }
1172
 
1173
    @RequestMapping(value = "/loan/download-partner-loan-statement-report", method = RequestMethod.GET)
1174
    public ResponseEntity<?> downloadPartnerLoanStatement(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
1175
                                                          @RequestParam(required = false) LocalDateTime startDate,
1176
                                                          @RequestParam(required = false) LocalDateTime endDate)
1177
            throws Exception {
1178
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1179
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1180
 
1181
        int partnerId = 0;
1182
 
1183
        if (fofoId > 0) {
1184
            partnerId = fofoId;
1185
        } else {
1186
            partnerId = loginDetails.getFofoId();
1187
        }
1188
 
1189
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(partnerId);
1190
 
1191
        List<List<?>> rows = new ArrayList<>();
1192
 
1193
        List<LoanStatementReportModel> loanStatementReportModels = loanStatementRepository.selectByDatesAndStoreCode(startDate, endDate, fofoStore.getCode());// Extract the store name from the first loan statement
1194
        String storeName = loanStatementReportModels.get(0).getStoreName();
1195
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
1196
        for (LoanStatementReportModel loanStatement : loanStatementReportModels) {
1197
            rows.add(Arrays.asList(
1198
                    loanStatement.getCode(),  // Code
1199
                    String.valueOf(loanStatement.getId()),  // ID (convert int to string)
1200
                    loanStatement.getStoreName(),  // Store Name
1201
                    loanStatement.getState(),  // State
1202
                    loanStatement.getZone(),  // Zone
1203
                    loanStatement.getArea(),  // Area
1204
                    loanStatement.getTerritory(),  // Territory
1205
                    String.valueOf(loanStatement.getLoanId()),  // Loan ID
1206
                    loanStatement.getInterestRate().toString(),  // Interest Rate (BigDecimal to String)
1207
                    loanStatement.getIntialAmount().toString(),  // Initial Amount (BigDecimal to String)
1208
                    loanStatement.getPendingAmount().toString(),  // Pending Amount (BigDecimal to String)
1209
                    loanStatement.getCreatedOn().format(dateTimeFormatter),  // Created On (format LocalDateTime)
1210
                    loanStatement.getDueDate().format(dateTimeFormatter),  // Due Date (format LocalDateTime)
1211
                    loanStatement.getInterestAccrued().toString(),  // Interest Accrued (BigDecimal to String)
1212
                    loanStatement.getInterestPaid().toString(),  // Interest Paid (BigDecimal to String)
1213
                    String.valueOf(loanStatement.getFreeDays()),  // Free Days (convert int to string)
1214
                    loanStatement.getLoanReferenceType().toString(),  // Loan Reference Type (enum or string)
1215
                    loanStatement.getAmount().toString(),  // Amount (BigDecimal to String)
1216
                    loanStatement.getBusinessDate().format(dateTimeFormatter),  // Business Date (format LocalDateTime)
1217
                    loanStatement.getCreatedAt().format(dateTimeFormatter),  // Created At (format LocalDateTime)
1218
                    loanStatement.getDescription(),  // Description
1219
                    loanStatement.getStatus()  // Status (calculated value)
1220
            ));
1221
        }
1222
 
1223
        // Set up the headers and create the CSV
1224
        List<String> headers = Arrays.asList("Code", "ID", "Store Name", "State", "Zone", "Area", "Territory", "Loan ID",
1225
                "Interest Rate", "Initial Amount", "Pending Amount", "Created On", "Due Date",
1226
                "Interest Accrued", "Interest Paid", "Free Days", "Loan Reference Type",
1227
                "Amount", "Business Date", "Created At", "Description", "Status");
1228
 
1229
        // Create the CSV byte stream
1230
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
1231
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Partner Loan Summary Report");
1232
 
1233
        return responseEntity;
1234
 
1235
    }
23612 amit.gupta 1236
}