Subversion Repositories SmartDukaan

Rev

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