Subversion Repositories SmartDukaan

Rev

Rev 33816 | Rev 34066 | 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());
33815 ranu 370
        float openingBalance = 0;
371
        float openingPendingAmount = 0;
33143 tejus.loha 372
        List<WalletSummaryReportModel> walletSummartList = null;
373
        if (isAdmin) {
374
            if (fofoId == 0)
375
                walletSummartList = new ArrayList<>();
376
            else
33815 ranu 377
 
33143 tejus.loha 378
                walletSummartList = fofoOrderRepository.selectWalletSummaryReport(
379
                        fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33815 ranu 380
            openingBalance = walletService.getOpeningTill(fofoId, startDate.atStartOfDay());
381
            Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate.atStartOfDay(), Optional.of(fofoId));
382
            openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
383
 
33143 tejus.loha 384
        } else {
33102 tejus.loha 385
 
33143 tejus.loha 386
            walletSummartList = fofoOrderRepository.selectWalletSummaryReport(
387
                    fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33815 ranu 388
 
389
 
33143 tejus.loha 390
        }
33815 ranu 391
 
33143 tejus.loha 392
        LOGGER.info("walletSummartList {}", fofoId);
393
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
394
        String partnerDetail = null;
33815 ranu 395
// Headers for the table data
34011 tejus.loha 396
        rows.add(Arrays.asList("Id", "Amount", "Refundable_amount", "Reference", "Reference_type", "Running Balance", "Business_timestamp", "timestamp", "Description"));
33143 tejus.loha 397
        for (WalletSummaryReportModel walletSummary : walletSummartList) {
398
            partnerDetail = walletSummary.getName() + "(" + walletSummary.getCode() + "-" + walletSummary.getPhone() + ")" + "-" + walletSummary.getEmail();
33102 tejus.loha 399
 
33143 tejus.loha 400
            rows.add(Arrays.asList(
401
                    walletSummary.getId(),
402
                    walletSummary.getAmount(),
403
                    walletSummary.getRefundableAmount(),
404
                    walletSummary.getReference(),
405
                    walletSummary.getReferenceType(),
33815 ranu 406
                    openingBalance + walletSummary.getAmount(),
407
                    FormattingUtils.format(walletSummary.getBusinessTimestamp() != null ? walletSummary.getBusinessTimestamp() : walletSummary.getTimestamp()),
34011 tejus.loha 408
                    walletSummary.getTimestamp(),
33143 tejus.loha 409
                    walletSummary.getDescription()
410
            ));
33102 tejus.loha 411
 
33143 tejus.loha 412
        }
33102 tejus.loha 413
 
33815 ranu 414
 
415
        float openingBalanceWithOpeningPendingAmount = openingPendingAmount + openingBalance;
33143 tejus.loha 416
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
33816 ranu 417
                .getCSVByteStream(Arrays.asList("Opening Balance - : " + openingBalanceWithOpeningPendingAmount), rows);
33143 tejus.loha 418
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, partnerDetail + " Wallet Statement Report");
33102 tejus.loha 419
 
33143 tejus.loha 420
        return responseEntity;
33102 tejus.loha 421
 
33143 tejus.loha 422
    }
33102 tejus.loha 423
 
33143 tejus.loha 424
    @RequestMapping(value = "/walletSummaryFetchReportByDate", method = RequestMethod.GET)
425
    public String getwalletSummaryFetchReport(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
426
                                              @RequestParam(required = false) LocalDate startDate,
427
                                              @RequestParam(required = false) LocalDate endDate)
428
            throws Exception {
429
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
430
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
431
        if (startDate == null) {
432
            startDate = LocalDate.now().minusDays(30);
433
        }
34011 tejus.loha 434
        if (endDate == null) {
435
            endDate = LocalDate.now();
436
        }
437
        List<WalletSummaryReportModel> walletSummartList = new ArrayList<>();
438
        float openingBalance = 0;
439
        float openingPendingAmount = 0;
33143 tejus.loha 440
        if (isAdmin) {
34011 tejus.loha 441
            if (fofoId > 0) {
442
                openingBalance = walletService.getOpeningTill(fofoId, startDate.atStartOfDay());
33815 ranu 443
                Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate.atStartOfDay(), Optional.of(fofoId));
34011 tejus.loha 444
                openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
445
                walletSummartList = fofoOrderRepository.selectWalletSummaryReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
446
                LOGGER.info("startDate - " + startDate.atStartOfDay());
447
                LOGGER.info("endDate - " + endDate.atTime(LocalTime.MAX));
33143 tejus.loha 448
            }
449
        } else {
34011 tejus.loha 450
            walletSummartList = fofoOrderRepository.selectWalletSummaryReport(loginDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33143 tejus.loha 451
        }
34011 tejus.loha 452
        LOGGER.info("walletSummartList {}", walletSummartList);
453
        model.addAttribute("walletSummartList", walletSummartList);
454
        model.addAttribute("openingBalance", (openingBalance + openingPendingAmount));
455
        model.addAttribute("startDate", startDate);
456
        model.addAttribute("endDate", endDate);
457
        model.addAttribute("isAdmin", isAdmin);
458
        return "wallet-summary-report";
33143 tejus.loha 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());
34011 tejus.loha 465
        LocalDateTime startDate = LocalDateTime.now().minusDays(30);
466
        LocalDateTime endDate = LocalDateTime.now();
467
        List<WalletSummaryReportModel> walletSummartList = new ArrayList<>();
468
        if (!isAdmin) {
469
            walletSummartList = fofoOrderRepository
470
                    .selectWalletSummaryReport(fofoDetails.getFofoId(), startDate, endDate);
471
        }
33143 tejus.loha 472
        LOGGER.info("walletSummartList {}", walletSummartList);
34011 tejus.loha 473
        model.addAttribute("startDate", startDate.toLocalDate());
474
        model.addAttribute("endDate", endDate.toLocalDate());
33143 tejus.loha 475
        model.addAttribute("walletSummartList", walletSummartList);
476
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 477
 
33143 tejus.loha 478
        return "wallet-summary-report";
479
    }
33102 tejus.loha 480
 
33143 tejus.loha 481
    @RequestMapping(value = "/pendingIndentReport", method = RequestMethod.GET)
482
    public String getPendingIndentReport(HttpServletRequest request, Model model) throws Exception {
483
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
484
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33102 tejus.loha 485
 
33143 tejus.loha 486
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
487
        LocalDateTime currentStartMonth = currentDate.minusMonths(2).toLocalDate().atStartOfDay();
33102 tejus.loha 488
 
33143 tejus.loha 489
        List<PendingIndentReportModel> pendingIndentReports = fofoOrderRepository
490
                .selectPendingIndentReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
491
        LOGGER.info("pendingIndentReports {}", pendingIndentReports);
33102 tejus.loha 492
 
33143 tejus.loha 493
        model.addAttribute("startDate", currentDate.minusMonths(2).toLocalDate());
494
        model.addAttribute("endDate", LocalDate.now());
495
        model.addAttribute("pendingIndentReports", pendingIndentReports);
496
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 497
 
498
 
33143 tejus.loha 499
        return "pending-indent-report";
500
    }
33102 tejus.loha 501
 
33143 tejus.loha 502
    @RequestMapping(value = "/pendingIndentFetchReportByDate", method = RequestMethod.GET)
503
    public String getpendingIndentFetchReport(
504
            HttpServletRequest request,
505
            @RequestParam(defaultValue = "0") int fofoId,
506
            @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
507
            @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate,
508
            Model model
509
    ) throws Exception {
510
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
511
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
512
        if (startDate == null) {
513
            startDate = LocalDate.now().minusDays(30);
514
            endDate = LocalDate.now();
515
        }
516
        model.addAttribute("startDate", startDate);
517
        model.addAttribute("endDate", endDate);
518
        model.addAttribute("isAdmin", isAdmin);
519
        if (isAdmin) {
520
            if (fofoId == 0) {
521
                model.addAttribute("pendingIndentReports", new ArrayList<>());
522
                return "pending-indent-report";
523
            } else {
524
                List<PendingIndentReportModel> pendingIndentReports = fofoOrderRepository
525
                        .selectPendingIndentReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
526
                model.addAttribute("pendingIndentReports", pendingIndentReports);
527
                return "pending-indent-report";
528
            }
529
        } else {
530
            LocalDateTime currentDate = LocalDate.now().atStartOfDay();
531
            List<PendingIndentReportModel> pendingIndentReports = fofoOrderRepository
532
                    .selectPendingIndentReport(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
533
            model.addAttribute("pendingIndentReports", pendingIndentReports);
534
            return "pending-indent-report";
33102 tejus.loha 535
 
33143 tejus.loha 536
        }
537
    }
33102 tejus.loha 538
 
539
 
33143 tejus.loha 540
    @RequestMapping(value = "/pendingIndentReportDownload", method = RequestMethod.GET)
541
    public ResponseEntity<?> getPendingIndentReportDownload(HttpServletRequest request,
542
                                                            @RequestParam(defaultValue = "0") int fofoId,
543
                                                            @RequestParam(name = "startDate") LocalDate startDate,
544
                                                            @RequestParam(name = "endDate") LocalDate endDate, Model model)
545
            throws Exception {
546
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
547
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33102 tejus.loha 548
        /*LocalDateTime currentDate = LocalDate.now().atStartOfDay();
549
        LocalDateTime currentStartMonth = currentDate.minusMonths(2).toLocalDate().atStartOfDay();*/
33143 tejus.loha 550
        List<PendingIndentReportModel> pendingIndentReports = null;
551
        List<List<?>> rows = new ArrayList<>();
552
        if (isAdmin) {
553
            if (fofoId == 0)
554
                pendingIndentReports = new ArrayList<>();
555
            else
556
                pendingIndentReports = fofoOrderRepository
557
                        .selectPendingIndentReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
558
        } else {
559
            pendingIndentReports = fofoOrderRepository
560
                    .selectPendingIndentReport(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 561
 
33143 tejus.loha 562
        }
563
        LOGGER.info("pendingIndentReports {}", pendingIndentReports);
564
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
33102 tejus.loha 565
 
33143 tejus.loha 566
        for (PendingIndentReportModel pir : pendingIndentReports) {
33102 tejus.loha 567
 
33143 tejus.loha 568
            rows.add(Arrays.asList(pir.getTransactionId(), pir.getOrderId(),
569
                    pir.getCreatTimestamp().format(dateTimeFormatter), pir.getItemId(), pir.getBrand(),
570
                    pir.getModelName(), pir.getModelNumber(), pir.getColor(), pir.getQuantity(), pir.getUnitPrice(),
571
                    pir.getWalletAmount(), pir.getStatus(), pir.getInvoiceNumber(),
572
                    pir.getBillingTimestamp() == null ? "" : pir.getBillingTimestamp().format(dateTimeFormatter)));
33102 tejus.loha 573
 
33143 tejus.loha 574
        }
33102 tejus.loha 575
 
33143 tejus.loha 576
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList(
577
                "Transaction Id", "Order Id", "Created_At", "Item_Id", "Brand", "Model Name", "Model Number", "Color",
578
                "Quantity", "Unit Price", "Wallet Deduction", "Status", "Invoice Number", "Billing Timestamp"), rows);
33102 tejus.loha 579
 
33143 tejus.loha 580
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Order Status Summary Report");
33102 tejus.loha 581
 
33143 tejus.loha 582
        return responseEntity;
583
    }
33102 tejus.loha 584
 
33143 tejus.loha 585
    @RequestMapping(value = "/schemePayoutReport", method = RequestMethod.GET)
586
    public String getschemePayoutReport(HttpServletRequest request, Model model,
587
                                        @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate)
588
            throws ProfitMandiBusinessException {
33102 tejus.loha 589
 
33143 tejus.loha 590
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
591
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
592
        if (startDate == null) {
593
            startDate = LocalDate.now().minusDays(30);
594
            endDate = LocalDate.now();
595
        }
596
        model.addAttribute("startDate", startDate);
597
        model.addAttribute("endDate", endDate);
598
        model.addAttribute("isAdmin", isAdmin);
599
        //LOGGER.info("schemePayoutReports {}", schemePayoutReports);
600
        List<SchemePayoutReportModel> schemePayoutReports = fofoOrderRepository
601
                .selectSchemePayoutReport(loginDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
602
        model.addAttribute("schemePayoutReports", schemePayoutReports);
603
        return "scheme-payout-report";
33102 tejus.loha 604
 
33143 tejus.loha 605
    }
33102 tejus.loha 606
 
33143 tejus.loha 607
    @RequestMapping(value = "/schemePayoutFetchReportByDate", method = RequestMethod.GET)
608
    public String getschemePayoutFetchReportByDate(
609
            HttpServletRequest request,
610
            Model model,
611
            @RequestParam(defaultValue = "0") int fofoId,
612
            @RequestParam(required = false) LocalDate startDate,
613
            @RequestParam(required = false) LocalDate endDate)
614
            throws ProfitMandiBusinessException {
615
        //LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
616
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
617
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
618
        if (startDate == null) {
619
            startDate = LocalDate.now().minusDays(30);
620
            endDate = LocalDate.now();
621
        }
622
        model.addAttribute("startDate", startDate);
623
        model.addAttribute("endDate", endDate);
624
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 625
 
33143 tejus.loha 626
        LOGGER.info("q {}, starDate - {}, endDate - {}", fofoId, startDate, endDate);
627
        if (isAdmin) {
628
            if (fofoId == 0) {
629
                //No need to pull any data
630
                model.addAttribute("schemePayoutReports", new ArrayList<>());
631
                return "scheme-payout-report";
33102 tejus.loha 632
 
33143 tejus.loha 633
            } else {
634
                List<SchemePayoutReportModel> schemePayoutReports = fofoOrderRepository
635
                        .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 636
 
33143 tejus.loha 637
                model.addAttribute("schemePayoutReports", schemePayoutReports);
638
                return "scheme-payout-report";
639
            }
640
        } else {
641
            fofoId = loginDetails.getFofoId();
33102 tejus.loha 642
 
33143 tejus.loha 643
            List<SchemePayoutReportModel> schemePayoutReports = fofoOrderRepository
644
                    .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 645
 
33143 tejus.loha 646
            model.addAttribute("schemePayoutReports", schemePayoutReports);
647
            return "scheme-payout-report";
648
        }
33102 tejus.loha 649
 
33143 tejus.loha 650
    }
33102 tejus.loha 651
 
33143 tejus.loha 652
    @RequestMapping(value = "/offerPayoutReport", method = RequestMethod.GET)
653
    public String getOfferPayoutReport(HttpServletRequest request, Model model, @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate) throws Exception {
654
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
655
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33102 tejus.loha 656
 
33143 tejus.loha 657
        if (startDate == null) {
658
            startDate = LocalDate.now().minusDays(30);
659
            endDate = LocalDate.now();
660
        }
661
        model.addAttribute("startDate", startDate);
662
        model.addAttribute("endDate", endDate);
33102 tejus.loha 663
 
664
 
33143 tejus.loha 665
        List<OfferPayoutDumpReportModel> offerPayoutDumpReports = fofoOrderRepository
666
                .selectOfferPayoutDumpReport(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
667
        LOGGER.info("offerPayoutDumpReports {}", offerPayoutDumpReports);
33102 tejus.loha 668
 
33143 tejus.loha 669
        model.addAttribute("offerPayoutDumpReports", offerPayoutDumpReports);
670
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 671
 
33143 tejus.loha 672
        return "offer-payout-dump-report";
673
    }
33102 tejus.loha 674
 
33143 tejus.loha 675
    @RequestMapping(value = "/offerPayoutFetchReportByDate", method = RequestMethod.GET)
676
    public String getofferPayoutFetchReportByDate(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
677
                                                  @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate)
678
            throws ProfitMandiBusinessException {
33102 tejus.loha 679
 
33143 tejus.loha 680
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
681
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
682
        if (startDate == null) {
683
            startDate = LocalDate.now().minusDays(30);
684
            endDate = LocalDate.now();
685
        }
686
        model.addAttribute("startDate", startDate);
687
        model.addAttribute("endDate", endDate);
688
        model.addAttribute("isAdmin", isAdmin);
689
        LOGGER.info("q {}, starDate - {}, endDate - {}", fofoId, startDate, endDate);
690
        if (isAdmin) {
691
            if (fofoId == 0) {
692
                //No need to pull any data
693
                model.addAttribute("offerPayoutReports", new ArrayList<>());
694
                return "offer-payout-dump-report";
33102 tejus.loha 695
 
33143 tejus.loha 696
            } else {
697
                List<OfferPayoutDumpReportModel> offerPayoutDumpReports = fofoOrderRepository
698
                        .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 699
 
33143 tejus.loha 700
                model.addAttribute("offerPayoutDumpReports", offerPayoutDumpReports);
33102 tejus.loha 701
 
702
 
33143 tejus.loha 703
                return "offer-payout-dump-report";
33102 tejus.loha 704
 
33143 tejus.loha 705
            }
706
        } else {
707
            fofoId = loginDetails.getFofoId();
708
            List<OfferPayoutDumpReportModel> offerPayoutDumpReports = fofoOrderRepository
709
                    .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 710
 
33143 tejus.loha 711
            model.addAttribute("offerPayoutDumpReports", offerPayoutDumpReports);
33102 tejus.loha 712
 
713
 
33143 tejus.loha 714
            return "offer-payout-dump-report";
715
        }
716
    }
33102 tejus.loha 717
 
718
 
33143 tejus.loha 719
    @RequestMapping(value = "/selectPartnerBillingSummaryReport", method = RequestMethod.GET)
720
    public String getselectPartnerBillingSummaryReport(HttpServletRequest request, Model model) throws Exception {
721
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 722
 
33143 tejus.loha 723
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
724
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 725
 
33143 tejus.loha 726
        List<PartnerBillingSummaryModel> partnerBillingSummaryReports = fofoOrderRepository
727
                .selectPartnerBillingSummaryReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
33102 tejus.loha 728
 
33143 tejus.loha 729
        model.addAttribute("startDate", currentDate.minusMonths(3).toLocalDate());
730
        model.addAttribute("endDate", LocalDate.now());
731
        model.addAttribute("partnerBillingSummaryReports", partnerBillingSummaryReports);
33102 tejus.loha 732
 
33143 tejus.loha 733
        return "partner-billing-summary-report";
734
    }
33102 tejus.loha 735
 
33143 tejus.loha 736
    @RequestMapping(value = "/priceDropReport", method = RequestMethod.GET)
737
    public String getSelectPriceDropReport(HttpServletRequest request, @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
738
                                           @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate, Model model) throws Exception {
739
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
740
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
741
        if (startDate == null) {
742
            startDate = LocalDate.now().minusDays(30);
743
            endDate = LocalDate.now();
744
        }
745
        model.addAttribute("startDate", startDate);
746
        model.addAttribute("endDate", endDate);
747
        model.addAttribute("isAdmin", isAdmin);
748
        List<PriceDropReportModel> priceDropReports = orderRepository.selectPriceDropReport(fofoDetails.getFofoId(),
749
                startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 750
 
33143 tejus.loha 751
        model.addAttribute("priceDropReports", priceDropReports);
33102 tejus.loha 752
 
33143 tejus.loha 753
        return "price-drop-report";
754
    }
33102 tejus.loha 755
 
33143 tejus.loha 756
    @RequestMapping(value = "/priceDropFetchReportByDate", method = RequestMethod.GET)
757
    public String getpriceDropFetchReportByDate(HttpServletRequest request,
758
                                                @RequestParam(defaultValue = "0") int fofoId,
759
                                                @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
760
                                                @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate, Model model)
761
            throws Exception {
33102 tejus.loha 762
 
33143 tejus.loha 763
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
764
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
765
        if (startDate == null) {
766
            startDate = LocalDate.now().minusDays(30);
767
            endDate = LocalDate.now();
768
        }
769
        model.addAttribute("startDate", startDate);
770
        model.addAttribute("endDate", endDate);
771
        model.addAttribute("isAdmin", isAdmin);
772
        if (isAdmin) {
773
            if (fofoId == 0) {
774
                model.addAttribute("priceDropReports", new ArrayList<>());
775
                return "price-drop-report";
776
            } else {
777
                List<PriceDropReportModel> priceDropReports = orderRepository.selectPriceDropReport(fofoId,
778
                        startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
779
                model.addAttribute("priceDropReports", priceDropReports);
780
                return "price-drop-report";
781
            }
33102 tejus.loha 782
 
33143 tejus.loha 783
        } else {
784
            List<PriceDropReportModel> priceDropReports = orderRepository.selectPriceDropReport(fofoDetails.getFofoId(),
785
                    startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
786
            model.addAttribute("priceDropReports", priceDropReports);
787
            return "price-drop-report";
788
        }
789
    }
33102 tejus.loha 790
 
791
 
33143 tejus.loha 792
    @RequestMapping(value = "/downloadPriceDropReport", method = RequestMethod.GET)
793
    public ResponseEntity<?> getSelectDownloadPriceDropReport(HttpServletRequest request,
794
                                                              @RequestParam(defaultValue = "0") int fofoId,
795
                                                              @RequestParam(name = "startDate") LocalDate startDate,
796
                                                              @RequestParam(name = "endDate") LocalDate endDate, Model model)
797
            throws Exception {
798
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
799
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
800
        List<List<?>> rows = new ArrayList<>();
801
        List<PriceDropReportModel> priceDropReports = null;
802
        if (isAdmin) {
803
            if (fofoId == 0)
804
                priceDropReports = new ArrayList<>();
805
            else
806
                priceDropReports = orderRepository.selectPriceDropReport(fofoId,
807
                        startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
808
        } else {
809
            fofoId = fofoDetails.getFofoId();
810
            priceDropReports = orderRepository.selectPriceDropReport(fofoId,
811
                    startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
812
        }
813
        for (PriceDropReportModel pdr : priceDropReports) {
33102 tejus.loha 814
 
33143 tejus.loha 815
            rows.add(Arrays.asList(pdr.getCode(), pdr.getId(), pdr.getBrand(), pdr.getModelName(), pdr.getModelNumber(),
816
                    FormattingUtils.formatDate(pdr.getAffectedOn()), pdr.getAmount(), FormattingUtils.format(pdr.getCreditTimestamp()), pdr.getImei(), pdr.getStatus(),
817
                    FormattingUtils.format(pdr.getRejectedTimestamp()), pdr.getRejectionReason()));
33102 tejus.loha 818
 
33143 tejus.loha 819
        }
820
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
821
                .getCSVByteStream(Arrays.asList("code", "Price_Drop_Id", "brand", "model_name", "model_number",
822
                        "affected_on", "amount", "Credit Date", "Imei", "status", "Rejected Date", "Rejected Reason"), rows);
33102 tejus.loha 823
 
33143 tejus.loha 824
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "price drop report");
33102 tejus.loha 825
 
33143 tejus.loha 826
        return responseEntity;
33102 tejus.loha 827
 
33143 tejus.loha 828
    }
33102 tejus.loha 829
 
33143 tejus.loha 830
    @RequestMapping(value = "/downloadPartnerBillingSummaryReport", method = RequestMethod.GET)
831
    public ResponseEntity<?> getdownloadPartnerBillingSummaryReport(HttpServletRequest request,
832
                                                                    @RequestParam(name = "startDate") LocalDate startDate,
833
                                                                    @RequestParam(name = "endDate") LocalDate endDate, Model model)
834
            throws Exception {
33102 tejus.loha 835
 
33143 tejus.loha 836
        List<List<?>> rows = new ArrayList<>();
837
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 838
 
33143 tejus.loha 839
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
840
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 841
 
33143 tejus.loha 842
        List<PartnerBillingSummaryModel> partnerBillingSummaryReports = fofoOrderRepository
843
                .selectPartnerBillingSummaryReport(fofoDetails.getFofoId(), startDate.atStartOfDay(),
844
                        endDate.atTime(LocalTime.MAX));
33102 tejus.loha 845
 
33143 tejus.loha 846
        for (PartnerBillingSummaryModel pbsr : partnerBillingSummaryReports) {
33102 tejus.loha 847
 
33143 tejus.loha 848
            rows.add(Arrays.asList(pbsr.getId(),
849
                    FormattingUtils.format(pbsr.getCreateTimestamp()),
850
                    FormattingUtils.format(pbsr.getBillingTimestamp()),
851
                    FormattingUtils.format(pbsr.getDeliveryTimestamp()),
852
                    FormattingUtils.format(pbsr.getPartnerGrnTimestamp()),
853
                    pbsr.getTransactionId(),
854
                    pbsr.getLogisticsTransactionId(), pbsr.getAirwayBillNumber(), pbsr.getStatusSubGroup(),
855
                    pbsr.getStatusName(), pbsr.getRetailerId(), pbsr.getRetailerName(), pbsr.getItemId(),
856
                    pbsr.getBrand(), pbsr.getModelName(), pbsr.getModelNumber(), pbsr.getColor(), pbsr.getUnitPrice(),
857
                    pbsr.getQuantity(), pbsr.getTotalPrice(), pbsr.getInvoiceNumber(), pbsr.getSellerName(), pbsr.getGstNumber(), pbsr.getHsnCode(), pbsr.getIgstRate(),
858
                    pbsr.getCgstRate(), pbsr.getSgstRate()));
33102 tejus.loha 859
 
33143 tejus.loha 860
        }
33102 tejus.loha 861
 
33143 tejus.loha 862
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("OrderId",
863
                "Created On", "Billed On", "Delivered On", "Grned On", "Transaction_id", "master_order_id",
864
                "airwaybill_no", "statusSubGroupp", "statusName", "customer_id", "customer_name", "Item_Id", "brand",
865
                "model_name", "model_number", "color", "selling_price", "Quantity", "total_price", "invoice_number",
866
                "seller_name", "gst_number", "hsn_code", "igstrate", "cgstrate", "sgstrate"), rows);
33102 tejus.loha 867
 
33143 tejus.loha 868
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Billing Statement Report");
33102 tejus.loha 869
 
33143 tejus.loha 870
        return responseEntity;
33102 tejus.loha 871
 
872
 
33143 tejus.loha 873
    }
33102 tejus.loha 874
 
33143 tejus.loha 875
    @RequestMapping(value = "/invoiceSchemeOutSummaryReport", method = RequestMethod.GET)
876
    public String getInvoiceSchemeOutSummaryReport(HttpServletRequest request, Model model) throws Exception {
877
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 878
 
33143 tejus.loha 879
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
880
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 881
 
33143 tejus.loha 882
        List<FocoSchemeOutReportModel> focoSchemeOutReports = fofoOrderRepository
883
                .selectInvoiceSchemeOutSummaryReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
884
        LOGGER.info("focoSchemeOutReportModel {}", focoSchemeOutReports);
33102 tejus.loha 885
 
33143 tejus.loha 886
        model.addAttribute("startDate", currentDate.minusMonths(3).toLocalDate());
887
        model.addAttribute("endDate", LocalDate.now());
888
        model.addAttribute("focoSchemeOutReports", focoSchemeOutReports);
33102 tejus.loha 889
 
33143 tejus.loha 890
        return "invoicewise-scheme-out-report";
891
    }
33102 tejus.loha 892
 
33143 tejus.loha 893
    @RequestMapping(value = "/downloadInvoiceSchemeOutSummaryReport", method = RequestMethod.GET)
894
    public ResponseEntity<?> getDownloadInvoiceSchemeOutSummaryReport(HttpServletRequest request, Model model)
895
            throws Exception {
896
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 897
 
33143 tejus.loha 898
        List<List<?>> rows = new ArrayList<>();
899
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
900
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 901
 
33143 tejus.loha 902
        List<FocoSchemeOutReportModel> focoSchemeOutReports = fofoOrderRepository
903
                .selectInvoiceSchemeOutSummaryReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
904
        LOGGER.info("focoSchemeOutReportModel {}", focoSchemeOutReports);
33102 tejus.loha 905
 
33143 tejus.loha 906
        for (FocoSchemeOutReportModel fsor : focoSchemeOutReports) {
907
            rows.add(Arrays.asList(fsor.getInvoiceNumber(), fsor.getQuantity(), fsor.getBrand(), fsor.getModelName(),
908
                    fsor.getModelNumber(), fsor.getColor(), fsor.getAmount()));
33102 tejus.loha 909
 
33143 tejus.loha 910
        }
33102 tejus.loha 911
 
33143 tejus.loha 912
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
913
                Arrays.asList("InvoiceNumber", "Quantity", "Brand", "Model Name", "Model Number", "Color", "Amount"),
914
                rows);
33102 tejus.loha 915
 
33143 tejus.loha 916
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows,
917
                "invoice wise scheme out Summary Report");
33102 tejus.loha 918
 
33143 tejus.loha 919
        return responseEntity;
920
    }
33102 tejus.loha 921
 
33143 tejus.loha 922
    @RequestMapping(value = "/schemePayoutReportDownload", method = RequestMethod.GET)
923
    public ResponseEntity<?> getSchemePayoutReportDownload(HttpServletRequest request,
924
                                                           @RequestParam(defaultValue = "0") int fofoId,
925
                                                           @RequestParam(name = "startDate") LocalDate startDate,
926
                                                           @RequestParam(name = "endDate") LocalDate endDate, Model model)
927
            throws Exception {
928
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 929
 
33143 tejus.loha 930
        List<List<?>> rows = new ArrayList<>();
33102 tejus.loha 931
 
33143 tejus.loha 932
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33102 tejus.loha 933
 
33143 tejus.loha 934
        List<SchemePayoutReportModel> schemePayoutReports = null;
935
        if (isAdmin) {
936
            if (fofoId == 0)
937
                schemePayoutReports = new ArrayList<>();
938
            else
939
                schemePayoutReports = fofoOrderRepository
940
                        .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
941
        } else {
942
            fofoId = fofoDetails.getFofoId();
943
            schemePayoutReports = fofoOrderRepository
944
                    .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
945
        }
946
        LOGGER.info("schemePayoutReports {}", schemePayoutReports);
33102 tejus.loha 947
 
33143 tejus.loha 948
        for (SchemePayoutReportModel spr : schemePayoutReports) {
33102 tejus.loha 949
 
33143 tejus.loha 950
            rows.add(Arrays.asList(spr.getId(), spr.getSerialNumber(), spr.getBrand(), spr.getModelName(),
951
                    spr.getModelNumber(), spr.getColor(), spr.getSchemeInDp(), spr.getSchemeOutDp(), spr.getSchemeId(),
33646 amit.gupta 952
                    spr.getName(), spr.getType(), spr.getAmount(), spr.getAmountType(), spr.getSioAmount(), spr.getPurchaseReference(),
33656 amit.gupta 953
                    spr.getInvoiceNumber(), spr.getStatus(), spr.getStatusDescription(),
33646 amit.gupta 954
                    FormattingUtils.formatDateTime(spr.getCreateTimestamp()), FormattingUtils.formatDateTime(spr.getRolledBackTimestamp())));
33102 tejus.loha 955
 
33143 tejus.loha 956
        }
33646 amit.gupta 957
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("Item Id",
958
                "Serial No", "Brand", "Model Name", "Model Number", "Color", "Scheme In Dp", "Scheme Out Dp",
33656 amit.gupta 959
                "Scheme Id", "Name", "Scheme Type", "Amount", "Amount Type", "Amount Paid", "Purchase Invoice", "Sale Invoice", "Status",
33646 amit.gupta 960
                "Description", "Created on", "Reversed On"), rows);
33102 tejus.loha 961
 
33143 tejus.loha 962
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Scheme Payout Summary Report");
33102 tejus.loha 963
 
33143 tejus.loha 964
        return responseEntity;
965
    }
33102 tejus.loha 966
 
967
 
33143 tejus.loha 968
    @RequestMapping(value = "/offerPayoutDumpReportDownload", method = RequestMethod.GET)
969
    public ResponseEntity<?> getOfferPayoutDumpReportDownload(HttpServletRequest request,
970
                                                              @RequestParam(defaultValue = "0") int fofoId,
971
                                                              @RequestParam(name = "startDate") LocalDate startDate,
972
                                                              @RequestParam(name = "endDate") LocalDate endDate, Model model)
973
            throws Exception {
974
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
975
        List<List<?>> rows = new ArrayList<>();
976
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
977
        List<OfferPayoutDumpReportModel> offerPayoutReports = null;
978
        if (isAdmin) {
979
            if (fofoId == 0)
980
                offerPayoutReports = new ArrayList<>();
981
            else
982
                offerPayoutReports = fofoOrderRepository
983
                        .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
984
        } else {
985
            fofoId = fofoDetails.getFofoId();
986
            offerPayoutReports = fofoOrderRepository
987
                    .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
988
        }
33102 tejus.loha 989
 
990
 
33143 tejus.loha 991
        for (OfferPayoutDumpReportModel opdr : offerPayoutReports) {
33102 tejus.loha 992
 
33143 tejus.loha 993
            rows.add(Arrays.asList(opdr.getId(), opdr.getBrand(), opdr.getModelName(),
994
                    opdr.getModelNumber(), opdr.getColor(), opdr.getSerialNumber(), opdr.getOfferId(),
995
                    opdr.getName(), opdr.getType(),
996
                    opdr.getSlabAmount(), opdr.getAmount(), opdr.getDescription(),
997
                    opdr.getCreateTimestamp(), opdr.getRejectTimestamp()));
33102 tejus.loha 998
 
33143 tejus.loha 999
        }
1000
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("Id",
1001
                "Brand", "Model Name", "Model Number", "Color", "Serial number",
1002
                "Offer Id", "Name", "Type", "Slab Amount", "Amount",
1003
                "Description", "Credited On", "Rejected On"), rows);
33102 tejus.loha 1004
 
33143 tejus.loha 1005
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Offer Payout Summary Report");
33102 tejus.loha 1006
 
33143 tejus.loha 1007
        return responseEntity;
1008
    }
33102 tejus.loha 1009
 
1010
 
33143 tejus.loha 1011
    @GetMapping("/getAllOnlineOrder")
1012
    public String getAllOrders(HttpServletRequest request, @RequestParam(required = false) LocalDate date, Model model)
1013
            throws ProfitMandiBusinessException {
1014
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1015
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1016
        if (date == null) {
1017
            date = LocalDate.now().minusDays(3);
1018
        }
33102 tejus.loha 1019
 
33143 tejus.loha 1020
        LOGGER.info("date" + date);
1021
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1022
                .collect(Collectors.toList());
33102 tejus.loha 1023
 
33143 tejus.loha 1024
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
33102 tejus.loha 1025
 
33143 tejus.loha 1026
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1027
                .filter(x -> x != null).collect(Collectors.toList()).stream()
1028
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
33102 tejus.loha 1029
 
33143 tejus.loha 1030
        model.addAttribute("customRetailersMap", customRetailersMap);
33102 tejus.loha 1031
 
33143 tejus.loha 1032
        List<PendingOrderItem> pendingOrderItem = null;
33102 tejus.loha 1033
 
33143 tejus.loha 1034
        pendingOrderItem = pendingOrderItemRepository.selectAll(date.atStartOfDay(), LocalDateTime.now());
33102 tejus.loha 1035
 
33143 tejus.loha 1036
        Map<String, Object> map = pendingOrderService.getItemOrders(pendingOrderItem, 0);
33102 tejus.loha 1037
 
33143 tejus.loha 1038
        model.addAttribute("pendingOrderItem", map.get("pendingOrderItem"));
1039
        model.addAttribute("partnerInventoryMap", map.get("partnerInventoryMap"));
1040
        model.addAttribute("date", date);
1041
        model.addAttribute("isAdmin", isAdmin);
1042
        return "online-all-order-item";
1043
    }
33102 tejus.loha 1044
 
33143 tejus.loha 1045
 
1046
    @RequestMapping(value = "/reports", method = RequestMethod.GET)
1047
    public String reports(HttpServletRequest httpServletRequest, Model model) throws ProfitMandiBusinessException, UnsupportedOperationException, IOException {
1048
        //LoginDetails loginDetails = cookiesProcessor.getCookiesObject(httpServletRequest);
1049
        Map<ReporticoProject, List<ReporticoUrlInfo>> returnMap = ReporticoProject.reporticoProjectMap;
28137 amit.gupta 1050
		/*if(fofoStoreRepository.getWarehousePartnerMap().get(7720).stream().filter(x->x.getId()==loginDetails.getFofoId()).count() > 0) {
28106 amit.gupta 1051
			Map<ReporticoProject, List<ReporticoUrlInfo>> returnMap1 = new HashMap<ReporticoProject, List<ReporticoUrlInfo>>();
1052
			returnMap1.put(ReporticoProject.FOCO, returnMap.get(ReporticoProject.FOCO));
1053
			returnMap1.put(ReporticoProject.FOCOR, returnMap.get(ReporticoProject.FOCOR).stream().skip(1).collect(Collectors.toList()));
28107 amit.gupta 1054
			returnMap = returnMap1;
28137 amit.gupta 1055
		}*/
33143 tejus.loha 1056
        model.addAttribute("reporticoProjectMap", returnMap);
1057
        return "reports";
1058
    }
33775 ranu 1059
 
1060
    @RequestMapping(value = "/account-statement", method = RequestMethod.GET)
1061
    public String accountStatement(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
1062
                                   @RequestParam(required = false) LocalDate startDate,
1063
                                   @RequestParam(required = false) LocalDate endDate)
1064
            throws Exception {
1065
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1066
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1067
 
1068
        model.addAttribute("isAdmin", isAdmin);
1069
 
1070
        return "partner-account-statement";
1071
 
1072
    }
1073
 
1074
    @RequestMapping(value = "/account-statement-report", method = RequestMethod.GET)
1075
    public String getPartnerAccountStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
1076
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
1077
        if (fofoId > 0) {
1078
            if (!isAdmin) {
1079
                throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
1080
            }
1081
        } else {
1082
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1083
        }
1084
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
1085
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
1086
        UserWallet uw = walletService.getUserWallet(fofoId);
1087
        LOGGER.info("Start date - {}, end Date - {}", startDate, endDate);
1088
 
1089
        List<UserWalletHistory> history = userWalletHistoryRepository.selectPaginatedByWalletId(uw.getId(), startDate, endDate, 0, 0);
1090
 
1091
        history = history.stream().filter(x -> !x.getReferenceType().equals(WalletReferenceType.PURCHASE))
1092
                .filter(x -> !WalletService.CN_WALLET_REFERENCES.contains(x.getReferenceType())).sorted(Comparator.comparing(UserWalletHistory::getId)).collect(Collectors.toList());
1093
        Map<LocalDate, List<UserWalletHistory>> dateWalletMap = history.stream().collect(Collectors.groupingBy(x -> x.getTimestamp().toLocalDate()));
1094
        CustomRetailer customRetailer = retailerService.getAllFofoRetailers().get(fofoId);
1095
        List<StatementDetailModel> billedStatementDetails = orderRepository.selectDetailsBetween(fofoId, startDate, endDate);
1096
        Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate, Optional.of(fofoId));
1097
        Map<Integer, Float> closingAmountMap = transactionService.getPendingIndentValueMap(endDate, Optional.of(fofoId));
1098
 
1099
        float openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
1100
        float closingPendingAmount = closingAmountMap.get(fofoId) == null ? 0 : closingAmountMap.get(fofoId);
1101
        LOGGER.info("Opening - {}, Closing - {}", openingPendingAmount, closingPendingAmount);
1102
 
1103
        double grandTotalDebit = 0;
1104
        double grandTotalCredit = 0;
1105
 
1106
        for (UserWalletHistory walletEntry : history) {
1107
            if (walletEntry.getAmount() < 0) {
1108
                grandTotalDebit += Math.abs(walletEntry.getAmount());
1109
            } else {
1110
                grandTotalCredit += walletEntry.getAmount();
1111
            }
1112
        }
1113
 
1114
        for (StatementDetailModel statement : billedStatementDetails) {
1115
            if (statement.getAmount() < 0) {
1116
                grandTotalCredit += Math.abs(statement.getAmount());
1117
            } else {
1118
                grandTotalDebit += statement.getAmount();
1119
            }
1120
        }
1121
 
1122
        model.addAttribute("billedStatementDetails", billedStatementDetails);
1123
        model.addAttribute("customRetailer", customRetailer);
1124
        model.addAttribute("wallethistory", history);
1125
        model.addAttribute("startDate", startDate);
1126
        model.addAttribute("endDate", endDate);
1127
        model.addAttribute("dateWalletMap", dateWalletMap);
1128
        model.addAttribute("openingBalance", (openingBalance + openingPendingAmount));
1129
        model.addAttribute("closingBalance", (closingBalance + closingPendingAmount));
1130
        model.addAttribute("grandTotalDebit", grandTotalDebit);
1131
        model.addAttribute("grandTotalCredit", grandTotalCredit);
1132
 
1133
        return "account-statement-list";
1134
    }
33809 ranu 1135
 
1136
    @RequestMapping(value = "/loan/loan-statement", method = RequestMethod.GET)
33814 ranu 1137
    public String loanStatement(HttpServletRequest request, Model model)
33809 ranu 1138
            throws Exception {
1139
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1140
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1141
 
1142
        model.addAttribute("isAdmin", isAdmin);
1143
 
1144
        return "partner-loan-statement";
1145
 
1146
    }
1147
 
1148
    @RequestMapping(value = "/loan/partner-loan-statement-report", method = RequestMethod.GET)
1149
    public String partnerLoanStatement(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
1150
                                       @RequestParam(required = false) LocalDateTime startDate,
1151
                                       @RequestParam(required = false) LocalDateTime endDate)
1152
            throws Exception {
1153
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1154
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1155
        int partnerId = 0;
1156
 
1157
        if (fofoId > 0) {
1158
            partnerId = fofoId;
1159
        } else {
1160
            partnerId = loginDetails.getFofoId();
1161
        }
1162
 
1163
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(partnerId);
1164
 
1165
        List<LoanStatementReportModel> loanStatementReportModels = loanStatementRepository.selectByDatesAndStoreCode(startDate, endDate, fofoStore.getCode());
1166
 
1167
        model.addAttribute("isAdmin", isAdmin);
1168
        model.addAttribute("loanStatementReportModels", loanStatementReportModels);
1169
 
1170
        return "partner-loan-statement-summary";
1171
 
1172
    }
1173
 
1174
    @RequestMapping(value = "/loan/download-partner-loan-statement-report", method = RequestMethod.GET)
1175
    public ResponseEntity<?> downloadPartnerLoanStatement(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
1176
                                                          @RequestParam(required = false) LocalDateTime startDate,
1177
                                                          @RequestParam(required = false) LocalDateTime endDate)
1178
            throws Exception {
1179
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1180
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1181
 
1182
        int partnerId = 0;
1183
 
1184
        if (fofoId > 0) {
1185
            partnerId = fofoId;
1186
        } else {
1187
            partnerId = loginDetails.getFofoId();
1188
        }
1189
 
1190
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(partnerId);
1191
 
1192
        List<List<?>> rows = new ArrayList<>();
1193
 
1194
        List<LoanStatementReportModel> loanStatementReportModels = loanStatementRepository.selectByDatesAndStoreCode(startDate, endDate, fofoStore.getCode());// Extract the store name from the first loan statement
1195
        String storeName = loanStatementReportModels.get(0).getStoreName();
1196
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
1197
        for (LoanStatementReportModel loanStatement : loanStatementReportModels) {
1198
            rows.add(Arrays.asList(
1199
                    loanStatement.getCode(),  // Code
1200
                    String.valueOf(loanStatement.getId()),  // ID (convert int to string)
1201
                    loanStatement.getStoreName(),  // Store Name
1202
                    loanStatement.getState(),  // State
1203
                    loanStatement.getZone(),  // Zone
1204
                    loanStatement.getArea(),  // Area
1205
                    loanStatement.getTerritory(),  // Territory
1206
                    String.valueOf(loanStatement.getLoanId()),  // Loan ID
1207
                    loanStatement.getInterestRate().toString(),  // Interest Rate (BigDecimal to String)
1208
                    loanStatement.getIntialAmount().toString(),  // Initial Amount (BigDecimal to String)
1209
                    loanStatement.getPendingAmount().toString(),  // Pending Amount (BigDecimal to String)
1210
                    loanStatement.getCreatedOn().format(dateTimeFormatter),  // Created On (format LocalDateTime)
1211
                    loanStatement.getDueDate().format(dateTimeFormatter),  // Due Date (format LocalDateTime)
1212
                    loanStatement.getInterestAccrued().toString(),  // Interest Accrued (BigDecimal to String)
1213
                    loanStatement.getInterestPaid().toString(),  // Interest Paid (BigDecimal to String)
1214
                    String.valueOf(loanStatement.getFreeDays()),  // Free Days (convert int to string)
1215
                    loanStatement.getLoanReferenceType().toString(),  // Loan Reference Type (enum or string)
1216
                    loanStatement.getAmount().toString(),  // Amount (BigDecimal to String)
1217
                    loanStatement.getBusinessDate().format(dateTimeFormatter),  // Business Date (format LocalDateTime)
1218
                    loanStatement.getCreatedAt().format(dateTimeFormatter),  // Created At (format LocalDateTime)
1219
                    loanStatement.getDescription(),  // Description
1220
                    loanStatement.getStatus()  // Status (calculated value)
1221
            ));
1222
        }
1223
 
1224
        // Set up the headers and create the CSV
1225
        List<String> headers = Arrays.asList("Code", "ID", "Store Name", "State", "Zone", "Area", "Territory", "Loan ID",
1226
                "Interest Rate", "Initial Amount", "Pending Amount", "Created On", "Due Date",
1227
                "Interest Accrued", "Interest Paid", "Free Days", "Loan Reference Type",
1228
                "Amount", "Business Date", "Created At", "Description", "Status");
1229
 
1230
        // Create the CSV byte stream
1231
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
1232
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Partner Loan Summary Report");
1233
 
1234
        return responseEntity;
1235
 
1236
    }
23612 amit.gupta 1237
}