Subversion Repositories SmartDukaan

Rev

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

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