Subversion Repositories SmartDukaan

Rev

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