Subversion Repositories SmartDukaan

Rev

Rev 35771 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
22860 ashik.ali 1
package com.spice.profitmandi.web.controller;
2
 
31147 tejbeer 3
import com.google.gson.Gson;
33795 ranu 4
import com.spice.profitmandi.common.enumuration.OfferType;
29585 manish 5
import com.spice.profitmandi.common.enumuration.ReporticoProject;
22860 ashik.ali 6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
31352 amit.gupta 7
import com.spice.profitmandi.common.model.*;
29585 manish 8
import com.spice.profitmandi.common.services.ReporticoService;
30326 amit.gupta 9
import com.spice.profitmandi.common.util.ExcelUtils;
10
import com.spice.profitmandi.common.util.FileUtil;
11
import com.spice.profitmandi.common.util.FormattingUtils;
23784 ashik.ali 12
import com.spice.profitmandi.common.web.util.ResponseSender;
31170 amit.gupta 13
import com.spice.profitmandi.dao.entity.catalog.*;
14
import com.spice.profitmandi.dao.entity.cs.Region;
15
import com.spice.profitmandi.dao.entity.fofo.*;
28795 tejbeer 16
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
17
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
27389 amit.gupta 18
import com.spice.profitmandi.dao.enumuration.catalog.AmountType;
28491 amit.gupta 19
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
29707 tejbeer 20
import com.spice.profitmandi.dao.enumuration.catalog.UpgradeOfferStatus;
29899 tejbeer 21
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
29585 manish 22
import com.spice.profitmandi.dao.enumuration.transaction.SchemePayoutStatus;
31170 amit.gupta 23
import com.spice.profitmandi.dao.model.*;
24
import com.spice.profitmandi.dao.repository.catalog.*;
29899 tejbeer 25
import com.spice.profitmandi.dao.repository.cs.CsService;
31170 amit.gupta 26
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
26588 tejbeer 27
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
28
import com.spice.profitmandi.dao.repository.dtr.Mongo;
31170 amit.gupta 29
import com.spice.profitmandi.dao.repository.fofo.*;
28795 tejbeer 30
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
31
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
30768 amit.gupta 32
import com.spice.profitmandi.dao.repository.transaction.TransactionRepository;
23798 amit.gupta 33
import com.spice.profitmandi.service.authentication.RoleManager;
23020 ashik.ali 34
import com.spice.profitmandi.service.inventory.InventoryService;
27876 amit.gupta 35
import com.spice.profitmandi.service.offers.OfferService;
31147 tejbeer 36
import com.spice.profitmandi.service.offers.PartnerCriteria;
32331 amit.gupta 37
import com.spice.profitmandi.service.pricecircular.PriceCircularModel;
32232 amit.gupta 38
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
22860 ashik.ali 39
import com.spice.profitmandi.service.scheme.SchemeService;
26588 tejbeer 40
import com.spice.profitmandi.service.user.RetailerService;
29585 manish 41
import com.spice.profitmandi.service.wallet.WalletService;
22860 ashik.ali 42
import com.spice.profitmandi.web.model.LoginDetails;
43
import com.spice.profitmandi.web.util.CookiesProcessor;
23570 amit.gupta 44
import com.spice.profitmandi.web.util.MVCResponseSender;
29585 manish 45
import in.shop2020.model.v1.order.WalletReferenceType;
31170 amit.gupta 46
import org.apache.commons.csv.CSVRecord;
47
import org.apache.commons.lang.StringUtils;
48
import org.apache.logging.log4j.LogManager;
49
import org.apache.logging.log4j.Logger;
50
import org.springframework.beans.factory.annotation.Autowired;
51
import org.springframework.beans.factory.annotation.Qualifier;
52
import org.springframework.core.io.InputStreamResource;
53
import org.springframework.http.HttpHeaders;
54
import org.springframework.http.HttpStatus;
55
import org.springframework.http.ResponseEntity;
56
import org.springframework.stereotype.Controller;
35771 ranu 57
import org.springframework.transaction.annotation.Transactional;
31170 amit.gupta 58
import org.springframework.ui.Model;
59
import org.springframework.web.bind.annotation.*;
60
import org.springframework.web.multipart.MultipartFile;
29585 manish 61
 
31170 amit.gupta 62
import javax.servlet.http.HttpServletRequest;
63
import javax.servlet.http.HttpServletResponse;
64
import java.io.ByteArrayInputStream;
65
import java.io.ByteArrayOutputStream;
66
import java.io.InputStream;
67
import java.time.*;
68
import java.time.format.DateTimeFormatter;
69
import java.util.*;
70
import java.util.stream.Collectors;
71
 
22860 ashik.ali 72
@Controller
35458 amit 73
@Transactional(rollbackFor = Throwable.class)
22860 ashik.ali 74
public class SchemeController {
31352 amit.gupta 75
    // LED TV
76
    private static final List<Integer> categoryIds = Arrays.asList(ProfitMandiConstants.MOBILE_CATEGORY_ID,
77
            ProfitMandiConstants.TABLET_CATEGORY_ID, 14202);
22860 ashik.ali 78
 
34317 amit.gupta 79
    private static List<SchemeType> EXCLUDE_EXTEND_SCHEMES = Arrays.asList(SchemeType.SELLOUT, SchemeType.SPECIAL_SUPPORT, SchemeType.SELLIN);
31387 amit.gupta 80
 
31352 amit.gupta 81
    private static final Logger LOGGER = LogManager.getLogger(SchemeController.class);
82
    @Autowired
83
    WalletService walletService;
84
    @Autowired
85
    PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
86
    @Autowired
87
    InventoryItemRepository inventoryItemRepository;
88
    @Autowired
89
    PriceDropIMEIRepository priceDropIMEIRepository;
90
    @Autowired
91
    PriceDropRepository priceDropRepository;
92
    @Autowired
93
    SchemeInOutRepository schemeInOutRepository;
34211 vikas.jang 94
    List<String> adminEmail = Arrays.asList("tarun.verma@smartdukaan.com", "neeraj.gupta@smartdukaan.com", "amit.gupta@smartdukaan.com", "vikas.jangra@smartdukaan.com", "deena.nath@smartdukaan.com");
31352 amit.gupta 95
    @Autowired
96
    SchemeRegionRepository schemeRegionRepository;
97
    @Autowired
98
    RegionRepository regionRepository;
99
    @Autowired
100
    TransactionRepository transactionRepository;
101
    @Autowired
102
    private SchemeService schemeService;
103
    @Autowired
104
    private OfferService offerService;
105
    @Autowired
106
    private StateGstRateRepository stateGstRateRepository;
107
    @Autowired
108
    private ItemRepository itemRepository;
109
    @Autowired
110
    private ReporticoService reporticoService;
111
    @Autowired
112
    private SchemeRepository schemeRepository;
113
    @Autowired
114
    private SchemeItemRepository schemeItemRepository;
115
    @Autowired
116
    private MVCResponseSender mvcResponseSender;
117
    @Autowired
118
    private CookiesProcessor cookiesProcessor;
119
    @Autowired
120
    @Qualifier("fofoInventoryService")
121
    private InventoryService inventoryService;
122
    @Autowired
123
    private TagListingRepository tagListingRepository;
124
    @Autowired
125
    private RoleManager roleManager;
126
    @Autowired
127
    private ResponseSender<?> responseSender;
128
    @Autowired
129
    private FofoStoreRepository fofoStoreRepository;
130
    @Autowired
131
    private OfferPayoutRepository offerPayoutRepository;
132
    @Autowired
133
    private RetailerService retailerService;
134
    @Autowired
135
    private Mongo mongoClient;
136
    @Autowired
137
    private PartnerTypeChangeService partnerTypeChangeService;
138
    @Autowired
139
    private CustomerOfferRepository customerOfferRepository;
140
    @Autowired
141
    private CustomerOfferItemRepository customerOfferItemRepository;
142
    @Autowired
143
    private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
144
    @Autowired
145
    private CsService csService;
146
    @Autowired
147
    private CategoryRepository categoryRepository;
32232 amit.gupta 148
 
31352 amit.gupta 149
    @Autowired
32232 amit.gupta 150
    PriceCircularService priceCircularService;
33030 amit.gupta 151
    @Autowired
32299 jai.hind 152
    private FofoOrderRepository fofoOrderRepository;
33030 amit.gupta 153
    @Autowired
32299 jai.hind 154
    private PurchaseRepository purchaseRepository;
32232 amit.gupta 155
 
156
 
157
    @Autowired
31352 amit.gupta 158
    private Gson gson;
22860 ashik.ali 159
 
31352 amit.gupta 160
    private boolean getAccess(String emailId) {
27897 amit.gupta 161
 
31352 amit.gupta 162
        boolean fullAccesss = false;
163
        List<String> emails = csService
164
                .getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, EscalationType.L3).stream()
165
                .map(x -> x.getEmailId()).collect(Collectors.toList());
23786 amit.gupta 166
 
31352 amit.gupta 167
        emails.addAll(
168
                csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_CATEGORY, EscalationType.L2)
169
                        .stream().map(x -> x.getEmailId()).collect(Collectors.toList()));
27612 tejbeer 170
 
31352 amit.gupta 171
        if (adminEmail.contains(emailId)) {
172
            fullAccesss = true;
173
        }
29608 amit.gupta 174
 
31352 amit.gupta 175
        if (emails.contains(emailId)) {
176
            fullAccesss = false;
177
        }
27612 tejbeer 178
 
31352 amit.gupta 179
        return fullAccesss;
22860 ashik.ali 180
 
31352 amit.gupta 181
    }
23786 amit.gupta 182
 
31352 amit.gupta 183
    @RequestMapping(value = "/getBrandsByCategory", method = RequestMethod.GET)
184
    public String getTagListingItemsByBrand(HttpServletRequest request, @RequestParam int categoryId, Model model)
185
            throws Exception {
186
        Set<String> brands = inventoryService.getAllTagListingBrands(categoryId);
187
        model.addAttribute("brands", brands);
188
        model.addAttribute("categoryId", categoryId);
23786 amit.gupta 189
 
31352 amit.gupta 190
        return "tag-listing-brands";
191
    }
23786 amit.gupta 192
 
31352 amit.gupta 193
    @RequestMapping(value = "/schemes/update-schemes-page", method = RequestMethod.GET)
194
    public String updateShcemes(HttpServletRequest request) throws ProfitMandiBusinessException {
195
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
196
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
197
            throw new ProfitMandiBusinessException("User", loginDetails.getEmailId(), "Unauthorised access");
198
        }
199
        return "update-schemes-page";
200
    }
33030 amit.gupta 201
 
32299 jai.hind 202
    @RequestMapping(value = "/schemes/process-sellout", method = RequestMethod.POST)
203
    public String processSellout(HttpServletRequest request, Model model, @RequestBody List<String> invoiceNumbers) throws Exception {
204
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
205
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
206
            throw new ProfitMandiBusinessException("User", loginDetails.getEmailId(), "Unauthorised access");
207
        }
208
        for (String invoiceNumber : invoiceNumbers) {
209
            FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
210
            schemeService.processSchemeOut(fofoOrder.getId(), fofoOrder.getFofoId());
211
        }
212
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
213
        return "response";
214
    }
23556 amit.gupta 215
 
32299 jai.hind 216
    @RequestMapping(value = "/schemes/process-sellin", method = RequestMethod.POST)
217
    public String processSellin(HttpServletRequest request, Model model, @RequestBody List<String> invoiceNumbers) throws Exception {
218
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
219
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
220
            throw new ProfitMandiBusinessException("User", loginDetails.getEmailId(), "Unauthorised access");
221
        }
222
        for (String invoiceNumber : invoiceNumbers) {
223
            Purchase purchase = purchaseRepository.selectByPurchaseReference(invoiceNumber);
224
            schemeService.processSchemeIn(purchase.getId(), purchase.getFofoId());
225
        }
226
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
227
        return "response";
228
    }
229
 
31352 amit.gupta 230
    @RequestMapping(value = "/payMonthlyInvestment", method = RequestMethod.POST)
231
    public void payMonthlyInvestment(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
23914 govind 232
 
31352 amit.gupta 233
        LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
234
        LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
235
        int referenceId = Integer.parseInt(FormattingUtils.getYearMonth(startOfPreviousMonth.atStartOfDay()));
236
        LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
237
        List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
238
                .selectAll(startOfPreviousMonth, lastOfPreviousMonth);
239
        Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
240
                .filter(x -> x.getShortPercentage() <= 10)
241
                .collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
242
        LOGGER.info("investmentMaintainedDaysMap {}", investmentMaintainedDaysMap);
243
        List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectAllPending(SchemeType.INVESTMENT,
244
                startOfPreviousMonth.atStartOfDay(), firstDateOfCurrentMonth.atStartOfDay());
23786 amit.gupta 245
 
31352 amit.gupta 246
        if (schemeInOuts.isEmpty()) {
247
            throw new ProfitMandiBusinessException("Investment Payout", "", "No data Found");
248
        }
23786 amit.gupta 249
 
31352 amit.gupta 250
        Map<Integer, List<SchemeInOut>> inventoryItemIdSchemeMap = schemeInOuts.stream()
251
                .collect(Collectors.groupingBy(x -> x.getInventoryItemId()));
252
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIdSchemeMap.keySet());
253
        Map<Integer, List<Integer>> retailerInventoryItemIdMap = inventoryItems.stream().collect(
254
                Collectors.groupingBy(x -> x.getFofoId(), Collectors.mapping(x -> x.getId(), Collectors.toList())));
255
        System.out.println("Fofo Id\tInvestment Maintained Days\tEligible payout");
256
        for (Map.Entry<Integer, List<Integer>> retailerEntry : retailerInventoryItemIdMap.entrySet()) {
257
            int fofoId = retailerEntry.getKey();
258
            long investmentMaintainedDays = investmentMaintainedDaysMap.get(fofoId) == null ? 0
259
                    : investmentMaintainedDaysMap.get(fofoId);
23786 amit.gupta 260
 
31352 amit.gupta 261
            List<SchemeInOut> schemeInouts = retailerEntry.getValue().stream().map(x -> inventoryItemIdSchemeMap.get(x))
262
                    .flatMap(List::stream)
263
                    .filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING) && x.getRolledBackTimestamp() == null)
264
                    .collect(Collectors.toList());
265
            float totalAmount = 0;
266
            LocalDateTime firstBillingDate = transactionRepository.getFirstBillingDate(fofoId);
267
            boolean sameYearMonth = firstBillingDate.getMonth() == startOfPreviousMonth.getMonth()
268
                    && firstBillingDate.getYear() == startOfPreviousMonth.getYear();
269
            for (SchemeInOut sio : schemeInouts) {
270
                if (sameYearMonth) {
271
                    sio.setStatusDescription("Investment payout fully disbursed for first month");
272
                    sio.setStatus(SchemePayoutStatus.CREDITED);
273
                    sio.setCreditTimestamp(LocalDateTime.now());
274
                    totalAmount += sio.getAmount();
275
                } else {
276
                    if (investmentMaintainedDays < 8) {
277
                        sio.setStatus(SchemePayoutStatus.REJECTED);
278
                        // sio.setRolledBackTimestamp(LocalDateTime.now());
279
                        sio.setStatusDescription(
280
                                "Investment maintained for " + investmentMaintainedDays + "(< 8) days");
281
                    } else if (investmentMaintainedDays < 12) {
282
                        sio.setStatus(SchemePayoutStatus.CREDITED);
283
                        sio.setAmount(sio.getAmount() / 2);
284
                        sio.setCreditTimestamp(LocalDateTime.now());
285
                        sio.setStatusDescription(
286
                                "Investment maintained for " + investmentMaintainedDays + "(< 12) days");
287
                        totalAmount += sio.getAmount();
288
                    } else {
289
                        sio.setStatus(SchemePayoutStatus.CREDITED);
290
                        sio.setCreditTimestamp(LocalDateTime.now());
291
                        totalAmount += sio.getAmount();
292
                    }
293
                }
294
            }
295
            if (totalAmount > 0) {
296
                String description = "Investment margin paid for "
297
                        + FormattingUtils.formatYearMonth(startOfPreviousMonth.atStartOfDay());
298
                if (investmentMaintainedDays < 12) {
299
                    description += ", as maintained for " + investmentMaintainedDays + "(< 12) days";
300
                }
301
                walletService.addAmountToWallet(fofoId, referenceId, WalletReferenceType.INVESTMENT_PAYOUT, description,
302
                        totalAmount, lastOfPreviousMonth.atTime(LocalTime.MAX));
303
            }
304
            // Its ok to process Margins Pending for activation
305
            schemeService.processActivation();
306
            System.out.printf("%d\t%d\t%f%n", fofoId, investmentMaintainedDays, totalAmount);
307
        }
30651 amit.gupta 308
 
31352 amit.gupta 309
    }
22860 ashik.ali 310
 
31352 amit.gupta 311
    @RequestMapping(value = "/evaluateActualInvestmentPayout", method = RequestMethod.GET)
312
    public ResponseEntity<?> evaluateActualInvestmentPayout(HttpServletRequest request, Model model) throws Exception {
29608 amit.gupta 313
 
31352 amit.gupta 314
        List<List<?>> rows = new ArrayList<>();
315
        LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
316
        LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
317
        LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
318
        List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
319
                .selectAll(startOfPreviousMonth, lastOfPreviousMonth);
320
        Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
321
                .filter(x -> x.getShortPercentage() <= 10)
322
                .collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
323
        LOGGER.info("investmentMaintainedDaysMap {}", investmentMaintainedDaysMap);
324
        List<SchemeInOut> schemeInOuts = schemeInOutRepository.selectAllPending(SchemeType.INVESTMENT,
325
                startOfPreviousMonth.atStartOfDay(), firstDateOfCurrentMonth.atStartOfDay());
326
        Map<Integer, List<SchemeInOut>> inventoryItemIdSchemeMap = schemeInOuts.stream()
327
                .collect(Collectors.groupingBy(x -> x.getInventoryItemId()));
328
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectByIds(inventoryItemIdSchemeMap.keySet());
329
        Map<Integer, List<Integer>> retailerInventoryItemIdMap = inventoryItems.stream().collect(
330
                Collectors.groupingBy(x -> x.getFofoId(), Collectors.mapping(x -> x.getId(), Collectors.toList())));
331
        System.out.println("Fofo Id\tInvestment Maintained Days\tEligible payout");
332
        for (Map.Entry<Integer, List<Integer>> retailerEntry : retailerInventoryItemIdMap.entrySet()) {
333
            int fofoId = retailerEntry.getKey();
334
            List<SchemeInOut> schemeInouts = retailerEntry.getValue().stream().map(x -> inventoryItemIdSchemeMap.get(x))
335
                    .flatMap(List::stream).collect(Collectors.toList());
336
            double totalAmount = schemeInouts.stream().filter(x -> x.getRolledBackTimestamp() == null)
337
                    .collect(Collectors.summingDouble(x -> x.getAmount()));
338
            long investmentMaintainedDays = investmentMaintainedDaysMap.get(fofoId) == null ? 0
339
                    : investmentMaintainedDaysMap.get(fofoId);
340
            if (investmentMaintainedDays < 8) {
341
                totalAmount = 0;
342
            } else if (investmentMaintainedDays < 12) {
343
                totalAmount = totalAmount / 2;
344
            }
345
            System.out.printf("%d\t%d\t%f%n", fofoId, investmentMaintainedDays, totalAmount);
346
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
26588 tejbeer 347
 
31352 amit.gupta 348
            rows.add(Arrays.asList(fofoId, customRetailer.getBusinessName(), customRetailer.getCode(),
349
                    investmentMaintainedDays, totalAmount));
350
        }
29585 manish 351
 
31352 amit.gupta 352
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
353
                Arrays.asList("fofoId", "Name", "Code", "investmentMaintainedDays", "totalAmount"), rows);
26674 tejbeer 354
 
31352 amit.gupta 355
        final HttpHeaders headers = new HttpHeaders();
356
        headers.set("Content-Type", "text/csv");
357
        headers.set("Content-disposition", "inline; filename=investmentMaintainedDays.csv");
358
        headers.setContentLength(baos.toByteArray().length);
28795 tejbeer 359
 
31352 amit.gupta 360
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
361
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
28795 tejbeer 362
 
31352 amit.gupta 363
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
28795 tejbeer 364
 
31352 amit.gupta 365
    }
28795 tejbeer 366
 
31352 amit.gupta 367
    @RequestMapping(value = "/processInvestmentDryRun", method = RequestMethod.GET)
368
    public ResponseEntity<?> processInvestmentDryRun(HttpServletRequest request, Model model) throws Exception {
29707 tejbeer 369
 
31352 amit.gupta 370
        LocalDate firstDateOfCurrentMonth = LocalDateTime.now().withDayOfMonth(1).toLocalDate();
371
        LocalDate startOfPreviousMonth = firstDateOfCurrentMonth.minusMonths(1);
372
        LocalDate lastOfPreviousMonth = firstDateOfCurrentMonth.minusDays(1);
373
        List<List<?>> rows = new ArrayList<>();
29707 tejbeer 374
 
31352 amit.gupta 375
        Map<String, String> params = new HashMap<>();
29707 tejbeer 376
 
31352 amit.gupta 377
        params.put("MANUAL_datesBetween_FROMDATE", startOfPreviousMonth.toString());
378
        params.put("MANUAL_datesBetween_TODATE", lastOfPreviousMonth.toString());
29899 tejbeer 379
 
31352 amit.gupta 380
        params.put("type", "INVESTMENT");
30494 amit.gupta 381
 
31352 amit.gupta 382
        List<EvaluateSchemeInvestmentPayoutModel> evaluateSchemeInvestmentPayouts = reporticoService.getReports(
383
                EvaluateSchemeInvestmentPayoutModel.class, ReporticoProject.FOCO, "schemepayout.xml", params);
31147 tejbeer 384
 
31352 amit.gupta 385
        int referenceId = Integer.parseInt(FormattingUtils.getYearMonth(startOfPreviousMonth.atStartOfDay()));
386
        List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
387
                .selectAll(startOfPreviousMonth, lastOfPreviousMonth);
388
        Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
389
                .filter(x -> x.getShortPercentage() <= 10)
390
                .collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
29899 tejbeer 391
 
31352 amit.gupta 392
        for (EvaluateSchemeInvestmentPayoutModel esip : evaluateSchemeInvestmentPayouts) {
29608 amit.gupta 393
 
31352 amit.gupta 394
            long investmentMaintainedDays = investmentMaintainedDaysMap.get(esip.getFofoId()) == null ? 0
395
                    : investmentMaintainedDaysMap.get(esip.getFofoId());
29899 tejbeer 396
 
31352 amit.gupta 397
            esip.setInvestmentDays(investmentMaintainedDays);
29899 tejbeer 398
 
31383 amit.gupta 399
            float processAmount = esip.getPaidAmount();
31379 amit.gupta 400
            if (investmentMaintainedDays < 8) {
401
                processAmount = 0;
402
            } else if (investmentMaintainedDays < 12) {
403
                processAmount = processAmount / 2;
404
            }
29899 tejbeer 405
 
31352 amit.gupta 406
            esip.setProcessAmount(processAmount);
29899 tejbeer 407
 
31352 amit.gupta 408
            rows.add(Arrays.asList(esip.getCode(), esip.getStoreName(), esip.getFofoId(), esip.getItemId(),
409
                    esip.getBrand(), esip.getModelName(), esip.getModelNumber(), esip.getColor(), esip.getSchemeInDp(),
410
                    esip.getSchemeOutDp(), esip.getSchemeId(), esip.getName(), esip.getType(), esip.getPartnerType(),
411
                    esip.getAmountType(), esip.getAmount(), esip.getPurchaseInvoice(), esip.getSaleInovoice(),
412
                    esip.getPaidAmount(), esip.getCreateTimestamp(), esip.getRolledBackTimestamp(),
413
                    esip.getSerialNumber(), esip.getInRef(), esip.getOutRef(), esip.getBusinessDate(), esip.getStatus(),
414
                    esip.getDescription(), esip.getProcessAmount(), esip.getInvestmentDays()));
415
        }
29899 tejbeer 416
 
31352 amit.gupta 417
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
418
                .getCSVByteStream(Arrays.asList("Code", "Store Name", "Fofo Id", "Item Id", "Brand", "Model Name",
419
                        "Model Number", "Color", "Scheme In Dp", "Scheme Out Dp", "Scheme Id", "Name", "Type",
420
                        "Partner Type", "Amount Type", "Amount", "Purchase Invoice", "Sale Inovoice", "Paid Amount",
421
                        "Create Timestamp", "Rolled Back Timestamp", "Serial Number", "In Ref", "Out Ref",
422
                        "Business Date", "Status", "Description", "Process Amount", "Investment Days"), rows);
29899 tejbeer 423
 
31352 amit.gupta 424
        final HttpHeaders headers = new HttpHeaders();
425
        headers.set("Content-Type", "text/csv");
426
        headers.set("Content-disposition", "inline; filename=schemePayout.csv");
427
        headers.setContentLength(baos.toByteArray().length);
29899 tejbeer 428
 
31352 amit.gupta 429
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
430
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
23914 govind 431
 
31352 amit.gupta 432
        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
30494 amit.gupta 433
 
31352 amit.gupta 434
    }
30494 amit.gupta 435
 
31352 amit.gupta 436
    @RequestMapping(value = "/schemes/update", method = RequestMethod.POST)
437
    public String updateShcemes(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
438
            throws Exception {
439
        for (int schemeId : schemeItems.getSchemeIds()) {
440
            if (schemeRepository.selectById(schemeId) != null)
441
                for (int catalogId : schemeItems.getCatalogIds()) {
442
                    if (tagListingRepository.selectAllByCatalogIds(Arrays.asList(catalogId)).size() > 0) {
443
                        SchemeItem si = new SchemeItem();
444
                        si.setCatalogId(catalogId);
445
                        si.setSchemeId(schemeId);
446
                        si.setCreateTimestamp(LocalDateTime.now());
447
                        try {
448
                            schemeItemRepository.persist(si);
449
                        } catch (Exception e) {
450
                            LOGGER.info("Scheme aleady exist");
451
                        }
452
                        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
453
                    } else {
31520 amit.gupta 454
                        LOGGER.info("Invalid catalog Id - {}", catalogId);
31352 amit.gupta 455
                    }
456
                }
457
        }
458
        return "response";
459
    }
29608 amit.gupta 460
 
31352 amit.gupta 461
    @RequestMapping(value = "/addItemToScheme", method = RequestMethod.POST)
462
    public String updateScheme(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
463
            throws Exception {
464
        for (int schemeId : schemeItems.getSchemeIds()) {
465
            List<Integer> catalogIds = schemeItemRepository.selectCatalogIdsBySchemeId(schemeId);
466
            if (schemeRepository.selectById(schemeId) != null)
467
                for (int catalogId : schemeItems.getCatalogIds()) {
468
                    if (!(catalogIds.contains(catalogId))) {
469
                        SchemeItem si = new SchemeItem();
470
                        si.setCatalogId(catalogId);
471
                        si.setSchemeId(schemeId);
472
                        si.setCreateTimestamp(LocalDateTime.now());
473
                        try {
474
                            schemeItemRepository.persist(si);
475
                        } catch (Exception e) {
476
                            LOGGER.info("Scheme already exist");
477
                        }
478
                        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
479
                    } else {
480
                        throw new ProfitMandiBusinessException("Catalog exist for scheme",
481
                                "SchemeId= " + schemeId + ", CatalogId= " + catalogId, "Catalog exist for scheme");
482
                    }
483
                }
484
        }
485
        return "response";
486
    }
30768 amit.gupta 487
 
31352 amit.gupta 488
    @RequestMapping(value = "/createScheme", method = RequestMethod.GET)
489
    public String createScheme(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
490
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29608 amit.gupta 491
 
31352 amit.gupta 492
        LocalDate currentdate = LocalDate.now();
493
        Month month = currentdate.getMonth().minus(1);
494
        model.addAttribute("month", month);
29608 amit.gupta 495
 
31352 amit.gupta 496
        // Map<Integer, String> itemIdItemDescriptionMap =
497
        // inventoryService.getAllItemIdItemDescriptionMap();
498
        // model.addAttribute("itemIdItemDescriptionMap", itemIdItemDescriptionMap);
499
        // List<Category> categories = inventoryService.getAllCategories();
500
        List<Category> categories = categoryRepository.selectByIds(categoryIds);
501
        categories = categories.stream().sorted(Comparator.comparing(Category::getId)).collect(Collectors.toList());
502
        // Set<String> brands =
503
        // inventoryService.getAllTagListingBrands(ProfitMandiConstants.MOBILE_CATEGORY_ID);
504
        // brands.addAll(inventoryService.getAllTagListingBrands(14206));
29608 amit.gupta 505
 
31352 amit.gupta 506
        boolean fullAccesss = this.getAccess(loginDetails.getEmailId());
25256 amit.gupta 507
 
31352 amit.gupta 508
        List<Region> regionList = regionRepository.selectAll();
29608 amit.gupta 509
 
34317 amit.gupta 510
        List<SchemeType> schemeTypes = fullAccesss ? Arrays.stream(SchemeType.values()).collect(Collectors.toList()) : SchemeType.RESTRICTED_SCHEMES_TYPES;
511
        model.addAttribute("schemeTypes", schemeTypes);
31352 amit.gupta 512
        model.addAttribute("regionList", regionList);
29608 amit.gupta 513
 
31352 amit.gupta 514
        model.addAttribute("categories", categories);
515
        model.addAttribute("retailerTypes", PartnerType.values());
516
        return "create-scheme";
517
    }
29663 manish 518
 
31352 amit.gupta 519
    @RequestMapping(value = "/extendAllSchemes", method = RequestMethod.POST)
520
    public String extendAllScheme(HttpServletRequest request, @RequestBody LocalDateTime extendDatetime, Model model)
521
            throws Exception {
522
        List<Scheme> schemes = schemeRepository.selectActiveAll();
31387 amit.gupta 523
        //Filter scheme types ACTIVATION/SPECIAL SUPPORT/SELLOUT from extending
524
        schemes = schemes.stream().filter(x -> !EXCLUDE_EXTEND_SCHEMES.contains(x.getType())).collect(Collectors.toList());
31352 amit.gupta 525
        if (schemes.size() > 0) {
526
            for (Scheme scheme : schemes) {
527
                if (scheme.getExpireTimestamp() == null) {
528
                    scheme.setEndDateTime(extendDatetime);
529
                    schemeRepository.persist(scheme);
530
                }
531
            }
532
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
533
            return "response";
534
        }
535
        model.addAttribute("response1", mvcResponseSender.createResponseString(false));
536
        return "response";
537
    }
29608 amit.gupta 538
 
31352 amit.gupta 539
    @RequestMapping(value = "/getCatalogDescriptionByBrands", method = RequestMethod.GET)
540
    public String getTagListingItemsByBrand(HttpServletRequest request, @RequestParam int categoryId,
541
                                            @RequestParam List<String> brands, Model model) throws Exception {
542
        Map<Integer, String> catalogIdItemDescriptionMap = inventoryService.getModelDescriptionMap(categoryId, brands);
543
        model.addAttribute("catalogIdItemDescriptionMap", catalogIdItemDescriptionMap);
544
        // model.addAttribute("brands", inventoryService.getAllBrands());
29585 manish 545
 
31352 amit.gupta 546
        return "tag-listing-items-description";
547
    }
29663 manish 548
 
31352 amit.gupta 549
    @RequestMapping(value = "/createScheme", method = RequestMethod.POST)
550
    public String createScheme(HttpServletRequest request, @RequestBody CreateSchemeRequest createSchemeRequest,
551
                               Model model) throws ProfitMandiBusinessException {
552
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
553
        LOGGER.info("CreateSchemeRequest {}", createSchemeRequest);
554
        schemeService.saveScheme(loginDetails.getFofoId(), createSchemeRequest);
555
        return getDefaultSchemes(request, model);
556
    }
29663 manish 557
 
31352 amit.gupta 558
    private String getDefaultSchemes(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
559
        return getSchemes(request, 0, null, 30, 0, 0, PartnerType.ALL, "", model);
560
    }
29663 manish 561
 
31352 amit.gupta 562
    private List<Scheme> setSchemeAmountModel(List<Scheme> schemes) {
563
        for (Scheme scheme : schemes) {
564
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
565
                scheme.setAmountModel(scheme.getAmount() + "%");
566
            } else {
567
                scheme.setAmountModel(scheme.getAmount() + "");
568
            }
569
        }
570
        return schemes;
571
    }
29663 manish 572
 
31352 amit.gupta 573
    // Show 20 recents
29663 manish 574
 
31352 amit.gupta 575
    @RequestMapping(value = "/schemes/delete", method = RequestMethod.DELETE)
576
    public String deleteShcemes(HttpServletRequest request,
577
                                @RequestParam(name = "schemeId", required = false, defaultValue = "0") int schemeId,
578
                                @RequestParam(name = "catalogId", required = false, defaultValue = "0") int catalogId, Model model)
579
            throws Exception {
580
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
581
        if (schemeId > 0 && catalogId > 0) {
582
            schemeItemRepository.deleteByCatalogIdsAndSchemeIds(catalogId, schemeId);
29608 amit.gupta 583
 
31352 amit.gupta 584
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
29585 manish 585
 
31352 amit.gupta 586
            model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
29585 manish 587
 
31352 amit.gupta 588
        }
589
        return "response";
590
    }
29585 manish 591
 
31352 amit.gupta 592
    @RequestMapping(value = "/extendSchemeById", method = RequestMethod.POST)
593
    public String extendSchemeById(HttpServletRequest request,
29585 manish 594
 
31352 amit.gupta 595
                                   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
596
                                   @RequestBody LocalDateTime extendDatetime, Model model) throws Exception {
597
        Scheme scheme = schemeRepository.selectById(schemeId);
598
        if ((!(scheme.getActiveTimestamp() == null)) && scheme.getExpireTimestamp() == null) {
599
            scheme.setEndDateTime(extendDatetime);
600
            schemeRepository.persist(scheme);
601
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
602
            return "response";
603
        }
604
        model.addAttribute("response1", mvcResponseSender.createResponseString(false));
605
        return "response";
606
    }
29608 amit.gupta 607
 
31762 tejbeer 608
    @RequestMapping(value = "/getSchemesByImei", method = RequestMethod.GET)
33182 shampa 609
    public String getSchemesByImei(HttpServletRequest request,
35771 ranu 610
                                   @RequestParam(defaultValue = "") String searchImei,
611
                                   @RequestParam(defaultValue = "false") boolean modal, Model model) throws ProfitMandiBusinessException {
31762 tejbeer 612
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
613
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
614
 
615
            List<Scheme> schemes = null;
616
            List<SchemeInOut> schemeInOuts = null;
617
 
618
            InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumber(searchImei);
619
            int fofoId = inventoryItem.getFofoId();
33306 amit.gupta 620
           List<ItemPurchaseSummaryModel> itemPurchaseSummaryModels = inventoryItemRepository.selectPurchaseSummary(new ArrayList<>(Arrays.asList(inventoryItem.getId())));
31762 tejbeer 621
 
33182 shampa 622
            List<FofoOrder> fofoOrders=fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchImei ,null, null, 0, 0);
623
            LOGGER.info("fofoOrder {}", fofoOrders);
624
            List<FofoOrder> filterOrders = fofoOrders.stream().filter(x -> x.getCancelledTimestamp() == null).collect(Collectors.toList());
31762 tejbeer 625
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
626
            Item item = itemRepository.selectById(inventoryItem.getItemId());
627
            Map<Integer, Scheme> schemeMap = new HashMap<>();
628
            double netEarnings = 0;
629
            if (inventoryItem != null) {
630
                // Offer payout
631
                List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(fofoId, searchImei);
33030 amit.gupta 632
                Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream().map(x -> x.getOfferId())
33248 ranu 633
                        .distinct().map(offerId -> {
634
                            try {
635
                                return offerService.getOffer(fofoId, offerId.intValue());
636
                            } catch (ProfitMandiBusinessException e) {
637
                                throw new RuntimeException(e);
638
                            }
639
                        }).collect(Collectors.toMap(x -> x.getId(), x -> x));
31762 tejbeer 640
 
641
                schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
33182 shampa 642
                ActivatedImei activatedImei = activatedImeiRepository.selectBySerialNumber(searchImei);
31762 tejbeer 643
 
644
                if (!schemeInOuts.isEmpty()) {
645
                    netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED)).collect(Collectors.summingDouble(x -> x.getAmount()));
646
                    List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
647
 
648
                    schemes = schemeRepository.selectBySchemeIds(schemeIds);
649
                    for (Scheme scheme : schemes) {
650
                        if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
651
                            scheme.setAmountModel(scheme.getAmount() + "%");
652
                        } else {
653
                            scheme.setAmountModel(scheme.getAmount() + "");
654
                        }
655
                    }
656
 
657
                    schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
658
                }
33182 shampa 659
                List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByFofoIdImei(fofoId, searchImei);
31762 tejbeer 660
                if (priceDropImeis.size() > 0) {
661
 
662
                    for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
663
                        int priceDropId = priceDropIMEI.getPriceDropId();
664
                        PriceDrop pd = priceDropRepository.selectById(priceDropId);
665
                        priceDropIMEI.setPriceDrop(pd);
666
                    }
667
                    model.addAttribute("priceDropImeis", priceDropImeis);
668
                }
669
                netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
670
                model.addAttribute("offerPayouts", offerPayouts);
671
                model.addAttribute("offerRequestMap", offerRequestMap);
672
                model.addAttribute("inventoryItem", inventoryItem);
33306 amit.gupta 673
                model.addAttribute("itemPurchaseSummaryModels", itemPurchaseSummaryModels);
33182 shampa 674
                model.addAttribute("fofoOrders", filterOrders);
675
                model.addAttribute("activatedImei", activatedImei);
31762 tejbeer 676
 
33182 shampa 677
 
678
 
31762 tejbeer 679
            }
32331 amit.gupta 680
            LOGGER.info("Net Earnings {}", netEarnings);
31762 tejbeer 681
            model.addAttribute("netEarnings", netEarnings);
682
            model.addAttribute("fofoId", fofoId);
683
            model.addAttribute("schemeMap", schemeMap);
684
            model.addAttribute("item", item);
685
            model.addAttribute("schemeInOut", schemeInOuts);
686
            model.addAttribute("schemes", schemes);
687
            model.addAttribute("customRetailer", customRetailer);
33182 shampa 688
            model.addAttribute("searchImei", searchImei);
35775 ranu 689
            // Return IMEI results only when modal and searchImei provided
690
            if (modal) {
691
                return "scheme-imei-results-modal";
692
            }
31762 tejbeer 693
        }
35771 ranu 694
        if (modal) {
695
            return "scheme-imei-history-modal";
696
        }
31762 tejbeer 697
        return "scheme-imei-history";
698
    }
699
 
35775 ranu 700
    /**
701
     * New endpoint for modal IMEI-wise margin search
702
     * Returns shell when searchImei is empty, results when searchImei is provided
703
     */
704
    @RequestMapping(value = "/getImeiMarginModal", method = RequestMethod.GET)
705
    public String getImeiMarginModal(HttpServletRequest request,
706
                                     @RequestParam(defaultValue = "") String searchImei,
707
                                     @RequestParam(name = "fofoId") int fofoId,
708
                                     Model model) throws ProfitMandiBusinessException {
32232 amit.gupta 709
 
35775 ranu 710
        if (org.apache.commons.lang3.StringUtils.isEmpty(searchImei)) {
711
            // Return empty shell with search boxes
712
            return "scheme-imei-history-modal";
713
        }
714
 
715
        // Fetch IMEI margin data
716
        List<Scheme> schemes = null;
717
        List<SchemeInOut> schemeInOuts = null;
718
 
719
        InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumber(searchImei);
720
        if (inventoryItem == null) {
721
            model.addAttribute("searchImei", searchImei);
722
            return "scheme-imei-results-modal";
723
        }
724
 
725
        int itemFofoId = inventoryItem.getFofoId();
726
        List<ItemPurchaseSummaryModel> itemPurchaseSummaryModels = inventoryItemRepository.selectPurchaseSummary(new ArrayList<>(Arrays.asList(inventoryItem.getId())));
727
 
728
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(itemFofoId, searchImei, null, null, 0, 0);
729
        List<FofoOrder> filterOrders = fofoOrders.stream().filter(x -> x.getCancelledTimestamp() == null).collect(Collectors.toList());
730
        CustomRetailer customRetailer = retailerService.getFofoRetailer(itemFofoId);
731
        Item item = itemRepository.selectById(inventoryItem.getItemId());
732
        Map<Integer, Scheme> schemeMap = new HashMap<>();
733
        double netEarnings = 0;
734
 
735
        // Offer payout
736
        List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(itemFofoId, searchImei);
737
        Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream().map(x -> x.getOfferId())
738
                .distinct().map(offerId -> {
739
                    try {
740
                        return offerService.getOffer(itemFofoId, offerId.intValue());
741
                    } catch (ProfitMandiBusinessException e) {
742
                        throw new RuntimeException(e);
743
                    }
744
                }).collect(Collectors.toMap(x -> x.getId(), x -> x));
745
 
746
        schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
747
        ActivatedImei activatedImei = activatedImeiRepository.selectBySerialNumber(searchImei);
748
 
749
        if (!schemeInOuts.isEmpty()) {
750
            netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED)).collect(Collectors.summingDouble(x -> x.getAmount()));
751
            List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
752
 
753
            schemes = schemeRepository.selectBySchemeIds(schemeIds);
754
            for (Scheme scheme : schemes) {
755
                if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
756
                    scheme.setAmountModel(scheme.getAmount() + "%");
757
                } else {
758
                    scheme.setAmountModel(scheme.getAmount() + "");
759
                }
760
            }
761
            schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
762
        }
763
 
764
        List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByFofoIdImei(itemFofoId, searchImei);
765
        if (priceDropImeis.size() > 0) {
766
            for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
767
                int priceDropId = priceDropIMEI.getPriceDropId();
768
                PriceDrop pd = priceDropRepository.selectById(priceDropId);
769
                priceDropIMEI.setPriceDrop(pd);
770
            }
771
            model.addAttribute("priceDropImeis", priceDropImeis);
772
        }
773
 
774
        netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
775
        model.addAttribute("offerPayouts", offerPayouts);
776
        model.addAttribute("offerRequestMap", offerRequestMap);
777
        model.addAttribute("inventoryItem", inventoryItem);
778
        model.addAttribute("itemPurchaseSummaryModels", itemPurchaseSummaryModels);
779
        model.addAttribute("fofoOrders", filterOrders);
780
        model.addAttribute("activatedImei", activatedImei);
781
        model.addAttribute("netEarnings", netEarnings);
782
        model.addAttribute("fofoId", itemFofoId);
783
        model.addAttribute("schemeMap", schemeMap);
784
        model.addAttribute("item", item);
785
        model.addAttribute("schemeInOut", schemeInOuts);
786
        model.addAttribute("schemes", schemes);
787
        model.addAttribute("customRetailer", customRetailer);
788
        model.addAttribute("searchImei", searchImei);
789
 
790
        return "scheme-imei-results-modal";
791
    }
792
 
793
    /**
794
     * New endpoint for modal model-wise margin search
795
     * Accepts fofoId as parameter to work for both admin and partner views
796
     */
797
    @RequestMapping(value = "/getModelMarginModal", method = RequestMethod.GET)
798
    public String getModelMarginModal(HttpServletRequest request,
799
                                      @RequestParam(name = "searchModel") int searchModel,
800
                                      @RequestParam(name = "fofoId") int fofoId,
801
                                      @RequestParam(required = false) LocalDate date,
802
                                      Model model) throws ProfitMandiBusinessException {
803
        if (date == null) {
804
            date = LocalDate.now();
805
        } else if (date.isAfter(LocalDate.now())) {
806
            date = LocalDate.now();
807
        }
808
 
809
        Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
810
        TagListing tagListing = tagListingRepository.selectByItemId(item.getId());
811
        if (tagListing != null) {
812
            model.addAttribute("dp", tagListing.getSellingPrice());
813
            model.addAttribute("mop", tagListing.getMop());
814
        }
815
        model.addAttribute("modelName", item.getItemDescriptionNoColor());
816
        model.addAttribute("searchModel", searchModel);
817
        model.addAttribute("date", date);
818
 
819
        PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, Arrays.asList(searchModel), date);
820
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
821
        priceDropController.getPriceCircularView(priceCircularModel, model, fs.getCode());
822
 
823
        return "schemes-model-modal";
824
    }
825
 
826
 
32232 amit.gupta 827
    @Autowired
828
    PriceDropController priceDropController;
829
 
33182 shampa 830
    @Autowired
831
    ActivatedImeiRepository activatedImeiRepository;
832
 
31352 amit.gupta 833
    @RequestMapping(value = "/getSchemes", method = RequestMethod.GET)
834
    public String getSchemes(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset,
835
                             @RequestParam(required = false) LocalDate date,
836
                             @RequestParam(name = "limit", required = false, defaultValue = "30") int limit,
837
                             @RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel,
838
                             @RequestParam(name = "searchScheme", required = false, defaultValue = "0") int searchScheme,
839
                             @RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
840
                             @RequestParam(name = "searchImei", required = false, defaultValue = "") String searchImei, Model model)
841
            throws ProfitMandiBusinessException {
842
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
843
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
844
        if (date != null) {
845
            date = date.isAfter(LocalDate.now()) ? LocalDate.now() : date;
846
        } else if (!isAdmin) {
847
            date = LocalDate.now();
848
        }
29608 amit.gupta 849
 
31352 amit.gupta 850
        List<Scheme> schemes = null;
851
        List<SchemeInOut> schemeInOuts = null;
29608 amit.gupta 852
 
31352 amit.gupta 853
        boolean fullAccess = this.getAccess(loginDetails.getEmailId());
29608 amit.gupta 854
 
31352 amit.gupta 855
        model.addAttribute("fullAccess", fullAccess);
856
        model.addAttribute("searchImei", searchImei);
857
        model.addAttribute("isAdmin", isAdmin);
858
        model.addAttribute("searchModel", searchModel);
859
        model.addAttribute("searchScheme", searchScheme);
860
        model.addAttribute("partnerType", partnerType);
861
        model.addAttribute("date", date);
29608 amit.gupta 862
 
31352 amit.gupta 863
        final LocalDate date1 = date;
864
        if (searchScheme > 0) {
865
            schemes = Arrays.asList(schemeRepository.selectById(searchScheme));
866
            this.setSchemeAmountModel(schemes);
867
            if (schemes.size() > 0) {
868
                model.addAttribute("schemes", schemes);
869
                List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
870
                Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
871
                model.addAttribute("schemeRegionMap", schemeRegionMap);
872
                return "schemes";
873
            } else {
874
                throw new ProfitMandiBusinessException("SchemeId", searchScheme, "SchemeId Not Found");
875
            }
876
        } else if (searchModel > 0) {
877
            Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
878
            TagListing tagListing = tagListingRepository.selectByItemId(item.getId());
32331 amit.gupta 879
            LOGGER.info("tagListing {}", tagListing);
31352 amit.gupta 880
            if (tagListing != null) {
881
                model.addAttribute("dp", tagListing.getSellingPrice());
882
                model.addAttribute("mop", tagListing.getMop());
883
            }
884
            model.addAttribute("modelName", item.getItemDescriptionNoColor());
885
            if (isAdmin) {
886
                schemes = schemeService
887
                        .selectSchemeByPartnerType(partnerType, date, searchModel, isAdmin, offset, limit).stream()
888
                        .filter(x -> x.getId() != 411 && x.getId() != 612).collect(Collectors.toList());
889
                this.setSchemeAmountModel(schemes);
890
                model.addAttribute("schemes", schemes);
891
                List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
31482 amit.gupta 892
                Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(" ,"))));
31352 amit.gupta 893
                model.addAttribute("schemeRegionMap", schemeRegionMap);
894
                return "schemes";
895
            } else {
32331 amit.gupta 896
                PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(loginDetails.getFofoId(), Arrays.asList(searchModel), date);
32905 shampa 897
                FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
33030 amit.gupta 898
                priceDropController.getPriceCircularView(priceCircularModel, model, fs.getCode());
31352 amit.gupta 899
            }
29608 amit.gupta 900
 
31352 amit.gupta 901
        } else if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
29608 amit.gupta 902
 
31352 amit.gupta 903
            LOGGER.info("searchImei" + searchImei);
29608 amit.gupta 904
 
31352 amit.gupta 905
            InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
906
                    loginDetails.getFofoId());
907
            Item item = itemRepository.selectById(inventoryItem.getItemId());
908
            Map<Integer, Scheme> schemeMap = new HashMap<>();
909
            double netEarnings = 0;
910
            if (inventoryItem != null) {
32331 amit.gupta 911
                /*date = inventoryItem.getCreateTimestamp().toLocalDate();
912
                PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(loginDetails.getFofoId(), Arrays.asList(item.getCatalogItemId()), date);
913
                priceDropController.getPriceCircularView(priceCircularModel, model);*/
31352 amit.gupta 914
                // Offer payout
915
                List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(loginDetails.getFofoId(),
916
                        searchImei);
917
                Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream()
33248 ranu 918
                        .map(x -> {
919
                            try {
920
                                return offerService.getOffer(loginDetails.getFofoId(), (int) x.getOfferId());
921
                            } catch (ProfitMandiBusinessException e) {
922
                                throw new RuntimeException(e);
923
                            }
924
                        })
31352 amit.gupta 925
                        .collect(Collectors.toMap(x -> x.getId(), x -> x));
29608 amit.gupta 926
 
31352 amit.gupta 927
                schemeInOuts = schemeInOutRepository
928
                        .selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
25256 amit.gupta 929
 
31352 amit.gupta 930
                if (!schemeInOuts.isEmpty()) {
931
                    netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED))
932
                            .collect(Collectors.summingDouble(x -> x.getAmount()));
933
                    List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId())
934
                            .collect(Collectors.toList());
23914 govind 935
 
31352 amit.gupta 936
                    schemes = schemeRepository.selectBySchemeIds(schemeIds);
937
                    for (Scheme scheme : schemes) {
938
                        if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
939
                            scheme.setAmountModel(scheme.getAmount() + "%");
940
                        } else {
941
                            scheme.setAmountModel(scheme.getAmount() + "");
942
                        }
943
                    }
23914 govind 944
 
31352 amit.gupta 945
                    schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
946
                }
32331 amit.gupta 947
                netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
948
 
31352 amit.gupta 949
                List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
950
                        .selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
951
                if (priceDropImeis.size() > 0) {
23914 govind 952
 
31352 amit.gupta 953
                    for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
954
                        int priceDropId = priceDropIMEI.getPriceDropId();
955
                        PriceDrop pd = priceDropRepository.selectById(priceDropId);
956
                        priceDropIMEI.setPriceDrop(pd);
957
                    }
958
                    model.addAttribute("priceDropImeis", priceDropImeis);
959
                }
32331 amit.gupta 960
 
31352 amit.gupta 961
                model.addAttribute("offerPayouts", offerPayouts);
962
                model.addAttribute("offerRequestMap", offerRequestMap);
963
                model.addAttribute("inventoryItem", inventoryItem);
23914 govind 964
 
31352 amit.gupta 965
            }
32331 amit.gupta 966
            model.addAttribute("netEarnings", netEarnings);
31352 amit.gupta 967
            model.addAttribute("schemeMap", schemeMap);
968
            model.addAttribute("item", item);
969
            model.addAttribute("schemeInOut", schemeInOuts);
970
        }
31170 amit.gupta 971
 
31352 amit.gupta 972
        if (isAdmin) {
34369 amit.gupta 973
            schemes = schemeRepository.selectAll(0, 300);
31352 amit.gupta 974
            this.setSchemeAmountModel(schemes);
975
            List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
976
            Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
977
            model.addAttribute("schemes", schemes);
978
            model.addAttribute("schemeRegionMap", schemeRegionMap);
31170 amit.gupta 979
 
31352 amit.gupta 980
            return "schemes";
981
        } else {
982
            FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
983
            model.addAttribute("partnerCode", fs.getCode());
984
            model.addAttribute("fofoId", fs.getId());
985
            return "schemes-partner";
986
        }
23914 govind 987
 
31352 amit.gupta 988
    }
23786 amit.gupta 989
 
31352 amit.gupta 990
    private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing) {
31505 amit.gupta 991
        /*if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
31352 amit.gupta 992
                .filter(x -> x.getId() == fofoId).count() > 0) {
993
            schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
994
                    .collect(Collectors.toList());
31505 amit.gupta 995
        }*/
31352 amit.gupta 996
        float nlc = tagListing.getSellingPrice();
997
        for (Scheme scheme : schemes) {
998
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
999
                if (tagListing != null) {
1000
                    float amount = tagListing.getSellingPrice() * scheme.getAmount() / 100;
1001
                    scheme.setAmountModel(FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
1002
                    nlc -= amount;
1003
                } else {
1004
                    scheme.setAmountModel(scheme.getAmount() + "%");
1005
                }
1006
            } else {
1007
                scheme.setAmountModel(scheme.getAmount() + "");
1008
                nlc -= scheme.getAmount();
1009
            }
1010
        }
23819 govind 1011
 
31352 amit.gupta 1012
        return Math.round(nlc);
23914 govind 1013
 
31352 amit.gupta 1014
    }
29899 tejbeer 1015
 
31352 amit.gupta 1016
    @RequestMapping(value = "/getLastMonthCreditIncome", method = RequestMethod.GET)
1017
    public String getLastMonthCreditIncome(HttpServletRequest request, Model model) throws Exception {
30122 amit.gupta 1018
 
31352 amit.gupta 1019
        String status = "CREDITED";
1020
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23786 amit.gupta 1021
 
31352 amit.gupta 1022
        LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
1023
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
31170 amit.gupta 1024
 
31352 amit.gupta 1025
        YearMonth yearMonth = YearMonth.now();
1026
        LOGGER.info("yearMonth" + yearMonth);
31170 amit.gupta 1027
 
31352 amit.gupta 1028
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), yearMonth);
31170 amit.gupta 1029
 
31352 amit.gupta 1030
        LOGGER.info("partnerType" + partnerType);
31170 amit.gupta 1031
 
31352 amit.gupta 1032
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
31170 amit.gupta 1033
 
31352 amit.gupta 1034
        if (partnerType) {
1035
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1036
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), currentStartMonth,
1037
                            currentDate)
1038
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1039
        }
1040
        List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
1041
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
31170 amit.gupta 1042
 
31352 amit.gupta 1043
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1044
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
31170 amit.gupta 1045
 
31352 amit.gupta 1046
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1047
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), currentStartMonth, currentDate);
26802 tejbeer 1048
 
31352 amit.gupta 1049
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = schemeInOutRepository
1050
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate).stream()
1051
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
28796 tejbeer 1052
 
34409 amit.gupta 1053
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
31352 amit.gupta 1054
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
29608 amit.gupta 1055
 
31352 amit.gupta 1056
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
1057
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30274 amit.gupta 1058
 
31352 amit.gupta 1059
        lastMonthFrontEndIncomes.stream().forEach(x -> {
1060
            if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
1061
                x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
1062
                lastMonthSaleMarginMap.put(x.getBrand(), x);
1063
            } else {
1064
                lastMonthSaleMarginMap.put(x.getBrand(), x);
1065
            }
30274 amit.gupta 1066
 
31352 amit.gupta 1067
        });
1068
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1069
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
30274 amit.gupta 1070
 
31352 amit.gupta 1071
        Set<String> keySet = new HashSet<>();
1072
        keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
1073
        keySet.addAll(lastMonthSaleMarginMap.keySet());
1074
        keySet.addAll(lastMonthPendingIncomeMap.keySet());
28795 tejbeer 1075
 
31352 amit.gupta 1076
        lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
1077
            String brand = x.getKey();
1078
            float amount = x.getValue().getAmount();
1079
            if (!totalAmountMap.containsKey(brand)) {
1080
                totalAmountMap.put(brand, 0f);
1081
            }
1082
            totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
30253 amit.gupta 1083
 
31352 amit.gupta 1084
        });
30122 amit.gupta 1085
 
31352 amit.gupta 1086
        lastMonthPendingIncomeMap.entrySet().stream().forEach(x -> {
1087
            String brand = x.getKey();
1088
            float amount = x.getValue().getAmount();
1089
            if (!totalAmountMap.containsKey(brand)) {
1090
                totalAmountMap.put(brand, 0f);
1091
            }
1092
            totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
28795 tejbeer 1093
 
31352 amit.gupta 1094
        });
28795 tejbeer 1095
 
1096
 
31352 amit.gupta 1097
        Map<Integer, String> monthValueMap = new HashMap<>();
1098
        for (int i = 0; i <= 5; i++) {
1099
            LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1100
            monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
1101
        }
1102
        model.addAttribute("month", 0);
1103
        model.addAttribute("monthValueMap", monthValueMap);
1104
        model.addAttribute("keySet", keySet);
1105
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
28795 tejbeer 1106
 
31352 amit.gupta 1107
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1108
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1109
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1110
        model.addAttribute("status", status);
1111
        model.addAttribute("totalAmountMap", totalAmountMap);
28795 tejbeer 1112
 
31352 amit.gupta 1113
        return "last-month-credited-income";
1114
    }
30651 amit.gupta 1115
 
31352 amit.gupta 1116
    @RequestMapping(value = "/getLastMonthPendingIncome", method = RequestMethod.GET)
1117
    public String getLastMonthPendingIncome(HttpServletRequest request, Model model) throws Exception {
30651 amit.gupta 1118
 
31352 amit.gupta 1119
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
28795 tejbeer 1120
 
31352 amit.gupta 1121
        LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
1122
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
1123
        String status = "PENDING";
31170 amit.gupta 1124
 
31352 amit.gupta 1125
        LOGGER.info("currentStartMonth" + currentStartMonth);
1126
        LOGGER.info("currentDate" + currentDate);
28795 tejbeer 1127
 
31352 amit.gupta 1128
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1129
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
29899 tejbeer 1130
 
31352 amit.gupta 1131
        Map<String, LastMonthCreditedIncomeModel> lastMonthMarginMap = new HashMap<>();
23786 amit.gupta 1132
 
31352 amit.gupta 1133
        for (LastMonthCreditedIncomeModel lastMonthPendingIncomeModel : lastMonthPendingIncomeModels) {
28795 tejbeer 1134
 
31352 amit.gupta 1135
            lastMonthMarginMap.put(lastMonthPendingIncomeModel.getBrand(), lastMonthPendingIncomeModel);
1136
        }
1137
        LOGGER.info("lastMonthPendingIncomeModel" + lastMonthPendingIncomeModels);
1138
        LOGGER.info("lastMonthMarginMap" + lastMonthMarginMap);
1139
        model.addAttribute("lastMonthCreditedIncomeModels", lastMonthPendingIncomeModels);
1140
        model.addAttribute("lastMonthMarginMap", lastMonthMarginMap);
1141
        model.addAttribute("status", status);
28795 tejbeer 1142
 
31352 amit.gupta 1143
        return "last-month-credited-income";
1144
    }
28795 tejbeer 1145
 
31352 amit.gupta 1146
    @RequestMapping(value = "/getLastMonthImeiWiseIncome", method = RequestMethod.GET)
1147
    public String getLastMonthImeiWiseIncome(HttpServletRequest request,
1148
                                             @RequestParam(name = "catalogItemId", required = false, defaultValue = "") int catalogItemId,
1149
                                             @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
1150
            throws Exception {
30053 manish 1151
 
31352 amit.gupta 1152
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 1153
 
31352 amit.gupta 1154
        LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1155
        LocalDateTime lastMonthEnd = lastMonthStart.plusMonths(1);
30053 manish 1156
 
31352 amit.gupta 1157
        HashSet<String> allImeiSet = new LinkedHashSet<>();
30053 manish 1158
 
31352 amit.gupta 1159
        List<LastMonthFrontEndImeiModel> lmfi = schemeInOutRepository
1160
                .selectLastMonthFrontEndImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart, lastMonthEnd);
1161
        List<LastMonthImeiModel> lmpi = schemeInOutRepository.selectLastMonthPurchaseInImei(loginDetails.getFofoId(),
1162
                catalogItemId, lastMonthStart, lastMonthEnd);
1163
        List<LastMonthImeiModel> lmci = schemeInOutRepository.selectLastMonthCreditedImei(loginDetails.getFofoId(),
1164
                catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 1165
 
31352 amit.gupta 1166
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(YearMonth.of(lastMonthStart.getYear(),
1167
                lastMonthStart.getMonth()), loginDetails.getFofoId(), null, catalogItemId);
30053 manish 1168
 
31352 amit.gupta 1169
        LOGGER.info("lmci {}", lmci);
30053 manish 1170
 
31352 amit.gupta 1171
        Map<String, Double> lastmonthCategoryUpgradeMargin = schemeInOutRepository
1172
                .selectLastMonthCategoryUpgradeMarginByImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart,
1173
                        lastMonthEnd)
1174
                .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
30053 manish 1175
 
31352 amit.gupta 1176
        allImeiSet.addAll(lmpi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
1177
        allImeiSet.addAll(lmci.stream().map(x -> x.getImei()).collect(Collectors.toList()));
1178
        allImeiSet.addAll(lmfi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
1179
        allImeiSet.addAll(offerPayoutImeiIncomeModels.stream().map(x -> x.getImei()).collect(Collectors.toList()));
30053 manish 1180
 
31352 amit.gupta 1181
        List<String> allImeiList = new ArrayList<>(allImeiSet);
30053 manish 1182
 
31352 amit.gupta 1183
        LOGGER.info("allImeiList" + allImeiList);
1184
        LOGGER.info("lmcm" + lastmonthCategoryUpgradeMargin);
30253 amit.gupta 1185
 
31352 amit.gupta 1186
        List<LastMonthFrontEndImeiModel> lastMonthFrontEndImeis = schemeInOutRepository
1187
                .selectLastMonthFrontEndByImei(loginDetails.getFofoId(), allImeiList);
31379 amit.gupta 1188
        Map<String, LastMonthFrontEndImeiModel> soldMap = lastMonthFrontEndImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x));
30053 manish 1189
 
31379 amit.gupta 1190
 
31352 amit.gupta 1191
        List<LastMonthImeiModel> lastMonthPurchaseInImeis = schemeInOutRepository
1192
                .selectLastMonthPurchaseInByImei(loginDetails.getFofoId(), allImeiList);
30053 manish 1193
 
31352 amit.gupta 1194
        List<LastMonthImeiModel> lastMonthCreditedImeis = schemeInOutRepository
1195
                .selectLastMonthCreditedByImei(loginDetails.getFofoId(), allImeiList);
1196
        List<OfferPayoutImeiIncomeModel> allOfferPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByImei(allImeiList);
30053 manish 1197
 
31352 amit.gupta 1198
        //Map<String, OfferPayoutImeiIncomeModel> imeisOfferPayoutMap = allOfferPayoutImeiIncomeModels.stream().collect(Collectors.toMap(x->x.getImei(), x->x));
1199
        Map<String, Double> imeiWisePendingSaleAmount = lastMonthCreditedImeis.stream()
1200
                .filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).collect(Collectors
1201
                        .groupingBy(x -> x.getImei(), Collectors.summingDouble(x -> x.getPendingSaleAmount())));
30053 manish 1202
 
31352 amit.gupta 1203
        allOfferPayoutImeiIncomeModels.stream().forEach(x -> {
1204
            if (x.getSaleDate() != null) {
1205
                LastMonthImeiModel lastMonthImeiModel = new LastMonthImeiModel(x.getImei(), (float) x.getSalePayout(),
1206
                        0, "Addnl Margin", x.getSaleDate(), SchemePayoutStatus.CREDITED);
1207
                lastMonthCreditedImeis.add(lastMonthImeiModel);
1208
            }
1209
            if (x.getGrnDate() != null) {
1210
                LastMonthImeiModel lastMonthImeiModel = new LastMonthImeiModel(x.getImei(), (float) x.getPurchasePayout(),
1211
                        0, "Booster Payout", x.getGrnDate(), SchemePayoutStatus.CREDITED);
1212
                lastMonthPurchaseInImeis.add(lastMonthImeiModel);
1213
            }
1214
        });
30053 manish 1215
 
31352 amit.gupta 1216
        Map<String, Map<String, Double>> lastMonthPurchaseInMapPairMap = lastMonthPurchaseInImeis.stream()
1217
                .collect(Collectors.groupingBy(x -> x.getImei(),
1218
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
1219
        Map<String, LocalDate> imeiPurchaseDateMap = lastMonthPurchaseInImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x.getCreateTimeStamp().toLocalDate(), (x, y) -> x));
32236 amit.gupta 1220
        LOGGER.info("Last month front end imeis - {}", lastMonthFrontEndImeis);
32232 amit.gupta 1221
        Map<String, LocalDate> imeiSaleDateMap = lastMonthFrontEndImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x.getCreated()));
31352 amit.gupta 1222
        Map<String, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
1223
                .collect(Collectors.groupingBy(x -> x.getImei(),
1224
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
30053 manish 1225
 
31352 amit.gupta 1226
        // descriptionSet.add("")
30053 manish 1227
 
34409 amit.gupta 1228
        List<String> purchaseList = lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).distinct().collect(Collectors.toList());
1229
        List<String> saleList = lastMonthCreditedImeis.stream().map(x -> x.getDescription()).distinct().collect(Collectors.toList());
30253 amit.gupta 1230
 
31352 amit.gupta 1231
        Map<String, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
30053 manish 1232
 
31352 amit.gupta 1233
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
30235 tejbeer 1234
 
31352 amit.gupta 1235
            String imei = entry.getKey();
1236
            ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imei,
1237
                    imeiPurchaseDateMap.get(imei), null);
1238
            imeiWiseIncomeMapOfMap.put(imei, modelImeiMap);
1239
            double totalAmount = entry.getValue().entrySet().stream()
1240
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1241
            imeiWiseIncomeMapOfMap.get(imei).setTotalIncome(totalAmount);
1242
        }
31283 amit.gupta 1243
 
31352 amit.gupta 1244
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
1245
            Map<String, Double> descriptionAmountMap = entry.getValue();
1246
            if (!imeiWiseIncomeMapOfMap.containsKey(entry.getKey())) {
32232 amit.gupta 1247
                imeiWiseIncomeMapOfMap.put(entry.getKey(), new ImeiWiseIncomePairAndMapModel(entry.getKey(), null, null));
31352 amit.gupta 1248
            }
32232 amit.gupta 1249
            ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(entry.getKey());
1250
            ;
1251
            modelImeiMap.setSaleDate(imeiSaleDateMap.get(entry.getKey()));
30053 manish 1252
 
31352 amit.gupta 1253
            double totalAmount = descriptionAmountMap.entrySet().stream()
1254
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1255
            imeiWiseIncomeMapOfMap.get(entry.getKey())
1256
                    .setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(entry.getKey()).getTotalIncome());
1257
        }
30053 manish 1258
 
31352 amit.gupta 1259
        //Imeis for pending activation
1260
        lastMonthCreditedImeis.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).forEach(x -> {
1261
            if (!imeiWiseIncomeMapOfMap.containsKey(x.getImei())) {
32232 amit.gupta 1262
                imeiWiseIncomeMapOfMap.put(x.getImei(), new ImeiWiseIncomePairAndMapModel(x.getImei()));
31352 amit.gupta 1263
            }
1264
            ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1265
                    .get(x.getImei());
1266
            imeiWiseIncomePairAndMapModel.setSaleDate(x.getCreateTimeStamp().toLocalDate());
1267
            imeiWiseIncomePairAndMapModel.setTotalIncome(x.getPendingSaleAmount() + imeiWiseIncomePairAndMapModel.getTotalIncome());
1268
        });
30053 manish 1269
 
31379 amit.gupta 1270
        lastMonthFrontEndImeis.stream().forEach(lastMonthFrontEndImeiModel -> {
32232 amit.gupta 1271
            if (!imeiWiseIncomeMapOfMap.containsKey(lastMonthFrontEndImeiModel.getImei())) {
1272
                imeiWiseIncomeMapOfMap.put(lastMonthFrontEndImeiModel.getImei(), new ImeiWiseIncomePairAndMapModel(lastMonthFrontEndImeiModel.getImei()));
31379 amit.gupta 1273
            }
32232 amit.gupta 1274
            ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1275
                    .get(lastMonthFrontEndImeiModel.getImei());
1276
            lastMonthFrontEndImeiModel.setNlc(lastMonthFrontEndImeiModel.getDp()
1277
                    - (float) imeiWiseIncomeMapOfMap.get(lastMonthFrontEndImeiModel.getImei()).getTotalIncome());
1278
            lastMonthFrontEndImeiModel.setNetIncome(lastMonthFrontEndImeiModel.getSellingPrice() - lastMonthFrontEndImeiModel.getNlc());
1279
            imeiWiseIncomePairAndMapModel.setSaleDate(lastMonthFrontEndImeiModel.getCreated());
31379 amit.gupta 1280
        });
1281
 
31352 amit.gupta 1282
        model.addAttribute("imeiWisePendingSaleAmount", imeiWisePendingSaleAmount);
1283
        model.addAttribute("month", month);
1284
        model.addAttribute("purchaseList", purchaseList);
1285
        model.addAttribute("saleList", saleList);
1286
        model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1287
        model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1288
        model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1289
        model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
31379 amit.gupta 1290
        model.addAttribute("soldMap", soldMap);
31352 amit.gupta 1291
        model.addAttribute("allOfferPayoutImeiIncomeModels", allOfferPayoutImeiIncomeModels);
1292
        //model.addAttribute("iimeiSaleDateMap", imeiSaleDateMap);
1293
        //model.addAttribute("imeiPurchaseDateMap", imeiPurchaseDateMap);
30053 manish 1294
 
31352 amit.gupta 1295
        return "last-month-imei-wise-income";
1296
    }
30053 manish 1297
 
31352 amit.gupta 1298
    @RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1299
    public String getBrandWiseIncome(HttpServletRequest request,
1300
                                     @RequestParam(name = "brand", required = false, defaultValue = "") String brand,
32232 amit.gupta 1301
                                     @RequestParam(name = "month", required = false, defaultValue = "") int month,
1302
                                     Model model)
31352 amit.gupta 1303
            throws ProfitMandiBusinessException {
1304
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1305
        LOGGER.info("loginDetails {}", loginDetails);
1306
        LOGGER.info("brand" + brand);
1307
        LOGGER.info("month {}", month);
30053 manish 1308
 
31352 amit.gupta 1309
        LocalDateTime monthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1310
        LocalDateTime monthEnd = monthStart.plusMonths(1);
30053 manish 1311
 
31352 amit.gupta 1312
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1313
                YearMonth.of(monthStart.getYear(), monthStart.getMonth()), loginDetails.getFofoId(), brand, null);
32232 amit.gupta 1314
        LOGGER.info("offerPayoutImeiIncomeModels - {}", offerPayoutImeiIncomeModels);
1315
        Map<Integer, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().filter(x -> x.getPurchasePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getPurchasePayout())));
1316
        Map<Integer, Integer> additionalPurchaseQty = offerPayoutImeiIncomeModels.stream().filter(x -> x.getPurchasePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingInt(x -> 1)));
1317
        Map<Integer, Double> additionalSalePayoutMap = offerPayoutImeiIncomeModels.stream().filter(x -> x.getSalePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getSalePayout())));
1318
        Map<Integer, Integer> additionalSaleQty = offerPayoutImeiIncomeModels.stream().filter(x -> x.getSalePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingInt(x -> 1)));
30053 manish 1319
 
32232 amit.gupta 1320
        Set<Integer> allCatalogIds = offerPayoutImeiIncomeModels.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
31352 amit.gupta 1321
        boolean partnerTypeUpgraded = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(),
1322
                YearMonth.now());
30053 manish 1323
 
31352 amit.gupta 1324
        LOGGER.info("partnerType" + partnerTypeUpgraded);
30053 manish 1325
 
31352 amit.gupta 1326
        Map<String, Double> categoryUpgradeBrandModelMap = null;
1327
        if (partnerTypeUpgraded) {
1328
            categoryUpgradeBrandModelMap = schemeInOutRepository
1329
                    .selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, monthStart,
1330
                            monthEnd)
1331
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1332
        }
30053 manish 1333
 
31352 amit.gupta 1334
        List<LastMonthFrontEndBrandWiseIncome> modelWiseSalesMargins = schemeInOutRepository
1335
                .selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand, monthStart, monthEnd);
32232 amit.gupta 1336
        Map<Integer, LastMonthFrontEndBrandWiseIncome> modelWiseSalesMarginsMap = modelWiseSalesMargins.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1337
 
32232 amit.gupta 1338
 
31352 amit.gupta 1339
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMargins = schemeInOutRepository
1340
                .selectLastMonthBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1341
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMarginsMap = modelWiseSchemeOutMargins.stream()
1342
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1343
 
31352 amit.gupta 1344
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeInMargins = schemeInOutRepository
1345
                .selectLastMonthPurchaseBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1346
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeInMarginsMap = modelWiseSchemeInMargins.stream()
1347
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1348
 
32232 amit.gupta 1349
        allCatalogIds.addAll(modelWiseSalesMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
1350
        allCatalogIds.addAll(modelWiseSchemeInMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
1351
        allCatalogIds.addAll(modelWiseSchemeOutMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
30053 manish 1352
 
32232 amit.gupta 1353
        Map<Integer, String> modelNameMap = itemRepository.selectAllByCatalogIds(allCatalogIds).stream().collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x.getModel(), (u, v) -> u));
1354
        Map<Integer, Double> modelIncomeMap = new HashMap<>();
1355
        Map<Integer, Integer> modelPurchaseQtyMap = new HashMap<>();
1356
        Map<Integer, Integer> modelSaleQtyMap = new HashMap<>();
1357
        for (int catalogItemId : modelNameMap.keySet()) {
1358
            int saleQty = 0;
1359
            int purchaseQty = 0;
1360
            double income = 0;
30253 amit.gupta 1361
 
32232 amit.gupta 1362
            if (modelWiseSchemeInMarginsMap.containsKey(catalogItemId)) {
34813 aman 1363
                income += (modelWiseSchemeInMarginsMap.get(catalogItemId).getAmount()) + modelWiseSchemeInMarginsMap.get(catalogItemId).getPendingSaleAmount();
32232 amit.gupta 1364
                purchaseQty += modelWiseSchemeInMarginsMap.get(catalogItemId).getQty();
31352 amit.gupta 1365
            }
32232 amit.gupta 1366
            if (modelWiseSchemeOutMarginsMap.containsKey(catalogItemId)) {
1367
                income += modelWiseSchemeOutMarginsMap.get(catalogItemId).getAmount() + modelWiseSchemeOutMarginsMap.get(catalogItemId).getPendingSaleAmount();
31352 amit.gupta 1368
            }
32232 amit.gupta 1369
            if (additionalSalePayoutMap.containsKey(catalogItemId)) {
1370
                income += additionalSalePayoutMap.get(catalogItemId);
31352 amit.gupta 1371
            }
32232 amit.gupta 1372
            if (additionalPurchasePayout.containsKey(catalogItemId)) {
1373
                income += additionalPurchasePayout.get(catalogItemId);
1374
            }
1375
            if (modelWiseSalesMarginsMap.containsKey(catalogItemId)) {
1376
                income += modelWiseSalesMarginsMap.get(catalogItemId).getAmount();
1377
                saleQty = (int) modelWiseSalesMarginsMap.get(catalogItemId).getQty();
1378
            }
1379
            if (additionalPurchaseQty.containsKey(catalogItemId)) {
1380
                purchaseQty = Math.max(additionalPurchaseQty.get(catalogItemId), purchaseQty);
30253 amit.gupta 1381
 
31352 amit.gupta 1382
            }
32232 amit.gupta 1383
            modelIncomeMap.put(catalogItemId, income);
1384
            modelSaleQtyMap.put(catalogItemId, saleQty);
1385
            modelPurchaseQtyMap.put(catalogItemId, purchaseQty);
30253 amit.gupta 1386
 
32232 amit.gupta 1387
        }
30253 amit.gupta 1388
 
31352 amit.gupta 1389
        model.addAttribute("month", month);
32232 amit.gupta 1390
        model.addAttribute("modelWiseSalesMarginsMap", modelWiseSalesMarginsMap);
31352 amit.gupta 1391
        model.addAttribute("modelWiseSchemeOutMarginsMap", modelWiseSchemeOutMarginsMap);
1392
        model.addAttribute("modelWiseSchemeInMarginsMap", modelWiseSchemeInMarginsMap);
1393
        model.addAttribute("modelNameMap", modelNameMap);
32232 amit.gupta 1394
        model.addAttribute("modelPurchaseQtyMap", modelPurchaseQtyMap);
1395
        model.addAttribute("modelSaleQtyMap", modelSaleQtyMap);
1396
        model.addAttribute("modelIncomeMap", modelIncomeMap);
31352 amit.gupta 1397
        model.addAttribute("categoryUpgradeBrandModelMap", categoryUpgradeBrandModelMap);
1398
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
32232 amit.gupta 1399
        model.addAttribute("additionalSalePayoutMap", additionalSalePayoutMap);
30253 amit.gupta 1400
 
31352 amit.gupta 1401
        return "monthly-brand-wise-income";
30053 manish 1402
 
31352 amit.gupta 1403
    }
30053 manish 1404
 
31352 amit.gupta 1405
    @RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
34813 aman 1406
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @RequestParam(required = false) boolean partnerTask, @PathVariable int yearMonth, Model model)
31352 amit.gupta 1407
            throws ProfitMandiBusinessException {
1408
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30253 amit.gupta 1409
 
31352 amit.gupta 1410
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1411
        LocalDateTime lastMonthEnd = startOfMonth.plusMonths(1);
30253 amit.gupta 1412
 
31352 amit.gupta 1413
        YearMonth monthYear = YearMonth.now();
30053 manish 1414
 
31352 amit.gupta 1415
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
30053 manish 1416
 
31352 amit.gupta 1417
        LOGGER.info("partnerType" + partnerType);
30053 manish 1418
 
31352 amit.gupta 1419
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
30053 manish 1420
 
31352 amit.gupta 1421
        if (partnerType) {
1422
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1423
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), startOfMonth,
1424
                            lastMonthEnd)
1425
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1426
        }
30053 manish 1427
 
31352 amit.gupta 1428
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1429
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30053 manish 1430
 
31352 amit.gupta 1431
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1432
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1433
 
31352 amit.gupta 1434
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1435
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
32232 amit.gupta 1436
        Map<String, LastMonthCreditedIncomeModel> lastMonthFrontEndIncomeMap = lastMonthFrontEndIncomes.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30235 tejbeer 1437
 
31352 amit.gupta 1438
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1439
                YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()), loginDetails.getFofoId(), null, null);
30235 tejbeer 1440
 
31352 amit.gupta 1441
        Map<String, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getPurchasePayout)));
1442
        Map<String, Double> additionSalePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getSalePayout)));
30235 tejbeer 1443
 
1444
 
31352 amit.gupta 1445
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
1446
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1447
 
34409 amit.gupta 1448
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = schemeInOutRepository
1449
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd).stream()
31352 amit.gupta 1450
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1451
 
1452
 
31352 amit.gupta 1453
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = lastMonthPendingIncomeModels.stream()
1454
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1455
 
31352 amit.gupta 1456
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1457
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1458
        Set<String> brandSet = new HashSet<>();
1459
        brandSet.addAll(lastMonthPurchaseInMarginMap.keySet());
1460
        brandSet.addAll(lastMonthSaleMarginMap.keySet());
1461
        brandSet.addAll(lastMonthPendingIncomeMap.keySet());
1462
        brandSet.addAll(additionalPurchasePayout.keySet());
1463
        brandSet.addAll(additionSalePayout.keySet());
33313 amit.gupta 1464
        brandSet.addAll(lastMonthFrontEndIncomeMap.keySet());
31352 amit.gupta 1465
        brandSet.stream().forEach(brand -> {
1466
            totalAmountMap.put(brand,
1467
                    (lastMonthSaleMarginMap.get(brand) == null ? 0 : lastMonthSaleMarginMap.get(brand).getAmount()) +
1468
                            (lastMonthPurchaseInMarginMap.get(brand) == null ? 0 : lastMonthPurchaseInMarginMap.get(brand).getAmount()) +
1469
                            (lastMonthPendingIncomeMap.get(brand) == null ? 0 : lastMonthPendingIncomeMap.get(brand).getAmount()) +
1470
                            (additionalPurchasePayout.get(brand) == null ? 0 : additionalPurchasePayout.get(brand).longValue()) +
32232 amit.gupta 1471
                            (additionSalePayout.get(brand) == null ? 0 : additionSalePayout.get(brand).longValue()) +
1472
                            (lastMonthFrontEndIncomeMap.get(brand) == null ? 0 : lastMonthFrontEndIncomeMap.get(brand).getAmount())
31352 amit.gupta 1473
            );
1474
        });
30053 manish 1475
 
31352 amit.gupta 1476
        Map<Integer, String> monthValueMap = new HashMap<>();
1477
        for (int i = 0; i <= 5; i++) {
1478
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1479
            monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
1480
        }
1481
        model.addAttribute("monthValueMap", monthValueMap);
30053 manish 1482
 
32232 amit.gupta 1483
        model.addAttribute("brandSet", brandSet);
31352 amit.gupta 1484
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1485
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1486
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
1487
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
1488
        model.addAttribute("additionalSalePayoutMap", additionSalePayout);
32232 amit.gupta 1489
        model.addAttribute("lastMonthFrontEndIncomeMap", lastMonthFrontEndIncomeMap);
30053 manish 1490
 
31352 amit.gupta 1491
        model.addAttribute("totalAmountMap", totalAmountMap);
1492
        model.addAttribute("month", yearMonth);
1493
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1494
        LOGGER.info("totalAmountMap {}", totalAmountMap);
1495
        LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
30253 amit.gupta 1496
 
34813 aman 1497
        if (partnerTask) {
1498
            return "monthly-credited-income";
1499
        } else return "last-month-credited-income";
31352 amit.gupta 1500
    }
30253 amit.gupta 1501
 
31352 amit.gupta 1502
    @RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
1503
    public String downloadPage(HttpServletRequest request, Model model) {
1504
        return "schemes-download";
1505
    }
30253 amit.gupta 1506
 
31352 amit.gupta 1507
    @RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
1508
    public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
1509
                                                                  @RequestParam LocalDateTime startDateTime, @RequestParam LocalDateTime endDateTime)
1510
            throws ProfitMandiBusinessException {
30253 amit.gupta 1511
 
31352 amit.gupta 1512
        List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
31334 amit.gupta 1513
 
31352 amit.gupta 1514
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1515
        ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
30253 amit.gupta 1516
 
31352 amit.gupta 1517
        final HttpHeaders headers = new HttpHeaders();
1518
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
1519
        headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
1520
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1521
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1522
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1523
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1524
    }
30053 manish 1525
 
31352 amit.gupta 1526
    @RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
1527
    public String getSchemeById(HttpServletRequest request,
1528
                                @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
1529
            throws ProfitMandiBusinessException {
1530
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 1531
 
31352 amit.gupta 1532
        boolean fullAccess = this.getAccess(loginDetails.getEmailId());
1533
        Scheme scheme = schemeService.getSchemeById(schemeId);
1534
        model.addAttribute("fullAccess", fullAccess);
1535
        model.addAttribute("scheme", scheme);
1536
        model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
1537
        return "scheme-details";
1538
    }
30053 manish 1539
 
31352 amit.gupta 1540
    @RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
1541
    public String activeSchemeById(@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1542
                                   @RequestParam(name = "offset", defaultValue = "0") int offset,
1543
                                   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1544
            throws ProfitMandiBusinessException {
1545
        schemeService.activeSchemeById(schemeId);
1546
        List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
1547
        for (Scheme scheme : schemes) {
1548
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1549
                scheme.setAmountModel(scheme.getAmount() + "%");
1550
            } else {
1551
                scheme.setAmountModel(scheme.getAmount() + "");
1552
            }
1553
        }
1554
        return "schemes";
1555
    }
30053 manish 1556
 
34568 vikas.jang 1557
    @RequestMapping(value = "/activeSchemeByIds", method = RequestMethod.PUT)
34575 vikas.jang 1558
    public String activeSchemeByIds(@RequestParam(name = ProfitMandiConstants.SCHEME_ID) String schemeIds, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) throws Exception {
34568 vikas.jang 1559
        List<Integer> ids = Arrays.stream(schemeIds.split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(Integer::parseInt).collect(Collectors.toList());
1560
        List<Scheme> schemes = schemeRepository.selectBySchemeIds(ids);
1561
        schemeService.activeSchemeByIds(schemes);
34575 vikas.jang 1562
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1563
        return "response";
34568 vikas.jang 1564
    }
1565
 
35252 aman 1566
    @RequestMapping(value = "/expireSchemeByIds", method = RequestMethod.PUT)
1567
    public String expireSchemeByIds(@RequestParam(name = ProfitMandiConstants.SCHEME_ID) String schemeIds, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, Model model) throws Exception {
1568
        List<Integer> ids = Arrays.stream(schemeIds.split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(Integer::parseInt).collect(Collectors.toList());
1569
        List<Scheme> schemes = schemeRepository.selectBySchemeIds(ids);
1570
        schemeService.expireSchemeByIds(schemes);
1571
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1572
        return "response";
1573
    }
1574
 
31352 amit.gupta 1575
    @RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
1576
    public String expireSchemeById(HttpServletRequest request,
1577
                                   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1578
                                   @RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp, Model model)
1579
            throws ProfitMandiBusinessException {
1580
        schemeService.expireSchemeById(schemeId, expiryTimestamp);
1581
        return getDefaultSchemes(request, model);
1582
    }
30053 manish 1583
 
31352 amit.gupta 1584
    @RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
1585
    public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
1586
                                            @RequestParam(name = "offset", defaultValue = "0") int offset,
1587
                                            @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1588
            throws ProfitMandiBusinessException {
1589
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1590
        return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1591
    }
30053 manish 1592
 
31352 amit.gupta 1593
    @RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1594
    public String getCustomerOffer(HttpServletRequest request,
33795 ranu 1595
                                   @RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel, @RequestParam(name = "startDate", required = false) LocalDateTime startDate, @RequestParam(name = "endDate", required = false) LocalDateTime endDate, Model model)
31352 amit.gupta 1596
            throws ProfitMandiBusinessException {
1597
        List<CustomerOffer> customerOffers = null;
1598
        if (searchModel > 0) {
30053 manish 1599
 
31352 amit.gupta 1600
            Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
1601
            customerOffers = customerOfferRepository.selectActiveOfferByModel(searchModel, LocalDate.now());
1602
            model.addAttribute("modelName", item.getItemDescriptionNoColor());
33795 ranu 1603
        } else if (startDate != null && endDate != null) {
1604
            customerOffers = customerOfferRepository.selectOffersByDates(startDate, endDate);
31352 amit.gupta 1605
        } else {
33795 ranu 1606
            if (startDate == null) {
1607
                startDate = LocalDateTime.now().minusMonths(1);  // One month ago from today
1608
            }
1609
            if (endDate == null) {
1610
                endDate = LocalDateTime.now();  // Current date and time
1611
            }
1612
            customerOffers = customerOfferRepository.selectOffersByDates(startDate, endDate);
31352 amit.gupta 1613
        }
30053 manish 1614
 
31352 amit.gupta 1615
        LOGGER.info("customerOffers" + customerOffers);
30053 manish 1616
 
31352 amit.gupta 1617
        for (CustomerOffer customerOffer : customerOffers) {
30053 manish 1618
 
31352 amit.gupta 1619
            LOGGER.info("ss" + searchModel);
30053 manish 1620
 
31352 amit.gupta 1621
            if (!StringUtils.isEmpty(customerOffer.getPartnerCriteria())) {
33030 amit.gupta 1622
                String partnerCriteria = offerService.getPartnerCriteriaString(gson.fromJson(customerOffer.getPartnerCriteria(), PartnerCriteria.class));
31352 amit.gupta 1623
                customerOffer.setPartnerCriteriaString(partnerCriteria);
1624
            }
30053 manish 1625
 
31352 amit.gupta 1626
        }
30053 manish 1627
 
31352 amit.gupta 1628
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1629
                .collect(Collectors.toList());
31281 amit.gupta 1630
 
31352 amit.gupta 1631
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30053 manish 1632
 
31352 amit.gupta 1633
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1634
                .filter(x -> x != null).collect(Collectors.toList()).stream()
1635
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30053 manish 1636
 
31352 amit.gupta 1637
        model.addAttribute("customRetailersMap", customRetailersMap);
1638
        model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
1639
        model.addAttribute("searchModel", searchModel);
30053 manish 1640
 
31352 amit.gupta 1641
        model.addAttribute("customerOffers", customerOffers);
1642
        return "customer-offer";
30053 manish 1643
 
31352 amit.gupta 1644
    }
30053 manish 1645
 
31352 amit.gupta 1646
    @RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1647
    public String createCustomerOffer(HttpServletRequest request, @RequestBody CustomerOfferModel customerOfferModel,
1648
                                      Model model) throws Exception {
30053 manish 1649
 
31352 amit.gupta 1650
        CustomerOffer co = new CustomerOffer();
1651
        co.setOfferName(customerOfferModel.getOfferName());
1652
        co.setStartDate(customerOfferModel.getStartDate());
1653
        co.setEndDate(customerOfferModel.getEndDate());
1654
        co.setPartnerCriteria(gson.toJson(customerOfferModel.getPartnerCriteria()));
1655
        co.setCreatedTimestamp(LocalDateTime.now());
1656
        co.setUpdatedTimestamp(LocalDateTime.now());
1657
        customerOfferRepository.persist(co);
31281 amit.gupta 1658
 
31352 amit.gupta 1659
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31281 amit.gupta 1660
 
31352 amit.gupta 1661
        return "response";
30053 manish 1662
 
31352 amit.gupta 1663
    }
30053 manish 1664
 
31352 amit.gupta 1665
    @RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1666
    public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1667
        List<List<?>> rows = new ArrayList<>();
30053 manish 1668
 
31352 amit.gupta 1669
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("id",
33795 ranu 1670
                        "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date (dd-mm-yyyy)", "End Date (dd-mm-yyyy)", "Offer Type"),
31352 amit.gupta 1671
                rows);
30053 manish 1672
 
31352 amit.gupta 1673
        final HttpHeaders headers = new HttpHeaders();
1674
        headers.set("Content-Type", "text/csv");
1675
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1676
        headers.setContentLength(baos.toByteArray().length);
30053 manish 1677
 
31352 amit.gupta 1678
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1679
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1680
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
30053 manish 1681
 
31352 amit.gupta 1682
    }
30053 manish 1683
 
31352 amit.gupta 1684
    @RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1685
    public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
1686
                                          HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
23786 amit.gupta 1687
 
31352 amit.gupta 1688
        List<CSVRecord> records = FileUtil.readFile(file);
1689
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
23914 govind 1690
 
31352 amit.gupta 1691
        CustomerOffer customerOffer = customerOfferRepository.selectById(offerId);
1692
        List<Integer> catalogIds = new ArrayList<>();
1693
        for (CSVRecord record : records) {
23786 amit.gupta 1694
 
31352 amit.gupta 1695
            CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
23786 amit.gupta 1696
 
31352 amit.gupta 1697
            if (coi == null) {
1698
                coi = new CustomerOfferItem();
1699
                coi.setCatalogId(Integer.parseInt(record.get(1)));
1700
                coi.setSchemePayout(Integer.parseInt(record.get(2)));
1701
                coi.setDealerPayout(Integer.parseInt(record.get(3)));
33795 ranu 1702
                coi.setOfferType(OfferType.valueOf(record.get(6)));
31352 amit.gupta 1703
                coi.setCustomerOfferId(offerId);
34516 ranu 1704
                coi.setAdditionalInfo(String.valueOf(record.get(7)));
31352 amit.gupta 1705
                coi.setCreatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1706
 
31352 amit.gupta 1707
                customerOfferItemRepository.persist(coi);
29899 tejbeer 1708
 
31352 amit.gupta 1709
            }
1710
            coi.setSchemePayout(Integer.parseInt(record.get(2)));
1711
            coi.setDealerPayout(Integer.parseInt(record.get(3)));
33795 ranu 1712
            coi.setOfferType(OfferType.valueOf(record.get(6)));
34516 ranu 1713
            coi.setAdditionalInfo(String.valueOf(record.get(7)));
31352 amit.gupta 1714
            coi.setCustomerOfferId(offerId);
1715
            coi.setUpdatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1716
 
31352 amit.gupta 1717
            LOGGER.info(record.get(4));
23786 amit.gupta 1718
 
31352 amit.gupta 1719
            LocalDate startDate = LocalDate.parse(record.get(4), formatter);
1720
            LocalDate endDate = LocalDate.parse(record.get(5), formatter);
23786 amit.gupta 1721
 
31352 amit.gupta 1722
            if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1723
                    || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1724
                    && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1725
                    || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1726
                coi.setStartDate(startDate);
26802 tejbeer 1727
 
31352 amit.gupta 1728
            } else {
29707 tejbeer 1729
 
31352 amit.gupta 1730
                catalogIds.add(coi.getCatalogId());
1731
            }
29707 tejbeer 1732
 
31352 amit.gupta 1733
            if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1734
                    || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1735
                    && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1736
                    || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1737
 
31352 amit.gupta 1738
                coi.setEndDate(endDate);
31147 tejbeer 1739
 
31352 amit.gupta 1740
            } else {
1741
                catalogIds.add(coi.getCatalogId());
1742
            }
31147 tejbeer 1743
 
31352 amit.gupta 1744
        }
31147 tejbeer 1745
 
31352 amit.gupta 1746
        if (!catalogIds.isEmpty()) {
1747
            throw new ProfitMandiBusinessException("Please set accurate start and end date", catalogIds,
1748
                    "Please set accurate start and end date");
1749
        }
1750
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1751
 
31352 amit.gupta 1752
        return "response";
31147 tejbeer 1753
 
31352 amit.gupta 1754
    }
31147 tejbeer 1755
 
34788 ranu 1756
 
1757
    @RequestMapping(value = "/CheckIfExistCustomerOfferItem", method = RequestMethod.POST)
1758
    public String CheckIfExistCustomerOfferItem(HttpServletRequest request,
1759
                                                @RequestBody CustomerOfferItemModel customerOfferItemModel, Model model) throws Throwable {
1760
 
1761
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItemModel.getOfferId());
1762
 
1763
        if (!(customerOffer.getEndDate().toLocalDate().equals(LocalDate.now()))
1764
                && customerOffer.getEndDate().isBefore(LocalDateTime.now())) {
1765
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(), "Offer is Expired");
1766
 
1767
        }
1768
 
1769
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
1770
                .selectByOfferAndCatalogId(customerOfferItemModel.getOfferId(), customerOfferItemModel.getCatalogId());
1771
        boolean response = true;
1772
        if (!customerOfferItems.isEmpty()) {
1773
            for (CustomerOfferItem coi : customerOfferItems) {
1774
                if (!(coi.getEndDate().equals(LocalDate.now())) && coi.getEndDate().isAfter(LocalDate.now())) {
1775
                    response = false;
1776
 
1777
                }
1778
            }
1779
        }
1780
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
1781
        return "response";
1782
 
1783
    }
1784
 
31352 amit.gupta 1785
    @RequestMapping(value = "/addCustomerOfferItem", method = RequestMethod.POST)
1786
    public String addCustomerOfferItem(HttpServletRequest request,
1787
                                       @RequestBody CustomerOfferItemModel customerOfferItemModel, Model model) throws Throwable {
31147 tejbeer 1788
 
31352 amit.gupta 1789
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItemModel.getOfferId());
31147 tejbeer 1790
 
31352 amit.gupta 1791
        if (!(customerOffer.getEndDate().toLocalDate().equals(LocalDate.now()))
1792
                && customerOffer.getEndDate().isBefore(LocalDateTime.now())) {
1793
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(), "Offer is Expired");
29707 tejbeer 1794
 
31352 amit.gupta 1795
        }
29707 tejbeer 1796
 
34788 ranu 1797
       /* List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
31352 amit.gupta 1798
                .selectByOfferAndCatalogId(customerOfferItemModel.getOfferId(), customerOfferItemModel.getCatalogId());
29707 tejbeer 1799
 
31352 amit.gupta 1800
        if (!customerOfferItems.isEmpty()) {
29707 tejbeer 1801
 
31352 amit.gupta 1802
            for (CustomerOfferItem coi : customerOfferItems) {
1803
                if (!(coi.getEndDate().equals(LocalDate.now())) && coi.getEndDate().isAfter(LocalDate.now())) {
1804
                    throw new ProfitMandiBusinessException("Catalog Id", coi.getCatalogId(), "Item is already exist.");
1805
                }
1806
            }
29707 tejbeer 1807
 
34788 ranu 1808
        }*/
29707 tejbeer 1809
 
31352 amit.gupta 1810
        LocalDate startDate = customerOfferItemModel.getStartDate().toLocalDate();
1811
        LocalDate endDate = customerOfferItemModel.getEndDate().toLocalDate();
1812
        CustomerOfferItem coi = new CustomerOfferItem();
1813
        coi.setCatalogId(customerOfferItemModel.getCatalogId());
1814
        coi.setSchemePayout(customerOfferItemModel.getSchemePayout());
34516 ranu 1815
        coi.setAdditionalInfo(customerOfferItemModel.getAdditionalInfo());
31352 amit.gupta 1816
        coi.setDealerPayout(customerOfferItemModel.getDealerPayout());
33795 ranu 1817
        coi.setOfferType(customerOfferItemModel.getOfferType());
31352 amit.gupta 1818
        coi.setCustomerOfferId(customerOfferItemModel.getOfferId());
1819
        coi.setUpdatedTimestamp(LocalDateTime.now());
1820
        coi.setCreatedTimestamp(LocalDateTime.now());
29707 tejbeer 1821
 
31352 amit.gupta 1822
        if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1823
                || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1824
                && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1825
                || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 1826
 
31352 amit.gupta 1827
            coi.setStartDate(startDate);
29707 tejbeer 1828
 
31352 amit.gupta 1829
        } else {
29707 tejbeer 1830
 
31352 amit.gupta 1831
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1832
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1833
                            + customerOffer.getEndDate());
29707 tejbeer 1834
 
31352 amit.gupta 1835
        }
29707 tejbeer 1836
 
31352 amit.gupta 1837
        if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1838
                || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1839
                && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1840
                || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 1841
 
31352 amit.gupta 1842
            coi.setEndDate(endDate);
29707 tejbeer 1843
 
31352 amit.gupta 1844
        } else {
1845
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1846
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1847
                            + customerOffer.getEndDate());
1848
        }
31147 tejbeer 1849
 
31352 amit.gupta 1850
        customerOfferItemRepository.persist(coi);
31147 tejbeer 1851
 
31352 amit.gupta 1852
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1853
 
31352 amit.gupta 1854
        return "response";
29707 tejbeer 1855
 
31352 amit.gupta 1856
    }
31147 tejbeer 1857
 
31352 amit.gupta 1858
    @RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1859
    public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
31147 tejbeer 1860
 
31352 amit.gupta 1861
        List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1862
        List<List<?>> rows = new ArrayList<>();
1863
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
31147 tejbeer 1864
 
31352 amit.gupta 1865
        for (CustomerOfferItem coi : cois) {
1866
            rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout(),
34516 ranu 1867
                    coi.getStartDate().format(formatter), coi.getEndDate().format(formatter), coi.getOfferType(), coi.getAdditionalInfo()));
31147 tejbeer 1868
 
31352 amit.gupta 1869
        }
31147 tejbeer 1870
 
31352 amit.gupta 1871
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
34516 ranu 1872
                Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date", "End Date", "Offer Type", "Additional Info"), rows);
29707 tejbeer 1873
 
31352 amit.gupta 1874
        final HttpHeaders headers = new HttpHeaders();
1875
        headers.set("Content-Type", "text/csv");
1876
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1877
        headers.setContentLength(baos.toByteArray().length);
31147 tejbeer 1878
 
31352 amit.gupta 1879
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1880
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1881
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
31147 tejbeer 1882
 
31352 amit.gupta 1883
    }
31147 tejbeer 1884
 
31352 amit.gupta 1885
    @RequestMapping(value = "/getCustomerOfferItem", method = RequestMethod.GET)
1886
    public String getCustomerOfferItem(HttpServletRequest request, @RequestParam int offerId, Model model)
1887
            throws Exception {
29707 tejbeer 1888
 
31352 amit.gupta 1889
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository.selectByOfferId(offerId);
1890
        List<Integer> catalogIds = customerOfferItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
29707 tejbeer 1891
 
31352 amit.gupta 1892
        Map<Integer, List<Item>> catalogItemMap = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds))
1893
                .stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
29707 tejbeer 1894
 
33795 ranu 1895
        List<OfferType> offerTypes = Arrays.asList(OfferType.values());
1896
 
31352 amit.gupta 1897
        model.addAttribute("catalogItemMap", catalogItemMap);
29707 tejbeer 1898
 
31352 amit.gupta 1899
        model.addAttribute("offerId", offerId);
31147 tejbeer 1900
 
31352 amit.gupta 1901
        model.addAttribute("customerOfferItems", customerOfferItems);
33795 ranu 1902
 
1903
        model.addAttribute("offerTypes", offerTypes);
1904
 
31352 amit.gupta 1905
        return "customer-offer-item";
31147 tejbeer 1906
 
31352 amit.gupta 1907
    }
31147 tejbeer 1908
 
31352 amit.gupta 1909
    @RequestMapping(value = "/expiredCustomerOfferItem", method = RequestMethod.POST)
1910
    public String expiredCustomerOfferItem(HttpServletRequest request, @RequestParam int id,
1911
                                           @RequestParam LocalDateTime endDate, Model model) throws Exception {
31147 tejbeer 1912
 
31352 amit.gupta 1913
        CustomerOfferItem customerOfferItem = customerOfferItemRepository.selectById(id);
31147 tejbeer 1914
 
31352 amit.gupta 1915
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItem.getCustomerOfferId());
31147 tejbeer 1916
 
31352 amit.gupta 1917
        if ((endDate.toLocalDate().equals(customerOffer.getStartDate().toLocalDate())
1918
                || endDate.toLocalDate().isAfter(customerOffer.getStartDate().toLocalDate()))
1919
                && (endDate.toLocalDate().isEqual(customerOffer.getEndDate().toLocalDate())
1920
                || endDate.toLocalDate().isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1921
 
31352 amit.gupta 1922
            customerOfferItem.setEndDate(endDate.toLocalDate());
31147 tejbeer 1923
 
31352 amit.gupta 1924
        } else {
1925
            throw new ProfitMandiBusinessException("Date", customerOffer.getOfferName(),
1926
                    "customer offer expired on " + customerOffer.getEndDate());
1927
        }
1928
        Map<Integer, List<Item>> catalogItemMap = itemRepository
1929
                .selectAllByCatalogItemId(customerOfferItem.getCatalogId()).stream()
1930
                .collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
1931
        model.addAttribute("catalogItemMap", catalogItemMap);
31147 tejbeer 1932
 
31352 amit.gupta 1933
        model.addAttribute("coi", customerOfferItem);
31147 tejbeer 1934
 
31352 amit.gupta 1935
        return "customer-offer-item-index";
31147 tejbeer 1936
 
31352 amit.gupta 1937
    }
31147 tejbeer 1938
 
31352 amit.gupta 1939
    @RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1940
    public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
1941
                                      @RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 1942
 
31352 amit.gupta 1943
        CustomerOffer co = customerOfferRepository.selectById(id);
1944
        co.setEndDate(endDate);
1945
        co.setUpdatedTimestamp(LocalDateTime.now());
31147 tejbeer 1946
 
31352 amit.gupta 1947
        model.addAttribute("co", co);
31147 tejbeer 1948
 
31352 amit.gupta 1949
        return "customer-index-offer";
31147 tejbeer 1950
 
31352 amit.gupta 1951
    }
31147 tejbeer 1952
 
31352 amit.gupta 1953
    @RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1954
    public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 1955
 
31352 amit.gupta 1956
        List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1957
        List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1958
                uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
31147 tejbeer 1959
 
31352 amit.gupta 1960
        model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1961
        return "samsung-upgrade-offer";
31147 tejbeer 1962
 
31352 amit.gupta 1963
    }
31147 tejbeer 1964
 
31352 amit.gupta 1965
    @RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1966
    public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1967
            throws ProfitMandiBusinessException {
29707 tejbeer 1968
 
31352 amit.gupta 1969
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1970
        suo.setStatus(UpgradeOfferStatus.approved);
1971
        suo.setApprovedTimestamp(LocalDateTime.now());
1972
        model.addAttribute("suo", suo);
1973
        return "samsung-upgrade-offer-index";
29707 tejbeer 1974
 
31352 amit.gupta 1975
    }
29707 tejbeer 1976
 
31352 amit.gupta 1977
    @RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1978
    public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1979
            throws ProfitMandiBusinessException {
29707 tejbeer 1980
 
31352 amit.gupta 1981
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1982
        suo.setStatus(UpgradeOfferStatus.rejected);
29707 tejbeer 1983
 
31352 amit.gupta 1984
        model.addAttribute("suo", suo);
1985
        return "samsung-upgrade-offer-index";
29707 tejbeer 1986
 
31352 amit.gupta 1987
    }
29707 tejbeer 1988
 
35628 amit 1989
    @RequestMapping(value = "/schemes/rejectActivatedSchemeIds", method = RequestMethod.GET)
1990
    public String rejectActivatedSchemeIds(HttpServletRequest request, @RequestParam String schemeIds, Model model)
1991
            throws Exception {
1992
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1993
        String emailId = loginDetails.getEmailId();
1994
 
1995
        List<String> techEmails = new ArrayList<>();
1996
        for (EscalationType et : Arrays.asList(EscalationType.L2, EscalationType.L3, EscalationType.L4, EscalationType.L5)) {
1997
            techEmails.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_TECHNOLOGY, et)
1998
                    .stream().map(x -> x.getEmailId()).collect(Collectors.toList()));
1999
        }
2000
        if (!techEmails.contains(emailId)) {
2001
            throw new ProfitMandiBusinessException("User", emailId, "Unauthorised access");
2002
        }
2003
 
2004
        List<Integer> schemeIdList = Arrays.stream(schemeIds.split(","))
2005
                .map(String::trim).filter(s -> !s.isEmpty())
2006
                .map(Integer::parseInt).collect(Collectors.toList());
2007
 
2008
        schemeService.rejectActivatedSchemeIds(schemeIdList);
2009
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
2010
        return "response";
2011
    }
2012
 
22860 ashik.ali 2013
}