Subversion Repositories SmartDukaan

Rev

Rev 36708 | 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;
34066 aman.kumar 6
import com.spice.profitmandi.common.model.ProfitMandiConstants;
28106 amit.gupta 7
import com.spice.profitmandi.common.model.ReporticoUrlInfo;
23612 amit.gupta 8
import com.spice.profitmandi.common.services.ReporticoService;
30162 manish 9
import com.spice.profitmandi.common.util.FileUtil;
33102 tejus.loha 10
import com.spice.profitmandi.common.util.FormattingUtils;
34236 ranu 11
import com.spice.profitmandi.common.util.Utils;
26298 tejbeer 12
import com.spice.profitmandi.dao.entity.auth.AuthUser;
34066 aman.kumar 13
import com.spice.profitmandi.dao.entity.cs.Position;
33102 tejus.loha 14
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
15
import com.spice.profitmandi.dao.entity.fofo.PendingOrderItem;
34236 ranu 16
import com.spice.profitmandi.dao.entity.transaction.CreditNote;
33775 ranu 17
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
18
import com.spice.profitmandi.dao.entity.transaction.UserWalletHistory;
33102 tejus.loha 19
import com.spice.profitmandi.dao.model.*;
26298 tejbeer 20
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
21
import com.spice.profitmandi.dao.repository.cs.CsService;
34066 aman.kumar 22
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
28106 amit.gupta 23
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
23784 ashik.ali 24
import com.spice.profitmandi.dao.repository.dtr.RoleRepository;
34256 ranu 25
import com.spice.profitmandi.dao.repository.fofo.*;
33809 ranu 26
import com.spice.profitmandi.dao.repository.transaction.*;
23798 amit.gupta 27
import com.spice.profitmandi.service.authentication.RoleManager;
30162 manish 28
import com.spice.profitmandi.service.order.OrderService;
34236 ranu 29
import com.spice.profitmandi.service.transaction.CreditNoteService;
34256 ranu 30
import com.spice.profitmandi.service.transaction.InventoryMarginModel;
33775 ranu 31
import com.spice.profitmandi.service.transaction.TransactionService;
33102 tejus.loha 32
import com.spice.profitmandi.service.user.RetailerService;
33775 ranu 33
import com.spice.profitmandi.service.wallet.WalletService;
23612 amit.gupta 34
import com.spice.profitmandi.web.model.LoginDetails;
35
import com.spice.profitmandi.web.util.CookiesProcessor;
33775 ranu 36
import in.shop2020.model.v1.order.WalletReferenceType;
33092 tejus.loha 37
import org.apache.http.HttpResponse;
38
import org.apache.logging.log4j.LogManager;
39
import org.apache.logging.log4j.Logger;
40
import org.springframework.beans.factory.annotation.Autowired;
41
import org.springframework.core.io.InputStreamResource;
42
import org.springframework.http.HttpHeaders;
43
import org.springframework.http.HttpStatus;
34236 ranu 44
import org.springframework.http.MediaType;
33092 tejus.loha 45
import org.springframework.http.ResponseEntity;
46
import org.springframework.stereotype.Controller;
47
import org.springframework.transaction.annotation.Transactional;
48
import org.springframework.ui.Model;
49
import org.springframework.web.bind.annotation.*;
23612 amit.gupta 50
 
33092 tejus.loha 51
import javax.servlet.http.HttpServletRequest;
52
import java.io.IOException;
53
import java.time.LocalDate;
54
import java.time.LocalDateTime;
55
import java.time.LocalTime;
34236 ranu 56
import java.time.YearMonth;
33092 tejus.loha 57
import java.time.format.DateTimeFormatter;
58
import java.util.*;
33102 tejus.loha 59
import java.util.stream.Collectors;
33092 tejus.loha 60
 
23612 amit.gupta 61
@Controller
26298 tejbeer 62
@Transactional(rollbackFor = Throwable.class)
23612 amit.gupta 63
public class ReportsController {
33143 tejus.loha 64
    private static final Logger LOGGER = LogManager.getLogger(OrderController.class);
65
    private static final Logger Logger = LogManager.getLogger(OrderController.class);
66
    @Autowired
67
    private RoleRepository roleRepository;
68
    @Autowired
69
    private FofoOrderRepository fofoOrderRepository;
70
    @Autowired
71
    private RetailerService retailerService;
72
    @Autowired
73
    private PendingOrderItemRepository pendingOrderItemRepository;
74
    @Autowired
75
    private PendingOrderService pendingOrderService;
76
    @Autowired
77
    private CookiesProcessor cookiesProcessor;
78
    @Autowired
79
    private FofoStoreRepository fofoStoreRepository;
80
    @Autowired
81
    private ReporticoService reporticoService;
82
    @Autowired
83
    private OrderRepository orderRepository;
84
    @Autowired
85
    private RoleManager roleManager;
86
    @Autowired
87
    private OrderService orderService;
88
    @Autowired
89
    private CsService csService;
90
    @Autowired
91
    private AuthRepository authRepository;
33775 ranu 92
    @Autowired
93
    private WalletService walletService;
94
    @Autowired
95
    private UserWalletHistoryRepository userWalletHistoryRepository;
96
    @Autowired
97
    private TransactionService transactionService;
33809 ranu 98
    @Autowired
99
    private LoanStatementRepository loanStatementRepository;
34066 aman.kumar 100
    @Autowired
101
    PositionRepository positionRepository;
26298 tejbeer 102
 
34096 aman.kumar 103
    @Autowired
34236 ranu 104
    CreditNoteRepository creditNoteRepository;
105
 
106
    @Autowired
107
    CreditNoteService creditNoteService;
108
 
109
    @Autowired
36198 amit 110
    com.spice.profitmandi.dao.repository.transaction.EInvoiceDetailsRepository eInvoiceDetailsRepository;
111
 
112
    @Autowired
113
    com.spice.profitmandi.dao.repository.transaction.CreditNoteLineRepository creditNoteLineRepository;
114
 
115
    @Autowired
34256 ranu 116
    PriceDropIMEIRepository priceDropIMEIRepository;
117
 
118
    @Autowired
119
    SchemeInOutRepository schemeInOutRepository;
120
 
121
    @Autowired
122
    OfferPayoutRepository offerPayoutRepository;
123
 
124
    @Autowired
34096 aman.kumar 125
    UserWalletRepository userWalletRepository;
33186 amit.gupta 126
    @PostMapping(value = "/reports/{projectName}/{fileName}")
33143 tejus.loha 127
    public ResponseEntity<?> fetchReport(HttpServletRequest request, @PathVariable String fileName,
33187 amit.gupta 128
                                         @PathVariable ReporticoProject projectName, @RequestBody Map<String, String> paramsMap)
33143 tejus.loha 129
            throws ProfitMandiBusinessException, UnsupportedOperationException, IOException {
130
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
131
        HttpResponse response;
132
        if (roleManager.isAdmin(loginDetails.getRoleIds())) {
33102 tejus.loha 133
 
33143 tejus.loha 134
            if (fileName.equalsIgnoreCase("LeadsReport")) {
135
                if (paramsMap == null) {
136
                    paramsMap = new HashMap<String, String>();
137
                }
138
                Map<Integer, List<Integer>> mapping = csService.getL2L1Mapping();
33102 tejus.loha 139
 
33143 tejus.loha 140
                AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
33102 tejus.loha 141
 
33143 tejus.loha 142
                List<Integer> authIds = mapping.get(authUser.getId());
143
                if (authIds == null) {
144
                    authIds = new ArrayList<>();
145
                }
146
                authIds.add(authUser.getId());
33102 tejus.loha 147
 
33143 tejus.loha 148
                paramsMap.put("authId", authIds + "");
149
            }
150
        } else {
151
            if (paramsMap == null) {
152
                paramsMap = new HashMap<String, String>();
153
            }
26298 tejbeer 154
 
33143 tejus.loha 155
            paramsMap.put("MANUAL_fofoId", loginDetails.getFofoId() + "");
23764 amit.gupta 156
 
33143 tejus.loha 157
        }
158
        response = getAdminReportFile(loginDetails.getEmailId(), projectName, fileName + ".xml", paramsMap);
159
        HttpHeaders headers = new HttpHeaders();
160
        InputStreamResource is = new InputStreamResource(response.getEntity().getContent());
161
        headers.set("Content-Type", "application/vnd.ms-excel");
162
        headers.set("Content-disposition", "inline; filename=report-" + fileName + ".csv");
163
        headers.setContentLength(response.getEntity().getContentLength());
164
        return new ResponseEntity<InputStreamResource>(is, headers, HttpStatus.OK);
165
    }
26298 tejbeer 166
 
33143 tejus.loha 167
    private HttpResponse getAdminReportFile(String email, ReporticoProject projectName, String fileName,
168
                                            Map<String, String> reportParams) throws ProfitMandiBusinessException, IOException {
169
        return reporticoService.getReportFile(projectName, fileName, reportParams);
170
    }
26298 tejbeer 171
 
33143 tejus.loha 172
    @RequestMapping(value = "/collectionSummary", method = RequestMethod.GET)
173
    public String getCollectionSummary(HttpServletRequest request,
174
                                       Model model) throws ProfitMandiBusinessException {
175
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
176
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
177
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
178
        LocalDateTime currentStartMonth = currentDate.minusDays(30).toLocalDate().atStartOfDay();
179
        List<CollectionSummary> collectionSummaryList = orderRepository.selectCollectionSummary(fofoDetails.getFofoId(), currentStartMonth, currentDate);
180
        Logger.info("CollectionSummaryList {}", collectionSummaryList);
34069 aman.kumar 181
        boolean isRBM = false;
182
        if (isAdmin) {
183
            AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
184
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
185
            isRBM = positions.stream()
186
                    .anyMatch(position ->
187
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
188
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
189
            if (isRBM && pp.containsKey(authUser.getId())) {
190
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
191
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
192
                    try {
193
                        return retailerService.getFofoRetailers(true).get(x);
194
                    } catch (ProfitMandiBusinessException e) {
195
                        // TODO Auto-generated catch block
196
                        return null;
197
                    }
198
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
199
                model.addAttribute("customRetailersMap", customRetailersMap);
200
            }
34066 aman.kumar 201
        }
202
        model.addAttribute("isRBM", isRBM);
33143 tejus.loha 203
        model.addAttribute("startDate", currentDate.minusDays(30).toLocalDate());
204
        model.addAttribute("endDate", LocalDate.now());
205
        model.addAttribute("collectionSummaryList", collectionSummaryList);
206
        model.addAttribute("isAdmin", isAdmin);
207
        return "partner-collection-summary";
208
    }
26298 tejbeer 209
 
33143 tejus.loha 210
    @RequestMapping(value = "/collectionSummaryFetchReportByDate", method = RequestMethod.GET)
211
    public String getcollectionSummaryFetchReport(HttpServletRequest request,
212
                                                  @RequestParam(defaultValue = "0") int fofoId,
213
                                                  @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
214
                                                  @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate, Model model)
215
            throws Exception {
216
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
217
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
218
        if (isAdmin) {
219
            startDate = LocalDate.now().minusDays(30);
220
            endDate = LocalDate.now();
221
        }
34069 aman.kumar 222
        boolean isRBM = false;
223
        if (isAdmin) {
34096 aman.kumar 224
            AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
225
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 226
            isRBM = positions.stream()
34096 aman.kumar 227
                    .anyMatch(position ->
228
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
229
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 230
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 231
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
232
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
233
                    try {
234
                        return retailerService.getFofoRetailers(true).get(x);
235
                    } catch (ProfitMandiBusinessException e) {
236
                        // TODO Auto-generated catch block
237
                        return null;
238
                    }
239
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
240
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 241
            }
34066 aman.kumar 242
        }
243
        model.addAttribute("isRBM", isRBM);
33143 tejus.loha 244
        model.addAttribute("startDate", startDate);
245
        model.addAttribute("endDate", endDate);
246
        model.addAttribute("isAdmin", isAdmin);
23612 amit.gupta 247
 
26298 tejbeer 248
 
33143 tejus.loha 249
        if (isAdmin) {
250
            if (fofoId == 0) {
251
                //No need to send any data
252
                model.addAttribute("collectionSummaryList", new ArrayList<>());
253
                return "partner-collection-summary";
254
            } else {
255
                List<CollectionSummary> collectionSummaryList = orderRepository
256
                        .selectCollectionSummary(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
257
                model.addAttribute("collectionSummaryList", collectionSummaryList);
258
                return "partner-collection-summary";
259
            }
260
        } else {
261
            fofoId = fofoDetails.getFofoId();
262
            List<CollectionSummary> collectionSummaryList = orderRepository
263
                    .selectCollectionSummary(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
264
            model.addAttribute("collectionSummaryList", collectionSummaryList);
265
            return "partner-collection-summary";
26298 tejbeer 266
 
33143 tejus.loha 267
        }
268
    }
26298 tejbeer 269
 
33143 tejus.loha 270
    @RequestMapping(value = "/downloadCollectionSummary", method = RequestMethod.GET)
271
    public ResponseEntity<?> getDownloadCollectionSummary(HttpServletRequest request,
272
                                                          @RequestParam(defaultValue = "0") int fofoId,
273
                                                          @RequestParam(name = "startDate") LocalDate startDate,
274
                                                          @RequestParam(name = "endDate") LocalDate endDate, Model model) throws Exception {
275
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
276
        List<List<?>> rows = new ArrayList<>();
277
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
278
        List<CollectionSummary> collectionSummaryList = null;
279
        if (isAdmin) {
280
            if (fofoId == 0) {
281
                collectionSummaryList = new ArrayList<>();
282
            } else {
283
                collectionSummaryList = orderRepository.selectCollectionSummary(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
284
            }
285
        } else {
286
            collectionSummaryList = orderRepository.selectCollectionSummary(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
287
        }
288
        Logger.info("CollectionSummaryList {}", collectionSummaryList);
289
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
290
        for (CollectionSummary cs : collectionSummaryList) {
291
            rows.add(Arrays.asList(cs.getDate().format(
292
                            dateTimeFormatter), cs.getReferenceType(), cs.getCash(), cs.getPinelabs(), cs.getBajajFinserv(), cs.getHomeCredit(), cs.getPaytm(),
293
                    cs.getCapitalFirst(), cs.getZestMoney(), cs.getSamsungSure(), cs.getTotalAmount()));
294
        }
295
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
296
                .getCSVByteStream(Arrays.asList("Date", "Reference Type", "Cash", "Pinelabs", "Bajaj Finservice", "Home Credit", "Paymt",
297
                        "Capital First", "Zest Money", "Samsung Sure", "Total Amount"), rows);
298
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Collection Summary Report");
26298 tejbeer 299
 
33143 tejus.loha 300
        return responseEntity;
301
    }
26298 tejbeer 302
 
33143 tejus.loha 303
    @RequestMapping(value = "/franchiseeSalesReport", method = RequestMethod.GET)
304
    public String getFranchiseeSalesReport(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
305
                                           @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate)
306
            throws ProfitMandiBusinessException {
307
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
308
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
309
        if (startDate == null) {
310
            startDate = LocalDate.now().minusDays(30);
26298 tejbeer 311
 
33143 tejus.loha 312
        }
313
        endDate = LocalDate.now();
34069 aman.kumar 314
        boolean isRBM = false;
315
        if (isAdmin) {
34096 aman.kumar 316
            AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
317
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 318
            isRBM = positions.stream()
34096 aman.kumar 319
                    .anyMatch(position ->
320
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
321
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 322
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 323
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
324
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
325
                    try {
326
                        return retailerService.getFofoRetailers(true).get(x);
327
                    } catch (ProfitMandiBusinessException e) {
328
                        // TODO Auto-generated catch block
329
                        return null;
330
                    }
331
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
332
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 333
            }
34066 aman.kumar 334
        }
335
        model.addAttribute("isRBM", isRBM);
33143 tejus.loha 336
        model.addAttribute("startDate", startDate);
337
        model.addAttribute("endDate", endDate);
338
        model.addAttribute("isAdmin", isAdmin);
339
        LOGGER.info("q {}, starDate - {}, endDate - {}", fofoId, startDate, endDate);
340
        if (isAdmin) {
341
            if (fofoId == 0) {
342
                //No need to pull any data
343
                model.addAttribute("focoSaleReportList", new ArrayList<>());
344
                return "foco-sale-report";
23637 amit.gupta 345
 
33143 tejus.loha 346
            }
347
        } else {
348
            fofoId = loginDetails.getFofoId();
349
        }
33102 tejus.loha 350
 
351
 
33143 tejus.loha 352
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
33067 shampa 353
 
33143 tejus.loha 354
        List<FocoSaleReportModel> focoSaleReportList = fofoOrderRepository.selectFocoSaleReport(fofoId, fs.getCode(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
355
        model.addAttribute("focoSaleReportList", focoSaleReportList);
356
        return "foco-sale-report";
357
    }
33067 shampa 358
 
33143 tejus.loha 359
    @RequestMapping(value = "/franchiseeSalesFetchReportByDate", method = RequestMethod.GET)
360
    public String getfranchiseeSalesFetchReport(HttpServletRequest request, Model model,
361
                                                @RequestParam(defaultValue = "0") int fofoId,
362
                                                @RequestParam(required = false) LocalDate startDate,
363
                                                @RequestParam(required = false) LocalDate endDate)
364
            throws Exception {
365
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
366
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
367
        if (startDate == null) {
33067 shampa 368
 
33143 tejus.loha 369
            startDate = LocalDate.now().minusDays(30);
370
            endDate = LocalDate.now();
371
        }
34069 aman.kumar 372
        boolean isRBM = false;
373
        if (isAdmin) {
34096 aman.kumar 374
            AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
375
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 376
            isRBM = positions.stream()
34096 aman.kumar 377
                    .anyMatch(position ->
378
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
379
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 380
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 381
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
382
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
383
                    try {
384
                        return retailerService.getFofoRetailers(true).get(x);
385
                    } catch (ProfitMandiBusinessException e) {
386
                        // TODO Auto-generated catch block
387
                        return null;
388
                    }
389
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
390
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 391
            }
34066 aman.kumar 392
        }
393
        model.addAttribute("isRBM", isRBM);
33143 tejus.loha 394
        model.addAttribute("startDate", startDate);
395
        model.addAttribute("endDate", endDate);
396
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 397
 
33143 tejus.loha 398
        // List<List<?>> rows = new ArrayList<>();
30162 manish 399
 
33143 tejus.loha 400
        LOGGER.info("q {}, starDate - {}, endDate - {}", fofoId, startDate, endDate);
401
        if (isAdmin) {
402
            if (fofoId == 0) {
403
                //no need any data
404
                model.addAttribute("focoSaleReportList", new ArrayList<>());
405
                return "foco-sale-report";
406
            }
407
        } else {
408
            fofoId = loginDetails.getFofoId();
409
        }
410
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
411
        List<FocoSaleReportModel> focoSaleReportList = fofoOrderRepository.selectFocoSaleReport(fofoId, fs.getCode(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
412
        model.addAttribute("focoSaleReportList", focoSaleReportList);
413
        return "foco-sale-report";
414
    }
30162 manish 415
 
416
 
33143 tejus.loha 417
    @RequestMapping(value = "/downloadFranchiseeSales", method = RequestMethod.GET)
418
    public ResponseEntity<?> getdownloadFranchiseeSales(HttpServletRequest request,
419
                                                        @RequestParam(defaultValue = "0") int fofoId,
420
                                                        @RequestParam(name = "startDate") LocalDate startDate,
421
                                                        @RequestParam(name = "endDate") LocalDate endDate,
422
                                                        Model model)
423
            throws Exception {
424
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 425
 
33143 tejus.loha 426
        List<List<?>> rows = new ArrayList<>();
427
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
428
        List<FocoSaleReportModel> focoSaleReportList = null;
429
        FofoStore fs = null;
430
        if (isAdmin) {
431
            fs = fofoStoreRepository.selectByRetailerId(fofoId);
432
            if (fofoId == 0) {
433
                focoSaleReportList = new ArrayList<>();
434
            } else {
33102 tejus.loha 435
 
33143 tejus.loha 436
                focoSaleReportList = fofoOrderRepository.selectFocoSaleReport(fofoId,
34093 ranu 437
                        fs.getCode(), startDate.atStartOfDay(), endDate.atStartOfDay().plusDays(1));
33143 tejus.loha 438
            }
33102 tejus.loha 439
 
33143 tejus.loha 440
        } else {
441
            fs = fofoStoreRepository.selectByRetailerId(fofoDetails.getFofoId());
33102 tejus.loha 442
 
33143 tejus.loha 443
            focoSaleReportList = fofoOrderRepository.selectFocoSaleReport(fofoDetails.getFofoId(),
34093 ranu 444
                    fs.getCode(), startDate.atStartOfDay(), endDate.atStartOfDay().plusDays(1));
33143 tejus.loha 445
        }
446
        LOGGER.info("FocoSaleReportList {}", focoSaleReportList);
447
        String partnerName = null;
448
        for (FocoSaleReportModel fsr : focoSaleReportList) {
449
            partnerName = fsr.getName();
450
            rows.add(Arrays.asList(fsr.getCode(), fsr.getName(), fsr.getCity(), fsr.getState(), fsr.getRegion(),
451
                    fsr.getItemId(), fsr.getBrand(), fsr.getModelName(), fsr.getModelNumber(), fsr.getColor(),
452
                    fsr.getQuantity(), fsr.getDp(), fsr.getSellingPrice(), fsr.getMop(), fsr.getSerialNumber(),
453
                    FormattingUtils.format(fsr.getCreateDate()), fsr.getCustomerName(), fsr.getCustomerPhone(),
454
                    fsr.getCustomerCity(), fsr.getCustomerPincode(), fsr.getInvoiceNumber(), fsr.getPurchaseReference(),
455
                    fsr.getCustomerGstNumber(), FormattingUtils.format(fsr.getCancelledTimestamp()),
456
                    FormattingUtils.format(fsr.getGrnCompleteDate()), fsr.getHygieneRating(), fsr.getRating(),
457
                    fsr.getStatus(), fsr.getRemark(), FormattingUtils.format(fsr.getCreatedTimestamp()),
458
                    FormattingUtils.format(fsr.getDisposedTimestamp()),
459
                    FormattingUtils.format(fsr.getNextTimestamp()),
460
                    FormattingUtils.format(fsr.getActivationTimestamp()),
461
                    FormattingUtils.format(fsr.getActivationTimestamp()), fsr.getLabel()));
33102 tejus.loha 462
 
33143 tejus.loha 463
        }
33102 tejus.loha 464
 
33143 tejus.loha 465
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
466
                Arrays.asList("Code", "Name", "City", "State", "Region", "Item Id", "Brand", "Model Name",
467
                        "Model Number", "Color", "Quantity", "Dp", "Selling_Price", "mop", "Serial Number",
468
                        "Create Date", "Customer Name", "Customer Phone", "Customer City", " Customer Pincode",
469
                        "Invoice  Number", "Purchase Reference", "Customer Gst Number", " Cancelled Timestamp",
470
                        "GRN Complete Date", "Hygiene Rating", "Rating", "Status", "Remark", "Created Timestamp",
471
                        "Disposed Timestamp", " Next Timestamp", "Activation Timestamp", "Create Timestamp", "Label"),
472
                rows);
33102 tejus.loha 473
 
33143 tejus.loha 474
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, partnerName + " Franchisee Sales Report");
33102 tejus.loha 475
 
33143 tejus.loha 476
        return responseEntity;
33102 tejus.loha 477
 
33143 tejus.loha 478
    }
33102 tejus.loha 479
 
33143 tejus.loha 480
    @RequestMapping(value = "/downloadWalletSummaryReport", method = RequestMethod.GET)
481
    public ResponseEntity<?> getDownloadWalletSummaryReport(HttpServletRequest request,
482
                                                            @RequestParam(defaultValue = "0", name = "fofoId") int fofoId,
483
                                                            @RequestParam(name = "startDate") LocalDate startDate,
484
                                                            @RequestParam(name = "endDate") LocalDate endDate, Model model)
485
            throws Exception {
33102 tejus.loha 486
 
33143 tejus.loha 487
        List<List<?>> rows = new ArrayList<>();
488
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
489
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33815 ranu 490
 
34096 aman.kumar 491
        if (!isAdmin) fofoId = fofoDetails.getFofoId();
492
        List<WalletSummaryReportModel> walletSummaryList = fofoOrderRepository.selectWalletSummaryReport(
493
                fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
494
        double openingBalance = walletService.getOpeningTill(fofoId, startDate.atStartOfDay());
33815 ranu 495
 
33143 tejus.loha 496
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
497
        String partnerDetail = null;
33815 ranu 498
// Headers for the table data
34066 aman.kumar 499
        rows.add(Arrays.asList(
34096 aman.kumar 500
                "Timestamp", "Reference_type", "Reference", "Amount", "Running Balance", "Description"));
501
        for (
502
                WalletSummaryReportModel walletSummary : walletSummaryList) {
33143 tejus.loha 503
            partnerDetail = walletSummary.getName() + "(" + walletSummary.getCode() + "-" + walletSummary.getPhone() + ")" + "-" + walletSummary.getEmail();
33102 tejus.loha 504
 
33143 tejus.loha 505
            rows.add(Arrays.asList(
34096 aman.kumar 506
                    FormattingUtils.format(walletSummary.getTimestamp()),
34066 aman.kumar 507
                    walletSummary.getReferenceType(),
508
                    walletSummary.getReference(),
33143 tejus.loha 509
                    walletSummary.getAmount(),
36513 amit 510
                    walletSummary.getRunningBalance(),
33143 tejus.loha 511
                    walletSummary.getDescription()
512
            ));
33102 tejus.loha 513
 
33143 tejus.loha 514
        }
33102 tejus.loha 515
 
33815 ranu 516
 
33143 tejus.loha 517
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
34096 aman.kumar 518
                .getCSVByteStream(Arrays.asList("Opening Balance - : " + openingBalance), rows);
33143 tejus.loha 519
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, partnerDetail + " Wallet Statement Report");
33102 tejus.loha 520
 
33143 tejus.loha 521
        return responseEntity;
33102 tejus.loha 522
 
33143 tejus.loha 523
    }
524
    @RequestMapping(value = "/walletSummaryFetchReportByDate", method = RequestMethod.GET)
525
    public String getwalletSummaryFetchReport(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
526
                                              @RequestParam(required = false) LocalDate startDate,
527
                                              @RequestParam(required = false) LocalDate endDate)
528
            throws Exception {
529
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
34096 aman.kumar 530
        UserWallet userWallet = userWalletRepository.selectByRetailerId(fofoId);
33143 tejus.loha 531
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
532
        if (startDate == null) {
533
            startDate = LocalDate.now().minusDays(30);
534
        }
34011 tejus.loha 535
        if (endDate == null) {
536
            endDate = LocalDate.now();
537
        }
36513 amit 538
        List<WalletSummaryReportModel> walletSummaryList = new ArrayList<>();
34011 tejus.loha 539
        float openingBalance = 0;
540
        float openingPendingAmount = 0;
33143 tejus.loha 541
        if (isAdmin) {
34011 tejus.loha 542
            if (fofoId > 0) {
543
                openingBalance = walletService.getOpeningTill(fofoId, startDate.atStartOfDay());
33815 ranu 544
                Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate.atStartOfDay(), Optional.of(fofoId));
34011 tejus.loha 545
                openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
36513 amit 546
                walletSummaryList = fofoOrderRepository.selectWalletSummaryReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
34011 tejus.loha 547
                LOGGER.info("startDate - " + startDate.atStartOfDay());
548
                LOGGER.info("endDate - " + endDate.atTime(LocalTime.MAX));
33143 tejus.loha 549
            }
550
        } else {
36513 amit 551
            walletSummaryList = fofoOrderRepository.selectWalletSummaryReport(loginDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33143 tejus.loha 552
        }
34069 aman.kumar 553
        boolean isRBM = false;
554
        if (isAdmin) {
34096 aman.kumar 555
            AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
556
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 557
            isRBM = positions.stream()
34096 aman.kumar 558
                    .anyMatch(position ->
559
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
560
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 561
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 562
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
563
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
564
                    try {
565
                        return retailerService.getFofoRetailers(true).get(x);
566
                    } catch (ProfitMandiBusinessException e) {
567
                        // TODO Auto-generated catch block
568
                        return null;
569
                    }
570
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
571
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 572
            }
34066 aman.kumar 573
        }
574
        model.addAttribute("isRBM", isRBM);
575
 
36513 amit 576
        LOGGER.info("walletSummaryList {}", walletSummaryList);
577
        model.addAttribute("walletSummaryList", walletSummaryList);
34011 tejus.loha 578
        model.addAttribute("openingBalance", (openingBalance + openingPendingAmount));
579
        model.addAttribute("startDate", startDate);
580
        model.addAttribute("endDate", endDate);
581
        model.addAttribute("isAdmin", isAdmin);
34096 aman.kumar 582
        model.addAttribute("userWallet", userWallet);
34011 tejus.loha 583
        return "wallet-summary-report";
33143 tejus.loha 584
    }
33102 tejus.loha 585
 
33143 tejus.loha 586
    @RequestMapping(value = "/walletSummaryReport", method = RequestMethod.GET)
587
    public String getWalletSummaryReport(HttpServletRequest request, Model model) throws Exception {
588
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
589
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
34011 tejus.loha 590
        LocalDateTime startDate = LocalDateTime.now().minusDays(30);
591
        LocalDateTime endDate = LocalDateTime.now();
36513 amit 592
        List<WalletSummaryReportModel> walletSummaryList = new ArrayList<>();
34011 tejus.loha 593
        if (!isAdmin) {
36513 amit 594
            walletSummaryList = fofoOrderRepository
34011 tejus.loha 595
                    .selectWalletSummaryReport(fofoDetails.getFofoId(), startDate, endDate);
596
        }
34069 aman.kumar 597
        boolean isRBM = false;
598
        if (isAdmin) {
599
            AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
600
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
601
            isRBM = positions.stream()
602
                    .anyMatch(position ->
603
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
604
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
605
            if (isRBM && pp.containsKey(authUser.getId())) {
606
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
607
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
608
                    try {
609
                        return retailerService.getFofoRetailers(true).get(x);
610
                    } catch (ProfitMandiBusinessException e) {
611
                        // TODO Auto-generated catch block
612
                        return null;
613
                    }
614
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
615
                model.addAttribute("customRetailersMap", customRetailersMap);
616
            }
34066 aman.kumar 617
        }
618
        model.addAttribute("isRBM", isRBM);
619
 
36513 amit 620
        LOGGER.info("walletSummaryList {}", walletSummaryList);
34011 tejus.loha 621
        model.addAttribute("startDate", startDate.toLocalDate());
622
        model.addAttribute("endDate", endDate.toLocalDate());
36513 amit 623
        model.addAttribute("walletSummaryList", walletSummaryList);
33143 tejus.loha 624
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 625
 
33143 tejus.loha 626
        return "wallet-summary-report";
627
    }
33102 tejus.loha 628
 
33143 tejus.loha 629
    @RequestMapping(value = "/pendingIndentReport", method = RequestMethod.GET)
630
    public String getPendingIndentReport(HttpServletRequest request, Model model) throws Exception {
631
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
632
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
34069 aman.kumar 633
        boolean isRBM = false;
634
        if (isAdmin) {
34096 aman.kumar 635
            AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
636
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 637
            isRBM = positions.stream()
34096 aman.kumar 638
                    .anyMatch(position ->
639
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
640
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 641
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 642
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
643
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
644
                    try {
645
                        return retailerService.getFofoRetailers(true).get(x);
646
                    } catch (ProfitMandiBusinessException e) {
647
                        // TODO Auto-generated catch block
648
                        return null;
649
                    }
650
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
651
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 652
            }
34066 aman.kumar 653
        }
654
        model.addAttribute("isRBM", isRBM);
33102 tejus.loha 655
 
33143 tejus.loha 656
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
657
        LocalDateTime currentStartMonth = currentDate.minusMonths(2).toLocalDate().atStartOfDay();
33102 tejus.loha 658
 
33143 tejus.loha 659
        List<PendingIndentReportModel> pendingIndentReports = fofoOrderRepository
660
                .selectPendingIndentReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
661
        LOGGER.info("pendingIndentReports {}", pendingIndentReports);
33102 tejus.loha 662
 
33143 tejus.loha 663
        model.addAttribute("startDate", currentDate.minusMonths(2).toLocalDate());
664
        model.addAttribute("endDate", LocalDate.now());
665
        model.addAttribute("pendingIndentReports", pendingIndentReports);
666
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 667
 
668
 
33143 tejus.loha 669
        return "pending-indent-report";
670
    }
33102 tejus.loha 671
 
33143 tejus.loha 672
    @RequestMapping(value = "/pendingIndentFetchReportByDate", method = RequestMethod.GET)
673
    public String getpendingIndentFetchReport(
674
            HttpServletRequest request,
675
            @RequestParam(defaultValue = "0") int fofoId,
676
            @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
677
            @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate,
678
            Model model
679
    ) throws Exception {
680
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
681
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
682
        if (startDate == null) {
683
            startDate = LocalDate.now().minusDays(30);
684
            endDate = LocalDate.now();
685
        }
34069 aman.kumar 686
        boolean isRBM = false;
687
        if (isAdmin) {
34096 aman.kumar 688
            AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
689
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 690
            isRBM = positions.stream()
34096 aman.kumar 691
                    .anyMatch(position ->
692
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
693
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 694
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 695
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
696
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
697
                    try {
698
                        return retailerService.getFofoRetailers(true).get(x);
699
                    } catch (ProfitMandiBusinessException e) {
700
                        // TODO Auto-generated catch block
701
                        return null;
702
                    }
703
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
704
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 705
            }
34066 aman.kumar 706
        }
707
        model.addAttribute("isRBM", isRBM);
708
 
33143 tejus.loha 709
        model.addAttribute("startDate", startDate);
710
        model.addAttribute("endDate", endDate);
711
        model.addAttribute("isAdmin", isAdmin);
712
        if (isAdmin) {
713
            if (fofoId == 0) {
714
                model.addAttribute("pendingIndentReports", new ArrayList<>());
715
                return "pending-indent-report";
716
            } else {
717
                List<PendingIndentReportModel> pendingIndentReports = fofoOrderRepository
718
                        .selectPendingIndentReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
719
                model.addAttribute("pendingIndentReports", pendingIndentReports);
720
                return "pending-indent-report";
721
            }
722
        } else {
723
            LocalDateTime currentDate = LocalDate.now().atStartOfDay();
724
            List<PendingIndentReportModel> pendingIndentReports = fofoOrderRepository
725
                    .selectPendingIndentReport(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
726
            model.addAttribute("pendingIndentReports", pendingIndentReports);
727
            return "pending-indent-report";
33102 tejus.loha 728
 
33143 tejus.loha 729
        }
730
    }
33102 tejus.loha 731
 
732
 
33143 tejus.loha 733
    @RequestMapping(value = "/pendingIndentReportDownload", method = RequestMethod.GET)
734
    public ResponseEntity<?> getPendingIndentReportDownload(HttpServletRequest request,
735
                                                            @RequestParam(defaultValue = "0") int fofoId,
736
                                                            @RequestParam(name = "startDate") LocalDate startDate,
737
                                                            @RequestParam(name = "endDate") LocalDate endDate, Model model)
738
            throws Exception {
739
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
740
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33102 tejus.loha 741
        /*LocalDateTime currentDate = LocalDate.now().atStartOfDay();
742
        LocalDateTime currentStartMonth = currentDate.minusMonths(2).toLocalDate().atStartOfDay();*/
33143 tejus.loha 743
        List<PendingIndentReportModel> pendingIndentReports = null;
744
        List<List<?>> rows = new ArrayList<>();
745
        if (isAdmin) {
746
            if (fofoId == 0)
747
                pendingIndentReports = new ArrayList<>();
748
            else
749
                pendingIndentReports = fofoOrderRepository
750
                        .selectPendingIndentReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
751
        } else {
752
            pendingIndentReports = fofoOrderRepository
753
                    .selectPendingIndentReport(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 754
 
33143 tejus.loha 755
        }
756
        LOGGER.info("pendingIndentReports {}", pendingIndentReports);
757
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
33102 tejus.loha 758
 
33143 tejus.loha 759
        for (PendingIndentReportModel pir : pendingIndentReports) {
33102 tejus.loha 760
 
33143 tejus.loha 761
            rows.add(Arrays.asList(pir.getTransactionId(), pir.getOrderId(),
762
                    pir.getCreatTimestamp().format(dateTimeFormatter), pir.getItemId(), pir.getBrand(),
763
                    pir.getModelName(), pir.getModelNumber(), pir.getColor(), pir.getQuantity(), pir.getUnitPrice(),
764
                    pir.getWalletAmount(), pir.getStatus(), pir.getInvoiceNumber(),
765
                    pir.getBillingTimestamp() == null ? "" : pir.getBillingTimestamp().format(dateTimeFormatter)));
33102 tejus.loha 766
 
33143 tejus.loha 767
        }
33102 tejus.loha 768
 
33143 tejus.loha 769
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList(
770
                "Transaction Id", "Order Id", "Created_At", "Item_Id", "Brand", "Model Name", "Model Number", "Color",
771
                "Quantity", "Unit Price", "Wallet Deduction", "Status", "Invoice Number", "Billing Timestamp"), rows);
33102 tejus.loha 772
 
33143 tejus.loha 773
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Order Status Summary Report");
33102 tejus.loha 774
 
33143 tejus.loha 775
        return responseEntity;
776
    }
33102 tejus.loha 777
 
33143 tejus.loha 778
    @RequestMapping(value = "/schemePayoutReport", method = RequestMethod.GET)
779
    public String getschemePayoutReport(HttpServletRequest request, Model model,
780
                                        @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate)
781
            throws ProfitMandiBusinessException {
33102 tejus.loha 782
 
33143 tejus.loha 783
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
784
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
785
        if (startDate == null) {
786
            startDate = LocalDate.now().minusDays(30);
787
            endDate = LocalDate.now();
788
        }
34069 aman.kumar 789
        boolean isRBM = false;
790
        if (isAdmin) {
34096 aman.kumar 791
            AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
792
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 793
            isRBM = positions.stream()
34096 aman.kumar 794
                    .anyMatch(position ->
795
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
796
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 797
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 798
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
799
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
800
                    try {
801
                        return retailerService.getFofoRetailers(true).get(x);
802
                    } catch (ProfitMandiBusinessException e) {
803
                        // TODO Auto-generated catch block
804
                        return null;
805
                    }
806
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
807
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 808
            }
34066 aman.kumar 809
        }
810
        model.addAttribute("isRBM", isRBM);
33143 tejus.loha 811
        model.addAttribute("startDate", startDate);
812
        model.addAttribute("endDate", endDate);
813
        model.addAttribute("isAdmin", isAdmin);
814
        //LOGGER.info("schemePayoutReports {}", schemePayoutReports);
815
        List<SchemePayoutReportModel> schemePayoutReports = fofoOrderRepository
816
                .selectSchemePayoutReport(loginDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
817
        model.addAttribute("schemePayoutReports", schemePayoutReports);
818
        return "scheme-payout-report";
33102 tejus.loha 819
 
33143 tejus.loha 820
    }
33102 tejus.loha 821
 
33143 tejus.loha 822
    @RequestMapping(value = "/schemePayoutFetchReportByDate", method = RequestMethod.GET)
823
    public String getschemePayoutFetchReportByDate(
824
            HttpServletRequest request,
825
            Model model,
826
            @RequestParam(defaultValue = "0") int fofoId,
827
            @RequestParam(required = false) LocalDate startDate,
828
            @RequestParam(required = false) LocalDate endDate)
829
            throws ProfitMandiBusinessException {
830
        //LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
831
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
832
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
833
        if (startDate == null) {
834
            startDate = LocalDate.now().minusDays(30);
835
            endDate = LocalDate.now();
836
        }
34069 aman.kumar 837
        boolean isRBM = false;
838
        if (isAdmin) {
34096 aman.kumar 839
            AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
840
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 841
            isRBM = positions.stream()
34096 aman.kumar 842
                    .anyMatch(position ->
843
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
844
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 845
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 846
                List<Integer> fofoIds = pp.get(authUser.getId());
847
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
848
                    try {
849
                        return retailerService.getFofoRetailers(true).get(x);
850
                    } catch (ProfitMandiBusinessException e) {
851
                        // TODO Auto-generated catch block
852
                        return null;
853
                    }
854
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
855
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 856
            }
34066 aman.kumar 857
        }
858
 
859
        model.addAttribute("isRBM", isRBM);
33143 tejus.loha 860
        model.addAttribute("startDate", startDate);
861
        model.addAttribute("endDate", endDate);
862
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 863
 
33143 tejus.loha 864
        LOGGER.info("q {}, starDate - {}, endDate - {}", fofoId, startDate, endDate);
865
        if (isAdmin) {
866
            if (fofoId == 0) {
867
                //No need to pull any data
868
                model.addAttribute("schemePayoutReports", new ArrayList<>());
869
                return "scheme-payout-report";
33102 tejus.loha 870
 
33143 tejus.loha 871
            } else {
872
                List<SchemePayoutReportModel> schemePayoutReports = fofoOrderRepository
873
                        .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 874
 
33143 tejus.loha 875
                model.addAttribute("schemePayoutReports", schemePayoutReports);
876
                return "scheme-payout-report";
877
            }
878
        } else {
879
            fofoId = loginDetails.getFofoId();
33102 tejus.loha 880
 
33143 tejus.loha 881
            List<SchemePayoutReportModel> schemePayoutReports = fofoOrderRepository
882
                    .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 883
 
33143 tejus.loha 884
            model.addAttribute("schemePayoutReports", schemePayoutReports);
885
            return "scheme-payout-report";
886
        }
33102 tejus.loha 887
 
33143 tejus.loha 888
    }
33102 tejus.loha 889
 
33143 tejus.loha 890
    @RequestMapping(value = "/offerPayoutReport", method = RequestMethod.GET)
891
    public String getOfferPayoutReport(HttpServletRequest request, Model model, @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate) throws Exception {
892
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
893
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
34069 aman.kumar 894
        boolean isRBM = false;
895
        if (isAdmin) {
34096 aman.kumar 896
            AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
897
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 898
            isRBM = positions.stream()
34096 aman.kumar 899
                    .anyMatch(position ->
900
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
901
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 902
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 903
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
904
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
905
                    try {
906
                        return retailerService.getFofoRetailers(true).get(x);
907
                    } catch (ProfitMandiBusinessException e) {
908
                        // TODO Auto-generated catch block
909
                        return null;
910
                    }
911
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
912
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 913
            }
34066 aman.kumar 914
        }
915
        model.addAttribute("isRBM", isRBM);
33143 tejus.loha 916
        if (startDate == null) {
917
            startDate = LocalDate.now().minusDays(30);
918
            endDate = LocalDate.now();
919
        }
920
        model.addAttribute("startDate", startDate);
921
        model.addAttribute("endDate", endDate);
33102 tejus.loha 922
 
923
 
33143 tejus.loha 924
        List<OfferPayoutDumpReportModel> offerPayoutDumpReports = fofoOrderRepository
925
                .selectOfferPayoutDumpReport(fofoDetails.getFofoId(), startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
926
        LOGGER.info("offerPayoutDumpReports {}", offerPayoutDumpReports);
33102 tejus.loha 927
 
33143 tejus.loha 928
        model.addAttribute("offerPayoutDumpReports", offerPayoutDumpReports);
929
        model.addAttribute("isAdmin", isAdmin);
33102 tejus.loha 930
 
33143 tejus.loha 931
        return "offer-payout-dump-report";
932
    }
33102 tejus.loha 933
 
33143 tejus.loha 934
    @RequestMapping(value = "/offerPayoutFetchReportByDate", method = RequestMethod.GET)
935
    public String getofferPayoutFetchReportByDate(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
936
                                                  @RequestParam(required = false) LocalDate startDate, @RequestParam(required = false) LocalDate endDate)
937
            throws ProfitMandiBusinessException {
33102 tejus.loha 938
 
33143 tejus.loha 939
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
940
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
941
        if (startDate == null) {
942
            startDate = LocalDate.now().minusDays(30);
943
            endDate = LocalDate.now();
944
        }
34069 aman.kumar 945
        boolean isRBM = false;
946
        if (isAdmin) {
34096 aman.kumar 947
            AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
948
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 949
            isRBM = positions.stream()
34096 aman.kumar 950
                    .anyMatch(position ->
951
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
952
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 953
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 954
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
955
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
956
                    try {
957
                        return retailerService.getFofoRetailers(true).get(x);
958
                    } catch (ProfitMandiBusinessException e) {
959
                        // TODO Auto-generated catch block
960
                        return null;
961
                    }
962
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
963
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 964
            }
34066 aman.kumar 965
        }
966
        model.addAttribute("isRBM", isRBM);
33143 tejus.loha 967
        model.addAttribute("startDate", startDate);
968
        model.addAttribute("endDate", endDate);
969
        model.addAttribute("isAdmin", isAdmin);
970
        LOGGER.info("q {}, starDate - {}, endDate - {}", fofoId, startDate, endDate);
971
        if (isAdmin) {
972
            if (fofoId == 0) {
973
                //No need to pull any data
974
                model.addAttribute("offerPayoutReports", new ArrayList<>());
975
                return "offer-payout-dump-report";
33102 tejus.loha 976
 
33143 tejus.loha 977
            } else {
978
                List<OfferPayoutDumpReportModel> offerPayoutDumpReports = fofoOrderRepository
979
                        .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 980
 
33143 tejus.loha 981
                model.addAttribute("offerPayoutDumpReports", offerPayoutDumpReports);
33102 tejus.loha 982
 
983
 
33143 tejus.loha 984
                return "offer-payout-dump-report";
33102 tejus.loha 985
 
33143 tejus.loha 986
            }
987
        } else {
988
            fofoId = loginDetails.getFofoId();
989
            List<OfferPayoutDumpReportModel> offerPayoutDumpReports = fofoOrderRepository
990
                    .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 991
 
33143 tejus.loha 992
            model.addAttribute("offerPayoutDumpReports", offerPayoutDumpReports);
33102 tejus.loha 993
 
994
 
33143 tejus.loha 995
            return "offer-payout-dump-report";
996
        }
997
    }
33102 tejus.loha 998
 
999
 
33143 tejus.loha 1000
    @RequestMapping(value = "/selectPartnerBillingSummaryReport", method = RequestMethod.GET)
1001
    public String getselectPartnerBillingSummaryReport(HttpServletRequest request, Model model) throws Exception {
1002
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 1003
 
33143 tejus.loha 1004
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
1005
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 1006
 
33143 tejus.loha 1007
        List<PartnerBillingSummaryModel> partnerBillingSummaryReports = fofoOrderRepository
1008
                .selectPartnerBillingSummaryReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
33102 tejus.loha 1009
 
33143 tejus.loha 1010
        model.addAttribute("startDate", currentDate.minusMonths(3).toLocalDate());
1011
        model.addAttribute("endDate", LocalDate.now());
1012
        model.addAttribute("partnerBillingSummaryReports", partnerBillingSummaryReports);
33102 tejus.loha 1013
 
33143 tejus.loha 1014
        return "partner-billing-summary-report";
1015
    }
33102 tejus.loha 1016
 
33143 tejus.loha 1017
    @RequestMapping(value = "/priceDropReport", method = RequestMethod.GET)
1018
    public String getSelectPriceDropReport(HttpServletRequest request, @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
1019
                                           @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate, Model model) throws Exception {
1020
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
1021
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
1022
        if (startDate == null) {
1023
            startDate = LocalDate.now().minusDays(30);
1024
            endDate = LocalDate.now();
1025
        }
34069 aman.kumar 1026
        boolean isRBM = false;
1027
        if (isAdmin) {
1028
            AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
1029
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
1030
            isRBM = positions.stream()
1031
                    .anyMatch(position ->
1032
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
1033
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1034
            if (pp.containsKey(authUser.getId())) {
1035
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
1036
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
1037
                    try {
1038
                        return retailerService.getFofoRetailer(x);
1039
                    } catch (ProfitMandiBusinessException e) {
1040
                        // TODO Auto-generated catch block
1041
                        return null;
1042
                    }
1043
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1044
                model.addAttribute("customRetailersMap", customRetailersMap);
1045
            }
34066 aman.kumar 1046
        }
1047
        model.addAttribute("isRBM", isRBM);
33143 tejus.loha 1048
        model.addAttribute("startDate", startDate);
1049
        model.addAttribute("endDate", endDate);
1050
        model.addAttribute("isAdmin", isAdmin);
1051
        List<PriceDropReportModel> priceDropReports = orderRepository.selectPriceDropReport(fofoDetails.getFofoId(),
1052
                startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
33102 tejus.loha 1053
 
33143 tejus.loha 1054
        model.addAttribute("priceDropReports", priceDropReports);
33102 tejus.loha 1055
 
33143 tejus.loha 1056
        return "price-drop-report";
1057
    }
33102 tejus.loha 1058
 
33143 tejus.loha 1059
    @RequestMapping(value = "/priceDropFetchReportByDate", method = RequestMethod.GET)
1060
    public String getpriceDropFetchReportByDate(HttpServletRequest request,
1061
                                                @RequestParam(defaultValue = "0") int fofoId,
1062
                                                @RequestParam(name = "startDate", required = true, defaultValue = "") LocalDate startDate,
1063
                                                @RequestParam(name = "endDate", required = true, defaultValue = "") LocalDate endDate, Model model)
1064
            throws Exception {
33102 tejus.loha 1065
 
33143 tejus.loha 1066
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
1067
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
1068
        if (startDate == null) {
1069
            startDate = LocalDate.now().minusDays(30);
1070
            endDate = LocalDate.now();
1071
        }
34069 aman.kumar 1072
        boolean isRBM = false;
1073
        if (isAdmin) {
1074
            AuthUser authUser = authRepository.selectByEmailOrMobile(fofoDetails.getEmailId());
1075
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
1076
            isRBM = positions.stream()
1077
                    .anyMatch(position ->
1078
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
1079
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1080
            if (pp.containsKey(authUser.getId())) {
1081
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
1082
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
1083
                    try {
1084
                        return retailerService.getFofoRetailer(x);
1085
                    } catch (ProfitMandiBusinessException e) {
1086
                        // TODO Auto-generated catch block
1087
                        return null;
1088
                    }
1089
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1090
                model.addAttribute("customRetailersMap", customRetailersMap);
1091
            }
34066 aman.kumar 1092
        }
1093
        model.addAttribute("isRBM", isRBM);
33143 tejus.loha 1094
        model.addAttribute("startDate", startDate);
1095
        model.addAttribute("endDate", endDate);
1096
        model.addAttribute("isAdmin", isAdmin);
1097
        if (isAdmin) {
1098
            if (fofoId == 0) {
1099
                model.addAttribute("priceDropReports", new ArrayList<>());
1100
                return "price-drop-report";
1101
            } else {
1102
                List<PriceDropReportModel> priceDropReports = orderRepository.selectPriceDropReport(fofoId,
1103
                        startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
1104
                model.addAttribute("priceDropReports", priceDropReports);
1105
                return "price-drop-report";
1106
            }
33102 tejus.loha 1107
 
33143 tejus.loha 1108
        } else {
1109
            List<PriceDropReportModel> priceDropReports = orderRepository.selectPriceDropReport(fofoDetails.getFofoId(),
1110
                    startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
1111
            model.addAttribute("priceDropReports", priceDropReports);
1112
            return "price-drop-report";
1113
        }
1114
    }
33102 tejus.loha 1115
 
1116
 
33143 tejus.loha 1117
    @RequestMapping(value = "/downloadPriceDropReport", method = RequestMethod.GET)
1118
    public ResponseEntity<?> getSelectDownloadPriceDropReport(HttpServletRequest request,
1119
                                                              @RequestParam(defaultValue = "0") int fofoId,
1120
                                                              @RequestParam(name = "startDate") LocalDate startDate,
1121
                                                              @RequestParam(name = "endDate") LocalDate endDate, Model model)
1122
            throws Exception {
1123
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
1124
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
1125
        List<List<?>> rows = new ArrayList<>();
1126
        List<PriceDropReportModel> priceDropReports = null;
1127
        if (isAdmin) {
1128
            if (fofoId == 0)
1129
                priceDropReports = new ArrayList<>();
1130
            else
1131
                priceDropReports = orderRepository.selectPriceDropReport(fofoId,
1132
                        startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
1133
        } else {
1134
            fofoId = fofoDetails.getFofoId();
1135
            priceDropReports = orderRepository.selectPriceDropReport(fofoId,
1136
                    startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
1137
        }
1138
        for (PriceDropReportModel pdr : priceDropReports) {
33102 tejus.loha 1139
 
33143 tejus.loha 1140
            rows.add(Arrays.asList(pdr.getCode(), pdr.getId(), pdr.getBrand(), pdr.getModelName(), pdr.getModelNumber(),
1141
                    FormattingUtils.formatDate(pdr.getAffectedOn()), pdr.getAmount(), FormattingUtils.format(pdr.getCreditTimestamp()), pdr.getImei(), pdr.getStatus(),
1142
                    FormattingUtils.format(pdr.getRejectedTimestamp()), pdr.getRejectionReason()));
33102 tejus.loha 1143
 
33143 tejus.loha 1144
        }
1145
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1146
                .getCSVByteStream(Arrays.asList("code", "Price_Drop_Id", "brand", "model_name", "model_number",
1147
                        "affected_on", "amount", "Credit Date", "Imei", "status", "Rejected Date", "Rejected Reason"), rows);
33102 tejus.loha 1148
 
33143 tejus.loha 1149
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "price drop report");
33102 tejus.loha 1150
 
33143 tejus.loha 1151
        return responseEntity;
33102 tejus.loha 1152
 
33143 tejus.loha 1153
    }
33102 tejus.loha 1154
 
33143 tejus.loha 1155
    @RequestMapping(value = "/downloadPartnerBillingSummaryReport", method = RequestMethod.GET)
1156
    public ResponseEntity<?> getdownloadPartnerBillingSummaryReport(HttpServletRequest request,
1157
                                                                    @RequestParam(name = "startDate") LocalDate startDate,
1158
                                                                    @RequestParam(name = "endDate") LocalDate endDate, Model model)
1159
            throws Exception {
33102 tejus.loha 1160
 
33143 tejus.loha 1161
        List<List<?>> rows = new ArrayList<>();
1162
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 1163
 
33143 tejus.loha 1164
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
1165
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 1166
 
33143 tejus.loha 1167
        List<PartnerBillingSummaryModel> partnerBillingSummaryReports = fofoOrderRepository
1168
                .selectPartnerBillingSummaryReport(fofoDetails.getFofoId(), startDate.atStartOfDay(),
1169
                        endDate.atTime(LocalTime.MAX));
33102 tejus.loha 1170
 
33143 tejus.loha 1171
        for (PartnerBillingSummaryModel pbsr : partnerBillingSummaryReports) {
33102 tejus.loha 1172
 
33143 tejus.loha 1173
            rows.add(Arrays.asList(pbsr.getId(),
1174
                    FormattingUtils.format(pbsr.getCreateTimestamp()),
1175
                    FormattingUtils.format(pbsr.getBillingTimestamp()),
1176
                    FormattingUtils.format(pbsr.getDeliveryTimestamp()),
1177
                    FormattingUtils.format(pbsr.getPartnerGrnTimestamp()),
1178
                    pbsr.getTransactionId(),
1179
                    pbsr.getLogisticsTransactionId(), pbsr.getAirwayBillNumber(), pbsr.getStatusSubGroup(),
1180
                    pbsr.getStatusName(), pbsr.getRetailerId(), pbsr.getRetailerName(), pbsr.getItemId(),
1181
                    pbsr.getBrand(), pbsr.getModelName(), pbsr.getModelNumber(), pbsr.getColor(), pbsr.getUnitPrice(),
1182
                    pbsr.getQuantity(), pbsr.getTotalPrice(), pbsr.getInvoiceNumber(), pbsr.getSellerName(), pbsr.getGstNumber(), pbsr.getHsnCode(), pbsr.getIgstRate(),
1183
                    pbsr.getCgstRate(), pbsr.getSgstRate()));
33102 tejus.loha 1184
 
33143 tejus.loha 1185
        }
33102 tejus.loha 1186
 
33143 tejus.loha 1187
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("OrderId",
1188
                "Created On", "Billed On", "Delivered On", "Grned On", "Transaction_id", "master_order_id",
1189
                "airwaybill_no", "statusSubGroupp", "statusName", "customer_id", "customer_name", "Item_Id", "brand",
1190
                "model_name", "model_number", "color", "selling_price", "Quantity", "total_price", "invoice_number",
1191
                "seller_name", "gst_number", "hsn_code", "igstrate", "cgstrate", "sgstrate"), rows);
33102 tejus.loha 1192
 
33143 tejus.loha 1193
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Billing Statement Report");
33102 tejus.loha 1194
 
33143 tejus.loha 1195
        return responseEntity;
33102 tejus.loha 1196
 
1197
 
33143 tejus.loha 1198
    }
33102 tejus.loha 1199
 
33143 tejus.loha 1200
    @RequestMapping(value = "/invoiceSchemeOutSummaryReport", method = RequestMethod.GET)
1201
    public String getInvoiceSchemeOutSummaryReport(HttpServletRequest request, Model model) throws Exception {
1202
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 1203
 
33143 tejus.loha 1204
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
1205
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 1206
 
33143 tejus.loha 1207
        List<FocoSchemeOutReportModel> focoSchemeOutReports = fofoOrderRepository
1208
                .selectInvoiceSchemeOutSummaryReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
1209
        LOGGER.info("focoSchemeOutReportModel {}", focoSchemeOutReports);
33102 tejus.loha 1210
 
33143 tejus.loha 1211
        model.addAttribute("startDate", currentDate.minusMonths(3).toLocalDate());
1212
        model.addAttribute("endDate", LocalDate.now());
1213
        model.addAttribute("focoSchemeOutReports", focoSchemeOutReports);
33102 tejus.loha 1214
 
33143 tejus.loha 1215
        return "invoicewise-scheme-out-report";
1216
    }
33102 tejus.loha 1217
 
33143 tejus.loha 1218
    @RequestMapping(value = "/downloadInvoiceSchemeOutSummaryReport", method = RequestMethod.GET)
1219
    public ResponseEntity<?> getDownloadInvoiceSchemeOutSummaryReport(HttpServletRequest request, Model model)
1220
            throws Exception {
1221
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 1222
 
33143 tejus.loha 1223
        List<List<?>> rows = new ArrayList<>();
1224
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
1225
        LocalDateTime currentStartMonth = currentDate.minusMonths(3).toLocalDate().atStartOfDay();
33102 tejus.loha 1226
 
33143 tejus.loha 1227
        List<FocoSchemeOutReportModel> focoSchemeOutReports = fofoOrderRepository
1228
                .selectInvoiceSchemeOutSummaryReport(fofoDetails.getFofoId(), currentStartMonth, currentDate);
1229
        LOGGER.info("focoSchemeOutReportModel {}", focoSchemeOutReports);
33102 tejus.loha 1230
 
33143 tejus.loha 1231
        for (FocoSchemeOutReportModel fsor : focoSchemeOutReports) {
1232
            rows.add(Arrays.asList(fsor.getInvoiceNumber(), fsor.getQuantity(), fsor.getBrand(), fsor.getModelName(),
1233
                    fsor.getModelNumber(), fsor.getColor(), fsor.getAmount()));
33102 tejus.loha 1234
 
33143 tejus.loha 1235
        }
33102 tejus.loha 1236
 
33143 tejus.loha 1237
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1238
                Arrays.asList("InvoiceNumber", "Quantity", "Brand", "Model Name", "Model Number", "Color", "Amount"),
1239
                rows);
33102 tejus.loha 1240
 
33143 tejus.loha 1241
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows,
1242
                "invoice wise scheme out Summary Report");
33102 tejus.loha 1243
 
33143 tejus.loha 1244
        return responseEntity;
1245
    }
33102 tejus.loha 1246
 
33143 tejus.loha 1247
    @RequestMapping(value = "/schemePayoutReportDownload", method = RequestMethod.GET)
1248
    public ResponseEntity<?> getSchemePayoutReportDownload(HttpServletRequest request,
1249
                                                           @RequestParam(defaultValue = "0") int fofoId,
1250
                                                           @RequestParam(name = "startDate") LocalDate startDate,
1251
                                                           @RequestParam(name = "endDate") LocalDate endDate, Model model)
1252
            throws Exception {
1253
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
33102 tejus.loha 1254
 
33143 tejus.loha 1255
        List<List<?>> rows = new ArrayList<>();
33102 tejus.loha 1256
 
33143 tejus.loha 1257
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
33102 tejus.loha 1258
 
33143 tejus.loha 1259
        List<SchemePayoutReportModel> schemePayoutReports = null;
1260
        if (isAdmin) {
1261
            if (fofoId == 0)
1262
                schemePayoutReports = new ArrayList<>();
1263
            else
1264
                schemePayoutReports = fofoOrderRepository
1265
                        .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
1266
        } else {
1267
            fofoId = fofoDetails.getFofoId();
1268
            schemePayoutReports = fofoOrderRepository
1269
                    .selectSchemePayoutReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
1270
        }
1271
        LOGGER.info("schemePayoutReports {}", schemePayoutReports);
33102 tejus.loha 1272
 
33143 tejus.loha 1273
        for (SchemePayoutReportModel spr : schemePayoutReports) {
33102 tejus.loha 1274
 
33143 tejus.loha 1275
            rows.add(Arrays.asList(spr.getId(), spr.getSerialNumber(), spr.getBrand(), spr.getModelName(),
1276
                    spr.getModelNumber(), spr.getColor(), spr.getSchemeInDp(), spr.getSchemeOutDp(), spr.getSchemeId(),
33646 amit.gupta 1277
                    spr.getName(), spr.getType(), spr.getAmount(), spr.getAmountType(), spr.getSioAmount(), spr.getPurchaseReference(),
33656 amit.gupta 1278
                    spr.getInvoiceNumber(), spr.getStatus(), spr.getStatusDescription(),
33646 amit.gupta 1279
                    FormattingUtils.formatDateTime(spr.getCreateTimestamp()), FormattingUtils.formatDateTime(spr.getRolledBackTimestamp())));
33102 tejus.loha 1280
 
33143 tejus.loha 1281
        }
33646 amit.gupta 1282
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("Item Id",
1283
                "Serial No", "Brand", "Model Name", "Model Number", "Color", "Scheme In Dp", "Scheme Out Dp",
33656 amit.gupta 1284
                "Scheme Id", "Name", "Scheme Type", "Amount", "Amount Type", "Amount Paid", "Purchase Invoice", "Sale Invoice", "Status",
33646 amit.gupta 1285
                "Description", "Created on", "Reversed On"), rows);
33102 tejus.loha 1286
 
33143 tejus.loha 1287
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Scheme Payout Summary Report");
33102 tejus.loha 1288
 
33143 tejus.loha 1289
        return responseEntity;
1290
    }
33102 tejus.loha 1291
 
1292
 
33143 tejus.loha 1293
    @RequestMapping(value = "/offerPayoutDumpReportDownload", method = RequestMethod.GET)
1294
    public ResponseEntity<?> getOfferPayoutDumpReportDownload(HttpServletRequest request,
1295
                                                              @RequestParam(defaultValue = "0") int fofoId,
1296
                                                              @RequestParam(name = "startDate") LocalDate startDate,
1297
                                                              @RequestParam(name = "endDate") LocalDate endDate, Model model)
1298
            throws Exception {
1299
        LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
1300
        List<List<?>> rows = new ArrayList<>();
1301
        boolean isAdmin = roleManager.isAdmin(fofoDetails.getRoleIds());
1302
        List<OfferPayoutDumpReportModel> offerPayoutReports = null;
1303
        if (isAdmin) {
1304
            if (fofoId == 0)
1305
                offerPayoutReports = new ArrayList<>();
1306
            else
1307
                offerPayoutReports = fofoOrderRepository
1308
                        .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
1309
        } else {
1310
            fofoId = fofoDetails.getFofoId();
1311
            offerPayoutReports = fofoOrderRepository
1312
                    .selectOfferPayoutDumpReport(fofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
1313
        }
33102 tejus.loha 1314
 
1315
 
33143 tejus.loha 1316
        for (OfferPayoutDumpReportModel opdr : offerPayoutReports) {
33102 tejus.loha 1317
 
33143 tejus.loha 1318
            rows.add(Arrays.asList(opdr.getId(), opdr.getBrand(), opdr.getModelName(),
1319
                    opdr.getModelNumber(), opdr.getColor(), opdr.getSerialNumber(), opdr.getOfferId(),
1320
                    opdr.getName(), opdr.getType(),
1321
                    opdr.getSlabAmount(), opdr.getAmount(), opdr.getDescription(),
1322
                    opdr.getCreateTimestamp(), opdr.getRejectTimestamp()));
33102 tejus.loha 1323
 
33143 tejus.loha 1324
        }
1325
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("Id",
1326
                "Brand", "Model Name", "Model Number", "Color", "Serial number",
1327
                "Offer Id", "Name", "Type", "Slab Amount", "Amount",
1328
                "Description", "Credited On", "Rejected On"), rows);
33102 tejus.loha 1329
 
33143 tejus.loha 1330
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Offer Payout Summary Report");
33102 tejus.loha 1331
 
33143 tejus.loha 1332
        return responseEntity;
1333
    }
33102 tejus.loha 1334
 
1335
 
33143 tejus.loha 1336
    @GetMapping("/getAllOnlineOrder")
1337
    public String getAllOrders(HttpServletRequest request, @RequestParam(required = false) LocalDate date, Model model)
1338
            throws ProfitMandiBusinessException {
1339
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1340
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1341
        if (date == null) {
1342
            date = LocalDate.now().minusDays(3);
1343
        }
33102 tejus.loha 1344
 
33143 tejus.loha 1345
        LOGGER.info("date" + date);
1346
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1347
                .collect(Collectors.toList());
33102 tejus.loha 1348
 
33143 tejus.loha 1349
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
33102 tejus.loha 1350
 
33143 tejus.loha 1351
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1352
                .filter(x -> x != null).collect(Collectors.toList()).stream()
1353
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
33102 tejus.loha 1354
 
33143 tejus.loha 1355
        model.addAttribute("customRetailersMap", customRetailersMap);
33102 tejus.loha 1356
 
33143 tejus.loha 1357
        List<PendingOrderItem> pendingOrderItem = null;
33102 tejus.loha 1358
 
33143 tejus.loha 1359
        pendingOrderItem = pendingOrderItemRepository.selectAll(date.atStartOfDay(), LocalDateTime.now());
33102 tejus.loha 1360
 
33143 tejus.loha 1361
        Map<String, Object> map = pendingOrderService.getItemOrders(pendingOrderItem, 0);
33102 tejus.loha 1362
 
33143 tejus.loha 1363
        model.addAttribute("pendingOrderItem", map.get("pendingOrderItem"));
1364
        model.addAttribute("partnerInventoryMap", map.get("partnerInventoryMap"));
1365
        model.addAttribute("date", date);
1366
        model.addAttribute("isAdmin", isAdmin);
1367
        return "online-all-order-item";
1368
    }
33102 tejus.loha 1369
 
33143 tejus.loha 1370
 
37037 amit 1371
    @RequestMapping(value = "/orderReport", method = RequestMethod.GET)
1372
    public String getOrderReport(HttpServletRequest request, Model model) throws Exception {
1373
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1374
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1375
        LocalDate startDate = LocalDate.now().withDayOfMonth(1);
1376
        LocalDate endDate = LocalDate.now();
1377
        model.addAttribute("startDate", startDate);
1378
        model.addAttribute("endDate", endDate);
1379
        model.addAttribute("isAdmin", isAdmin);
1380
        return "order-report";
1381
    }
1382
 
1383
    @RequestMapping(value = "/downloadOrderReport", method = RequestMethod.GET)
1384
    public ResponseEntity<?> getDownloadOrderReport(HttpServletRequest request,
1385
                                                    @RequestParam(name = "startDate") LocalDate startDate,
1386
                                                    @RequestParam(name = "endDate") LocalDate endDate,
1387
                                                    @RequestParam(name = "fofoId", required = false) Integer fofoId,
1388
                                                    Model model)
1389
            throws Exception {
1390
        // Period not more than a month (safety net behind the date filter)
1391
        if (endDate.isAfter(startDate.plusMonths(1))) {
1392
            endDate = startDate.plusMonths(1);
1393
        }
1394
 
1395
        // Scope: an admin may target a partner (blank fofoId = all partners); a non-admin
1396
        // is always restricted to their own store, whatever fofoId the client sends.
1397
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1398
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1399
        Integer scopedFofoId = isAdmin ? fofoId : loginDetails.getFofoId();
1400
 
1401
        List<com.spice.profitmandi.dao.entity.transaction.Order> orders =
1402
                scopedFofoId == null
1403
                        ? orderRepository.selectAllByDatesBetween(startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX))
1404
                        : orderRepository.selectAllByDatesBetween(scopedFofoId, startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX));
1405
 
1406
        List<List<?>> rows = new ArrayList<>();
1407
        rows.add(Arrays.asList(
1408
                "Order ID", "Created", "Verified", "Invoice No", "Billed By", "Billing Date", "Shipping Date",
1409
                "AWB", "Logistics Provider", "Delivery Date", "Quantity", "Amount", "Type", "Status", "Refund Reason",
1410
                "Customer ID", "Customer Name", "Customer City", "Customer Pincode", "Customer State",
1411
                "Item ID", "Product", "Logistics Txn ID", "Received Return Date", "Refund Date"));
1412
 
1413
        for (com.spice.profitmandi.dao.entity.transaction.Order o : orders) {
1414
            com.spice.profitmandi.dao.entity.transaction.LineItem li = o.getLineItem();
1415
            float amount = (o.getTotalAmount() == null ? 0f : o.getTotalAmount())
1416
                    + (o.getShippingCost() == null ? 0f : o.getShippingCost());
1417
            String product = li == null ? "" : (defaultString(li.getBrand()) + " "
1418
                    + defaultString(li.getModelName()) + " " + defaultString(li.getModelNumber())).trim();
1419
            rows.add(Arrays.asList(
1420
                    o.getId(),
1421
                    FormattingUtils.format(o.getCreateTimestamp()),
1422
                    FormattingUtils.format(o.getVerificationTimestamp()),
1423
                    o.getInvoiceNumber(),
1424
                    o.getBilledBy(),
1425
                    FormattingUtils.format(o.getBillingTimestamp()),
1426
                    FormattingUtils.format(o.getShippingTimestamp()),
1427
                    o.getAirwayBillNumber(),
1428
                    o.getLogisticsProviderId(),
1429
                    FormattingUtils.format(o.getDeliveryTimestamp()),
1430
                    li == null ? null : li.getQuantity(),
1431
                    amount,
1432
                    Boolean.TRUE.equals(o.getCod()) ? "COD" : "PREPAID",
1433
                    o.getStatusDescription(),
1434
                    o.getRefundReason(),
1435
                    o.getRetailerId(),
1436
                    o.getRetailerName(),
1437
                    o.getRetailerCity(),
1438
                    o.getRetailerPinCode(),
1439
                    o.getRetailerState(),
1440
                    li == null ? null : li.getItemId(),
1441
                    product,
1442
                    o.getLogisticsTransactionId(),
1443
                    FormattingUtils.format(o.getReceiverReturnTimestamp()),
1444
                    FormattingUtils.format(o.getRefundTimestamp())));
1445
        }
1446
 
1447
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
1448
                .getCSVByteStream(Arrays.asList("Order Report : " + startDate + " to " + endDate), rows);
1449
        return orderService.downloadReportInCsv(baos, rows, "Order Report " + startDate + " to " + endDate);
1450
    }
1451
 
1452
    private static String defaultString(String value) {
1453
        return value == null ? "" : value;
1454
    }
1455
 
33143 tejus.loha 1456
    @RequestMapping(value = "/reports", method = RequestMethod.GET)
1457
    public String reports(HttpServletRequest httpServletRequest, Model model) throws ProfitMandiBusinessException, UnsupportedOperationException, IOException {
1458
        //LoginDetails loginDetails = cookiesProcessor.getCookiesObject(httpServletRequest);
1459
        Map<ReporticoProject, List<ReporticoUrlInfo>> returnMap = ReporticoProject.reporticoProjectMap;
28137 amit.gupta 1460
		/*if(fofoStoreRepository.getWarehousePartnerMap().get(7720).stream().filter(x->x.getId()==loginDetails.getFofoId()).count() > 0) {
28106 amit.gupta 1461
			Map<ReporticoProject, List<ReporticoUrlInfo>> returnMap1 = new HashMap<ReporticoProject, List<ReporticoUrlInfo>>();
1462
			returnMap1.put(ReporticoProject.FOCO, returnMap.get(ReporticoProject.FOCO));
1463
			returnMap1.put(ReporticoProject.FOCOR, returnMap.get(ReporticoProject.FOCOR).stream().skip(1).collect(Collectors.toList()));
28107 amit.gupta 1464
			returnMap = returnMap1;
28137 amit.gupta 1465
		}*/
33143 tejus.loha 1466
        model.addAttribute("reporticoProjectMap", returnMap);
1467
        return "reports";
1468
    }
33775 ranu 1469
 
1470
    @RequestMapping(value = "/account-statement", method = RequestMethod.GET)
1471
    public String accountStatement(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
1472
                                   @RequestParam(required = false) LocalDate startDate,
1473
                                   @RequestParam(required = false) LocalDate endDate)
1474
            throws Exception {
1475
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1476
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1477
 
34069 aman.kumar 1478
        boolean isRBM = false;
1479
        if (isAdmin) {
34096 aman.kumar 1480
            AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1481
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 1482
            isRBM = positions.stream()
34096 aman.kumar 1483
                    .anyMatch(position ->
1484
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
1485
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 1486
            if (isRBM && pp.containsKey(authUser.getId())) {
34096 aman.kumar 1487
                Set<Integer> fofoIds = new HashSet<>(pp.get(authUser.getId()));
1488
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> {
1489
                    try {
1490
                        return retailerService.getFofoRetailers(true).get(x);
1491
                    } catch (ProfitMandiBusinessException e) {
1492
                        // TODO Auto-generated catch block
1493
                        return null;
1494
                    }
1495
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1496
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 1497
            }
34066 aman.kumar 1498
        }
1499
 
33775 ranu 1500
        model.addAttribute("isAdmin", isAdmin);
34066 aman.kumar 1501
        model.addAttribute("isRBM", isRBM);
33775 ranu 1502
 
1503
        return "partner-account-statement";
1504
 
1505
    }
1506
 
1507
    @RequestMapping(value = "/account-statement-report", method = RequestMethod.GET)
1508
    public String getPartnerAccountStatement(HttpServletRequest request, @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate, Model model, @RequestParam(defaultValue = "0") int fofoId) throws Exception {
1509
        boolean isAdmin = roleManager.isAdmin(cookiesProcessor.getCookiesObject(request).getRoleIds());
1510
        if (fofoId > 0) {
1511
            if (!isAdmin) {
1512
                throw new ProfitMandiBusinessException("Unauthorised access", "PartnerId", "Permission Denied");
1513
            }
1514
        } else {
1515
            fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1516
        }
1517
        float openingBalance = walletService.getOpeningTill(fofoId, startDate);
1518
        float closingBalance = walletService.getOpeningTill(fofoId, endDate);
1519
        UserWallet uw = walletService.getUserWallet(fofoId);
1520
        LOGGER.info("Start date - {}, end Date - {}", startDate, endDate);
1521
 
1522
        List<UserWalletHistory> history = userWalletHistoryRepository.selectPaginatedByWalletId(uw.getId(), startDate, endDate, 0, 0);
1523
 
1524
        history = history.stream().filter(x -> !x.getReferenceType().equals(WalletReferenceType.PURCHASE))
1525
                .filter(x -> !WalletService.CN_WALLET_REFERENCES.contains(x.getReferenceType())).sorted(Comparator.comparing(UserWalletHistory::getId)).collect(Collectors.toList());
1526
        Map<LocalDate, List<UserWalletHistory>> dateWalletMap = history.stream().collect(Collectors.groupingBy(x -> x.getTimestamp().toLocalDate()));
1527
        CustomRetailer customRetailer = retailerService.getAllFofoRetailers().get(fofoId);
1528
        List<StatementDetailModel> billedStatementDetails = orderRepository.selectDetailsBetween(fofoId, startDate, endDate);
1529
        Map<Integer, Float> openingAmountMap = transactionService.getPendingIndentValueMap(startDate, Optional.of(fofoId));
1530
        Map<Integer, Float> closingAmountMap = transactionService.getPendingIndentValueMap(endDate, Optional.of(fofoId));
1531
 
1532
        float openingPendingAmount = openingAmountMap.get(fofoId) == null ? 0 : openingAmountMap.get(fofoId);
1533
        float closingPendingAmount = closingAmountMap.get(fofoId) == null ? 0 : closingAmountMap.get(fofoId);
1534
        LOGGER.info("Opening - {}, Closing - {}", openingPendingAmount, closingPendingAmount);
1535
 
1536
        double grandTotalDebit = 0;
1537
        double grandTotalCredit = 0;
1538
 
1539
        for (UserWalletHistory walletEntry : history) {
1540
            if (walletEntry.getAmount() < 0) {
1541
                grandTotalDebit += Math.abs(walletEntry.getAmount());
1542
            } else {
1543
                grandTotalCredit += walletEntry.getAmount();
1544
            }
1545
        }
1546
 
1547
        for (StatementDetailModel statement : billedStatementDetails) {
1548
            if (statement.getAmount() < 0) {
1549
                grandTotalCredit += Math.abs(statement.getAmount());
1550
            } else {
1551
                grandTotalDebit += statement.getAmount();
1552
            }
1553
        }
1554
 
1555
        model.addAttribute("billedStatementDetails", billedStatementDetails);
1556
        model.addAttribute("customRetailer", customRetailer);
1557
        model.addAttribute("wallethistory", history);
1558
        model.addAttribute("startDate", startDate);
1559
        model.addAttribute("endDate", endDate);
1560
        model.addAttribute("dateWalletMap", dateWalletMap);
1561
        model.addAttribute("openingBalance", (openingBalance + openingPendingAmount));
1562
        model.addAttribute("closingBalance", (closingBalance + closingPendingAmount));
1563
        model.addAttribute("grandTotalDebit", grandTotalDebit);
1564
        model.addAttribute("grandTotalCredit", grandTotalCredit);
1565
 
1566
        return "account-statement-list";
1567
    }
33809 ranu 1568
 
1569
    @RequestMapping(value = "/loan/loan-statement", method = RequestMethod.GET)
33814 ranu 1570
    public String loanStatement(HttpServletRequest request, Model model)
33809 ranu 1571
            throws Exception {
1572
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1573
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
34069 aman.kumar 1574
        boolean isRBM = false;
1575
        if (isAdmin) {
34096 aman.kumar 1576
            AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1577
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
34069 aman.kumar 1578
            isRBM = positions.stream()
34096 aman.kumar 1579
                    .anyMatch(position ->
1580
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
1581
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
34069 aman.kumar 1582
            if (isRBM && pp.containsKey(authUser.getId())) {
1583
                List<Integer> fofoIds = pp.get(authUser.getId());
34096 aman.kumar 1584
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(fofoId -> {
1585
                    try {
1586
                        return retailerService.getFofoRetailers(true).get(fofoId);
1587
                    } catch (ProfitMandiBusinessException e) {
1588
                        // TODO Auto-generated catch block
1589
                        return null;
1590
                    }
1591
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1592
                model.addAttribute("customRetailersMap", customRetailersMap);
34069 aman.kumar 1593
            }
34066 aman.kumar 1594
        }
1595
        model.addAttribute("isRBM", isRBM);
33809 ranu 1596
        model.addAttribute("isAdmin", isAdmin);
1597
 
1598
        return "partner-loan-statement";
1599
 
1600
    }
1601
 
1602
    @RequestMapping(value = "/loan/partner-loan-statement-report", method = RequestMethod.GET)
1603
    public String partnerLoanStatement(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
1604
                                       @RequestParam(required = false) LocalDateTime startDate,
1605
                                       @RequestParam(required = false) LocalDateTime endDate)
1606
            throws Exception {
1607
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1608
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1609
        int partnerId = 0;
1610
 
1611
        if (fofoId > 0) {
1612
            partnerId = fofoId;
1613
        } else {
1614
            partnerId = loginDetails.getFofoId();
1615
        }
1616
 
1617
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(partnerId);
1618
 
1619
        List<LoanStatementReportModel> loanStatementReportModels = loanStatementRepository.selectByDatesAndStoreCode(startDate, endDate, fofoStore.getCode());
1620
 
1621
        model.addAttribute("isAdmin", isAdmin);
1622
        model.addAttribute("loanStatementReportModels", loanStatementReportModels);
1623
 
1624
        return "partner-loan-statement-summary";
1625
 
1626
    }
1627
 
1628
    @RequestMapping(value = "/loan/download-partner-loan-statement-report", method = RequestMethod.GET)
1629
    public ResponseEntity<?> downloadPartnerLoanStatement(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
1630
                                                          @RequestParam(required = false) LocalDateTime startDate,
1631
                                                          @RequestParam(required = false) LocalDateTime endDate)
1632
            throws Exception {
1633
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1634
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1635
 
1636
        int partnerId = 0;
1637
 
1638
        if (fofoId > 0) {
1639
            partnerId = fofoId;
1640
        } else {
1641
            partnerId = loginDetails.getFofoId();
1642
        }
1643
 
1644
        FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(partnerId);
1645
 
1646
        List<List<?>> rows = new ArrayList<>();
1647
 
1648
        List<LoanStatementReportModel> loanStatementReportModels = loanStatementRepository.selectByDatesAndStoreCode(startDate, endDate, fofoStore.getCode());// Extract the store name from the first loan statement
1649
        String storeName = loanStatementReportModels.get(0).getStoreName();
34713 aman.kumar 1650
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
33809 ranu 1651
        for (LoanStatementReportModel loanStatement : loanStatementReportModels) {
1652
            rows.add(Arrays.asList(
1653
                    loanStatement.getCode(),  // Code
1654
                    String.valueOf(loanStatement.getId()),  // ID (convert int to string)
1655
                    loanStatement.getStoreName(),  // Store Name
1656
                    loanStatement.getState(),  // State
1657
                    loanStatement.getZone(),  // Zone
1658
                    loanStatement.getArea(),  // Area
1659
                    loanStatement.getTerritory(),  // Territory
1660
                    String.valueOf(loanStatement.getLoanId()),  // Loan ID
1661
                    loanStatement.getInterestRate().toString(),  // Interest Rate (BigDecimal to String)
1662
                    loanStatement.getIntialAmount().toString(),  // Initial Amount (BigDecimal to String)
1663
                    loanStatement.getPendingAmount().toString(),  // Pending Amount (BigDecimal to String)
34713 aman.kumar 1664
                    loanStatement.getInvoiceNumber() != null ? loanStatement.getInvoiceNumber() : "-", // Invoice Number
33809 ranu 1665
                    loanStatement.getCreatedOn().format(dateTimeFormatter),  // Created On (format LocalDateTime)
1666
                    loanStatement.getDueDate().format(dateTimeFormatter),  // Due Date (format LocalDateTime)
1667
                    loanStatement.getInterestAccrued().toString(),  // Interest Accrued (BigDecimal to String)
1668
                    loanStatement.getInterestPaid().toString(),  // Interest Paid (BigDecimal to String)
1669
                    String.valueOf(loanStatement.getFreeDays()),  // Free Days (convert int to string)
1670
                    loanStatement.getLoanReferenceType().toString(),  // Loan Reference Type (enum or string)
1671
                    loanStatement.getAmount().toString(),  // Amount (BigDecimal to String)
1672
                    loanStatement.getBusinessDate().format(dateTimeFormatter),  // Business Date (format LocalDateTime)
1673
                    loanStatement.getCreatedAt().format(dateTimeFormatter),  // Created At (format LocalDateTime)
1674
                    loanStatement.getDescription(),  // Description
1675
                    loanStatement.getStatus()  // Status (calculated value)
1676
            ));
1677
        }
1678
 
1679
        // Set up the headers and create the CSV
34728 amit.gupta 1680
        List<String> headers = Arrays.asList("Code", "ID", "Store Name", "State", "Zone", "Area", "Territory", "Credit ID",
34713 aman.kumar 1681
                "Interest Rate", "Initial Amount", "Pending Amount", "Invoice Number", "Created On", "Due Date",
34728 amit.gupta 1682
                "Interest Accrued", "Interest Paid", "Free Days", "Credit Reference Type",
33809 ranu 1683
                "Amount", "Business Date", "Created At", "Description", "Status");
1684
 
1685
        // Create the CSV byte stream
1686
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(headers, rows);
34728 amit.gupta 1687
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Partner Credit Summary Report");
33809 ranu 1688
 
1689
        return responseEntity;
1690
 
1691
    }
34236 ranu 1692
 
1693
    @RequestMapping(value = "/report/credit-note", method = RequestMethod.GET)
1694
    public String creditNote(HttpServletRequest request, Model model)
1695
            throws Exception {
1696
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1697
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1698
        boolean isRBM = false;
1699
        if (isAdmin) {
1700
            AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1701
            List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId());
1702
            isRBM = positions.stream()
1703
                    .anyMatch(position ->
1704
                            ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId());
1705
            Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1706
            if (isRBM && pp.containsKey(authUser.getId())) {
1707
                List<Integer> fofoIds = pp.get(authUser.getId());
1708
                Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(fofoId -> {
1709
                    try {
1710
                        return retailerService.getFofoRetailers(true).get(fofoId);
1711
                    } catch (ProfitMandiBusinessException e) {
1712
                        // TODO Auto-generated catch block
1713
                        return null;
1714
                    }
1715
                }).filter(x -> x != null).collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
1716
                model.addAttribute("customRetailersMap", customRetailersMap);
1717
            }
1718
        }
1719
        model.addAttribute("isRBM", isRBM);
1720
        model.addAttribute("isAdmin", isAdmin);
1721
 
1722
        return "credit-note";
1723
 
1724
    }
1725
 
1726
 
1727
    @RequestMapping(value = "/credit/credit-note-report", method = RequestMethod.GET)
1728
    public String creditNoteReport(HttpServletRequest request, Model model, @RequestParam(defaultValue = "0") int fofoId,
1729
                                   @RequestParam(required = false) YearMonth yearMonth)
1730
            throws Exception {
1731
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1732
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1733
        int partnerId = 0;
1734
 
1735
        if (fofoId > 0) {
1736
            partnerId = fofoId;
1737
        } else {
1738
            partnerId = loginDetails.getFofoId();
1739
        }
1740
 
1741
        LOGGER.info("partnerId: " + partnerId + " yearMonth: " + yearMonth);
1742
 
1743
        List<CreditNote> creditNotes = creditNoteRepository.selectAll(partnerId, yearMonth);
1744
 
1745
        model.addAttribute("isAdmin", isAdmin);
1746
        model.addAttribute("creditNotes", creditNotes);
1747
 
1748
        return "credit-note-list";
1749
 
1750
    }
1751
 
1752
    @RequestMapping(value = "/credit-note/download", method = RequestMethod.GET)
1753
    public ResponseEntity<?> downloadCreditNote(@RequestParam("cnNumber") String cnNumber) {
1754
        try {
1755
            CreditNote creditNote = creditNoteRepository.selectByCreditNoteNumber(cnNumber);
1756
 
1757
            YearMonth yearMonth = YearMonth.from(creditNote.getCnDate());
1758
            int fofoId = creditNote.getFofoId();
1759
 
1760
            Utils.Attachment attachment = creditNoteService.downloadCN(creditNote, yearMonth, fofoId);
1761
 
1762
            return ResponseEntity.ok()
1763
                    .contentType(MediaType.APPLICATION_PDF)
1764
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + attachment.getFileName() + "\"")
1765
                    .body(attachment.getInputStreamSource());
1766
        } catch (Exception e) {
1767
            e.printStackTrace();
1768
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error generating PDF: " + e.getMessage());
1769
        }
1770
    }
1771
 
34256 ranu 1772
    @RequestMapping(value = "/credit-note/attachements", method = RequestMethod.GET)
1773
    public ResponseEntity<?> getCnAttachements(@RequestParam("cnNumber") String cnNumber) throws Exception {
1774
        CreditNote creditNote = creditNoteRepository.selectByCreditNoteNumber(cnNumber);
1775
        YearMonth yearMonth = YearMonth.from(creditNote.getCnDate());
1776
        int fofoId = creditNote.getFofoId();
1777
 
1778
        List<InventoryMarginModel> allOffers = offerPayoutRepository.getPaidOffers(yearMonth, fofoId);
1779
        List<InventoryMarginModel> allPriceDrops = priceDropIMEIRepository.selectPaidPriceDrops(yearMonth, fofoId);
1780
        List<InventoryMarginModel> schemeMarginsInventoryModel = schemeInOutRepository.getPaidMargins(yearMonth, fofoId);
1781
 
1782
        List<InventoryMarginModel> allInventoryMarginModels = new ArrayList<>();
1783
        allInventoryMarginModels.addAll(schemeMarginsInventoryModel);
1784
        allInventoryMarginModels.addAll(allPriceDrops);
1785
        allInventoryMarginModels.addAll(allOffers);
1786
 
36708 aman 1787
        List<List<?>> rows = allInventoryMarginModels.stream()
1788
                .map(InventoryMarginModel::toRow)
1789
                .map(row -> (List<?>) row.subList(0, 10))
1790
                .collect(Collectors.toList());
34256 ranu 1791
 
36708 aman 1792
        List<List<String>> headerRows = Arrays.asList(
1793
                Arrays.asList("CN Number:", cnNumber),
1794
                Collections.emptyList(),
1795
                Arrays.asList("CN Number", "FofoId", "InvoiceNo", "SerialNumber", "Margin", "Description",
1796
                        "CGST", "SGST", "IGST", "Credited On")
34256 ranu 1797
        );
1798
 
36708 aman 1799
        org.apache.commons.io.output.ByteArrayOutputStream byteArrayOutputStream =
1800
                FileUtil.getCSVByteStreamWithMultiHeaders(headerRows, rows);
1801
 
1802
        return orderService.downloadReportInCsv(byteArrayOutputStream, rows, "CN Detail Report");
34256 ranu 1803
    }
1804
 
36198 amit 1805
    @RequestMapping(value = "/credit-note/download-all", method = RequestMethod.GET)
1806
    public ResponseEntity<?> downloadAllCreditNotes(HttpServletRequest request,
1807
            @RequestParam("yearMonth") YearMonth yearMonth) throws Exception {
1808
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1809
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
1810
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Admin access required");
1811
        }
34256 ranu 1812
 
36198 amit 1813
        List<CreditNote> creditNotes = creditNoteRepository.selectAllMarginsTypeByMonth(yearMonth);
1814
        if (creditNotes.isEmpty()) {
1815
            return ResponseEntity.noContent().build();
1816
        }
34256 ranu 1817
 
36198 amit 1818
        // Bulk-fetch IRN and line items
1819
        List<String> cnNumbers = creditNotes.stream().map(CreditNote::getCreditNoteNumber).collect(Collectors.toList());
1820
        Map<String, com.spice.profitmandi.dao.entity.transaction.EInvoiceDetails> eiMap =
1821
                eInvoiceDetailsRepository.selectByInvoiceNumbers(cnNumbers).stream()
1822
                        .collect(Collectors.toMap(com.spice.profitmandi.dao.entity.transaction.EInvoiceDetails::getInvoiceNumber, e -> e, (a, b) -> a));
1823
        List<Integer> cnIds = creditNotes.stream().map(CreditNote::getId).collect(Collectors.toList());
1824
        Map<Integer, List<com.spice.profitmandi.dao.entity.transaction.CreditNoteLine>> linesMap =
1825
                creditNoteLineRepository.selectAllByCreditNoteIds(cnIds).stream()
1826
                        .collect(Collectors.groupingBy(com.spice.profitmandi.dao.entity.transaction.CreditNoteLine::getCreditNoteId));
1827
 
1828
        // Build partner lookup
1829
        Map<Integer, com.spice.profitmandi.common.model.CustomRetailer> retailers = retailerService.getAllFofoRetailers();
1830
 
1831
        List<List<?>> rows = new ArrayList<>();
1832
        for (CreditNote cn : creditNotes) {
1833
            com.spice.profitmandi.dao.entity.transaction.EInvoiceDetails ei = eiMap.get(cn.getCreditNoteNumber());
1834
            List<com.spice.profitmandi.dao.entity.transaction.CreditNoteLine> lines =
1835
                    linesMap.getOrDefault(cn.getId(), java.util.Collections.emptyList());
1836
            float total = (float) lines.stream().mapToDouble(l -> l.getAmount()).sum();
1837
            com.spice.profitmandi.common.model.CustomRetailer retailer = retailers.get(cn.getFofoId());
1838
            String partnerName = retailer != null ? retailer.getBusinessName() : "";
1839
            String partnerCode = retailer != null ? retailer.getCode() : "";
1840
 
1841
            rows.add(Arrays.asList(
1842
                    cn.getCreditNoteNumber(),
1843
                    cn.getFofoId(),
1844
                    partnerCode,
1845
                    partnerName,
1846
                    com.spice.profitmandi.common.util.FormattingUtils.formatDDMMMyyyyFormatter(cn.getCnDate().toLocalDate()),
1847
                    cn.getType(),
1848
                    Math.round(total),
1849
                    ei != null ? ei.getIrn() : "",
1850
                    ei != null ? ei.getAcknowledgeNumber() : "",
1851
                    ei != null && ei.getAcknowledgeDate() != null
1852
                            ? com.spice.profitmandi.common.util.FormattingUtils.formatDDMMMyyyyFormatter(ei.getAcknowledgeDate().toLocalDate())
1853
                            : ""
1854
            ));
1855
        }
1856
 
1857
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1858
                Arrays.asList("CN Number", "FofoId", "Partner Code", "Partner Name", "CN Date", "CN Type",
1859
                        "Total Amount", "IRN", "Ack Number", "IRN Ack Date"),
1860
                rows);
1861
 
1862
        return orderService.downloadReportInCsv(baos, rows,
1863
                "CN Summary Report - " + yearMonth.toString());
1864
    }
1865
 
23612 amit.gupta 1866
}