Subversion Repositories SmartDukaan

Rev

Rev 35938 | 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 {
439
        for (int schemeId : schemeItems.getSchemeIds()) {
440
            if (schemeRepository.selectById(schemeId) != null)
441
                for (int catalogId : schemeItems.getCatalogIds()) {
442
                    if (tagListingRepository.selectAllByCatalogIds(Arrays.asList(catalogId)).size() > 0) {
443
                        SchemeItem si = new SchemeItem();
444
                        si.setCatalogId(catalogId);
445
                        si.setSchemeId(schemeId);
446
                        si.setCreateTimestamp(LocalDateTime.now());
447
                        try {
448
                            schemeItemRepository.persist(si);
449
                        } catch (Exception e) {
450
                            LOGGER.info("Scheme aleady exist");
451
                        }
452
                        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
453
                    } else {
31520 amit.gupta 454
                        LOGGER.info("Invalid catalog Id - {}", catalogId);
31352 amit.gupta 455
                    }
456
                }
457
        }
458
        return "response";
459
    }
29608 amit.gupta 460
 
31352 amit.gupta 461
    @RequestMapping(value = "/addItemToScheme", method = RequestMethod.POST)
462
    public String updateScheme(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
463
            throws Exception {
36394 amit 464
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
31352 amit.gupta 465
        for (int schemeId : schemeItems.getSchemeIds()) {
36394 amit 466
            Scheme scheme = schemeRepository.selectById(schemeId);
467
            if (scheme != null) {
31352 amit.gupta 468
                for (int catalogId : schemeItems.getCatalogIds()) {
36394 amit 469
                    // Use dates from request if provided, else default to scheme's window
470
                    LocalDateTime startDate = schemeItems.getStartDate() != null ? schemeItems.getStartDate() : scheme.getStartDateTime();
471
                    LocalDateTime endDate = schemeItems.getEndDate() != null ? schemeItems.getEndDate() : scheme.getEndDateTime();
472
                    try {
473
                        schemeService.addSchemeItemWithDates(schemeId, catalogId, startDate, endDate, loginDetails.getFofoId());
474
                    } catch (ProfitMandiBusinessException e) {
475
                        throw e;
476
                    } catch (Exception e) {
477
                        LOGGER.info("Scheme already exist for schemeId={}, catalogId={}", schemeId, catalogId);
31352 amit.gupta 478
                    }
36394 amit 479
                    model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31352 amit.gupta 480
                }
36394 amit 481
            }
31352 amit.gupta 482
        }
483
        return "response";
484
    }
30768 amit.gupta 485
 
31352 amit.gupta 486
    @RequestMapping(value = "/createScheme", method = RequestMethod.GET)
487
    public String createScheme(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
488
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29608 amit.gupta 489
 
31352 amit.gupta 490
        LocalDate currentdate = LocalDate.now();
491
        Month month = currentdate.getMonth().minus(1);
492
        model.addAttribute("month", month);
29608 amit.gupta 493
 
31352 amit.gupta 494
        // Map<Integer, String> itemIdItemDescriptionMap =
495
        // inventoryService.getAllItemIdItemDescriptionMap();
496
        // model.addAttribute("itemIdItemDescriptionMap", itemIdItemDescriptionMap);
497
        // List<Category> categories = inventoryService.getAllCategories();
498
        List<Category> categories = categoryRepository.selectByIds(categoryIds);
499
        categories = categories.stream().sorted(Comparator.comparing(Category::getId)).collect(Collectors.toList());
500
        // Set<String> brands =
501
        // inventoryService.getAllTagListingBrands(ProfitMandiConstants.MOBILE_CATEGORY_ID);
502
        // brands.addAll(inventoryService.getAllTagListingBrands(14206));
29608 amit.gupta 503
 
31352 amit.gupta 504
        boolean fullAccesss = this.getAccess(loginDetails.getEmailId());
25256 amit.gupta 505
 
31352 amit.gupta 506
        List<Region> regionList = regionRepository.selectAll();
29608 amit.gupta 507
 
34317 amit.gupta 508
        List<SchemeType> schemeTypes = fullAccesss ? Arrays.stream(SchemeType.values()).collect(Collectors.toList()) : SchemeType.RESTRICTED_SCHEMES_TYPES;
509
        model.addAttribute("schemeTypes", schemeTypes);
31352 amit.gupta 510
        model.addAttribute("regionList", regionList);
29608 amit.gupta 511
 
31352 amit.gupta 512
        model.addAttribute("categories", categories);
513
        model.addAttribute("retailerTypes", PartnerType.values());
514
        return "create-scheme";
515
    }
29663 manish 516
 
31352 amit.gupta 517
    @RequestMapping(value = "/extendAllSchemes", method = RequestMethod.POST)
518
    public String extendAllScheme(HttpServletRequest request, @RequestBody LocalDateTime extendDatetime, Model model)
519
            throws Exception {
520
        List<Scheme> schemes = schemeRepository.selectActiveAll();
31387 amit.gupta 521
        //Filter scheme types ACTIVATION/SPECIAL SUPPORT/SELLOUT from extending
522
        schemes = schemes.stream().filter(x -> !EXCLUDE_EXTEND_SCHEMES.contains(x.getType())).collect(Collectors.toList());
31352 amit.gupta 523
        if (schemes.size() > 0) {
524
            for (Scheme scheme : schemes) {
525
                if (scheme.getExpireTimestamp() == null) {
526
                    scheme.setEndDateTime(extendDatetime);
527
                    schemeRepository.persist(scheme);
528
                }
529
            }
530
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
531
            return "response";
532
        }
533
        model.addAttribute("response1", mvcResponseSender.createResponseString(false));
534
        return "response";
535
    }
29608 amit.gupta 536
 
31352 amit.gupta 537
    @RequestMapping(value = "/getCatalogDescriptionByBrands", method = RequestMethod.GET)
538
    public String getTagListingItemsByBrand(HttpServletRequest request, @RequestParam int categoryId,
539
                                            @RequestParam List<String> brands, Model model) throws Exception {
540
        Map<Integer, String> catalogIdItemDescriptionMap = inventoryService.getModelDescriptionMap(categoryId, brands);
541
        model.addAttribute("catalogIdItemDescriptionMap", catalogIdItemDescriptionMap);
542
        // model.addAttribute("brands", inventoryService.getAllBrands());
29585 manish 543
 
31352 amit.gupta 544
        return "tag-listing-items-description";
545
    }
29663 manish 546
 
31352 amit.gupta 547
    @RequestMapping(value = "/createScheme", method = RequestMethod.POST)
548
    public String createScheme(HttpServletRequest request, @RequestBody CreateSchemeRequest createSchemeRequest,
549
                               Model model) throws ProfitMandiBusinessException {
550
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
551
        LOGGER.info("CreateSchemeRequest {}", createSchemeRequest);
552
        schemeService.saveScheme(loginDetails.getFofoId(), createSchemeRequest);
553
        return getDefaultSchemes(request, model);
554
    }
29663 manish 555
 
31352 amit.gupta 556
    private String getDefaultSchemes(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
557
        return getSchemes(request, 0, null, 30, 0, 0, PartnerType.ALL, "", model);
558
    }
29663 manish 559
 
31352 amit.gupta 560
    private List<Scheme> setSchemeAmountModel(List<Scheme> schemes) {
561
        for (Scheme scheme : schemes) {
562
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
563
                scheme.setAmountModel(scheme.getAmount() + "%");
564
            } else {
565
                scheme.setAmountModel(scheme.getAmount() + "");
566
            }
567
        }
568
        return schemes;
569
    }
29663 manish 570
 
31352 amit.gupta 571
    // Show 20 recents
29663 manish 572
 
31352 amit.gupta 573
    @RequestMapping(value = "/schemes/delete", method = RequestMethod.DELETE)
574
    public String deleteShcemes(HttpServletRequest request,
575
                                @RequestParam(name = "schemeId", required = false, defaultValue = "0") int schemeId,
576
                                @RequestParam(name = "catalogId", required = false, defaultValue = "0") int catalogId, Model model)
577
            throws Exception {
578
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
579
        if (schemeId > 0 && catalogId > 0) {
580
            schemeItemRepository.deleteByCatalogIdsAndSchemeIds(catalogId, schemeId);
29608 amit.gupta 581
 
31352 amit.gupta 582
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
29585 manish 583
 
31352 amit.gupta 584
            model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
29585 manish 585
 
31352 amit.gupta 586
        }
587
        return "response";
588
    }
29585 manish 589
 
31352 amit.gupta 590
    @RequestMapping(value = "/extendSchemeById", method = RequestMethod.POST)
591
    public String extendSchemeById(HttpServletRequest request,
29585 manish 592
 
31352 amit.gupta 593
                                   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
594
                                   @RequestBody LocalDateTime extendDatetime, Model model) throws Exception {
595
        Scheme scheme = schemeRepository.selectById(schemeId);
596
        if ((!(scheme.getActiveTimestamp() == null)) && scheme.getExpireTimestamp() == null) {
597
            scheme.setEndDateTime(extendDatetime);
598
            schemeRepository.persist(scheme);
599
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
600
            return "response";
601
        }
602
        model.addAttribute("response1", mvcResponseSender.createResponseString(false));
603
        return "response";
604
    }
29608 amit.gupta 605
 
31762 tejbeer 606
    @RequestMapping(value = "/getSchemesByImei", method = RequestMethod.GET)
33182 shampa 607
    public String getSchemesByImei(HttpServletRequest request,
35771 ranu 608
                                   @RequestParam(defaultValue = "") String searchImei,
609
                                   @RequestParam(defaultValue = "false") boolean modal, Model model) throws ProfitMandiBusinessException {
31762 tejbeer 610
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
611
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
612
 
613
            List<Scheme> schemes = null;
614
            List<SchemeInOut> schemeInOuts = null;
615
 
616
            InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumber(searchImei);
617
            int fofoId = inventoryItem.getFofoId();
33306 amit.gupta 618
           List<ItemPurchaseSummaryModel> itemPurchaseSummaryModels = inventoryItemRepository.selectPurchaseSummary(new ArrayList<>(Arrays.asList(inventoryItem.getId())));
31762 tejbeer 619
 
33182 shampa 620
            List<FofoOrder> fofoOrders=fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchImei ,null, null, 0, 0);
35938 amit 621
            LOGGER.info("fofoOrder count: {}", fofoOrders.size());
33182 shampa 622
            List<FofoOrder> filterOrders = fofoOrders.stream().filter(x -> x.getCancelledTimestamp() == null).collect(Collectors.toList());
31762 tejbeer 623
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
624
            Item item = itemRepository.selectById(inventoryItem.getItemId());
625
            Map<Integer, Scheme> schemeMap = new HashMap<>();
626
            double netEarnings = 0;
627
            if (inventoryItem != null) {
628
                // Offer payout
629
                List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(fofoId, searchImei);
33030 amit.gupta 630
                Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream().map(x -> x.getOfferId())
33248 ranu 631
                        .distinct().map(offerId -> {
632
                            try {
633
                                return offerService.getOffer(fofoId, offerId.intValue());
634
                            } catch (ProfitMandiBusinessException e) {
635
                                throw new RuntimeException(e);
636
                            }
637
                        }).collect(Collectors.toMap(x -> x.getId(), x -> x));
31762 tejbeer 638
 
639
                schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
33182 shampa 640
                ActivatedImei activatedImei = activatedImeiRepository.selectBySerialNumber(searchImei);
31762 tejbeer 641
 
642
                if (!schemeInOuts.isEmpty()) {
643
                    netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED)).collect(Collectors.summingDouble(x -> x.getAmount()));
644
                    List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
645
 
646
                    schemes = schemeRepository.selectBySchemeIds(schemeIds);
647
                    for (Scheme scheme : schemes) {
648
                        if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
649
                            scheme.setAmountModel(scheme.getAmount() + "%");
650
                        } else {
651
                            scheme.setAmountModel(scheme.getAmount() + "");
652
                        }
653
                    }
654
 
655
                    schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
656
                }
33182 shampa 657
                List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByFofoIdImei(fofoId, searchImei);
31762 tejbeer 658
                if (priceDropImeis.size() > 0) {
35938 amit 659
                    List<Integer> priceDropIds = priceDropImeis.stream().map(PriceDropIMEI::getPriceDropId).distinct().collect(Collectors.toList());
660
                    List<PriceDrop> priceDrops = priceDropRepository.selectByIds(priceDropIds);
661
                    Map<Integer, PriceDrop> priceDropMap = priceDrops.stream().collect(Collectors.toMap(PriceDrop::getId, x -> x));
31762 tejbeer 662
                    for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
35938 amit 663
                        priceDropIMEI.setPriceDrop(priceDropMap.get(priceDropIMEI.getPriceDropId()));
31762 tejbeer 664
                    }
665
                    model.addAttribute("priceDropImeis", priceDropImeis);
666
                }
667
                netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
668
                model.addAttribute("offerPayouts", offerPayouts);
669
                model.addAttribute("offerRequestMap", offerRequestMap);
670
                model.addAttribute("inventoryItem", inventoryItem);
33306 amit.gupta 671
                model.addAttribute("itemPurchaseSummaryModels", itemPurchaseSummaryModels);
33182 shampa 672
                model.addAttribute("fofoOrders", filterOrders);
673
                model.addAttribute("activatedImei", activatedImei);
31762 tejbeer 674
 
33182 shampa 675
 
676
 
31762 tejbeer 677
            }
32331 amit.gupta 678
            LOGGER.info("Net Earnings {}", netEarnings);
31762 tejbeer 679
            model.addAttribute("netEarnings", netEarnings);
680
            model.addAttribute("fofoId", fofoId);
681
            model.addAttribute("schemeMap", schemeMap);
682
            model.addAttribute("item", item);
683
            model.addAttribute("schemeInOut", schemeInOuts);
684
            model.addAttribute("schemes", schemes);
685
            model.addAttribute("customRetailer", customRetailer);
33182 shampa 686
            model.addAttribute("searchImei", searchImei);
35775 ranu 687
            // Return IMEI results only when modal and searchImei provided
688
            if (modal) {
689
                return "scheme-imei-results-modal";
690
            }
31762 tejbeer 691
        }
35771 ranu 692
        if (modal) {
693
            return "scheme-imei-history-modal";
694
        }
31762 tejbeer 695
        return "scheme-imei-history";
696
    }
697
 
35775 ranu 698
    /**
699
     * New endpoint for modal IMEI-wise margin search
700
     * Returns shell when searchImei is empty, results when searchImei is provided
701
     */
702
    @RequestMapping(value = "/getImeiMarginModal", method = RequestMethod.GET)
703
    public String getImeiMarginModal(HttpServletRequest request,
704
                                     @RequestParam(defaultValue = "") String searchImei,
705
                                     @RequestParam(name = "fofoId") int fofoId,
706
                                     Model model) throws ProfitMandiBusinessException {
32232 amit.gupta 707
 
35775 ranu 708
        if (org.apache.commons.lang3.StringUtils.isEmpty(searchImei)) {
709
            // Return empty shell with search boxes
710
            return "scheme-imei-history-modal";
711
        }
712
 
713
        // Fetch IMEI margin data
714
        List<Scheme> schemes = null;
715
        List<SchemeInOut> schemeInOuts = null;
716
 
717
        InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumber(searchImei);
718
        if (inventoryItem == null) {
719
            model.addAttribute("searchImei", searchImei);
720
            return "scheme-imei-results-modal";
721
        }
722
 
723
        int itemFofoId = inventoryItem.getFofoId();
724
        List<ItemPurchaseSummaryModel> itemPurchaseSummaryModels = inventoryItemRepository.selectPurchaseSummary(new ArrayList<>(Arrays.asList(inventoryItem.getId())));
725
 
726
        List<FofoOrder> fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(itemFofoId, searchImei, null, null, 0, 0);
727
        List<FofoOrder> filterOrders = fofoOrders.stream().filter(x -> x.getCancelledTimestamp() == null).collect(Collectors.toList());
728
        CustomRetailer customRetailer = retailerService.getFofoRetailer(itemFofoId);
729
        Item item = itemRepository.selectById(inventoryItem.getItemId());
730
        Map<Integer, Scheme> schemeMap = new HashMap<>();
731
        double netEarnings = 0;
732
 
733
        // Offer payout
734
        List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(itemFofoId, searchImei);
735
        Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream().map(x -> x.getOfferId())
736
                .distinct().map(offerId -> {
737
                    try {
738
                        return offerService.getOffer(itemFofoId, offerId.intValue());
739
                    } catch (ProfitMandiBusinessException e) {
740
                        throw new RuntimeException(e);
741
                    }
742
                }).collect(Collectors.toMap(x -> x.getId(), x -> x));
743
 
744
        schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
745
        ActivatedImei activatedImei = activatedImeiRepository.selectBySerialNumber(searchImei);
746
 
747
        if (!schemeInOuts.isEmpty()) {
748
            netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED)).collect(Collectors.summingDouble(x -> x.getAmount()));
749
            List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
750
 
751
            schemes = schemeRepository.selectBySchemeIds(schemeIds);
752
            for (Scheme scheme : schemes) {
753
                if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
754
                    scheme.setAmountModel(scheme.getAmount() + "%");
755
                } else {
756
                    scheme.setAmountModel(scheme.getAmount() + "");
757
                }
758
            }
759
            schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
760
        }
761
 
762
        List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByFofoIdImei(itemFofoId, searchImei);
763
        if (priceDropImeis.size() > 0) {
35938 amit 764
            List<Integer> priceDropIds = priceDropImeis.stream().map(PriceDropIMEI::getPriceDropId).distinct().collect(Collectors.toList());
765
            List<PriceDrop> priceDrops = priceDropRepository.selectByIds(priceDropIds);
766
            Map<Integer, PriceDrop> priceDropMap = priceDrops.stream().collect(Collectors.toMap(PriceDrop::getId, x -> x));
35775 ranu 767
            for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
35938 amit 768
                priceDropIMEI.setPriceDrop(priceDropMap.get(priceDropIMEI.getPriceDropId()));
35775 ranu 769
            }
770
            model.addAttribute("priceDropImeis", priceDropImeis);
771
        }
772
 
773
        netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
774
        model.addAttribute("offerPayouts", offerPayouts);
775
        model.addAttribute("offerRequestMap", offerRequestMap);
776
        model.addAttribute("inventoryItem", inventoryItem);
777
        model.addAttribute("itemPurchaseSummaryModels", itemPurchaseSummaryModels);
778
        model.addAttribute("fofoOrders", filterOrders);
779
        model.addAttribute("activatedImei", activatedImei);
780
        model.addAttribute("netEarnings", netEarnings);
781
        model.addAttribute("fofoId", itemFofoId);
782
        model.addAttribute("schemeMap", schemeMap);
783
        model.addAttribute("item", item);
784
        model.addAttribute("schemeInOut", schemeInOuts);
785
        model.addAttribute("schemes", schemes);
786
        model.addAttribute("customRetailer", customRetailer);
787
        model.addAttribute("searchImei", searchImei);
788
 
789
        return "scheme-imei-results-modal";
790
    }
791
 
792
    /**
36394 amit 793
     * Scheme-only net-margin modal for an IMEI, priced at the IMEI's
794
     * purchase-billed date (the date schemes were locked in when the
795
     * partner was billed-in). Offers are intentionally excluded.
796
     */
797
    @RequestMapping(value = "/getImeiNetMarginModal", method = RequestMethod.GET)
798
    public String getImeiNetMarginModal(HttpServletRequest request,
799
                                        @RequestParam(defaultValue = "") String searchImei,
800
                                        @RequestParam int fofoId,
801
                                        Model model) throws ProfitMandiBusinessException {
802
 
803
        model.addAttribute("searchImei", searchImei);
804
        model.addAttribute("fofoId", fofoId);
805
 
806
        if (StringUtils.isBlank(searchImei)) {
807
            model.addAttribute("errorMessage", "Please enter an IMEI.");
808
            return "imei-net-margin-modal";
809
        }
810
 
811
        InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumber(searchImei);
812
        if (inventoryItem == null) {
813
            model.addAttribute("errorMessage", "IMEI not found.");
814
            return "imei-net-margin-modal";
815
        }
816
        if (inventoryItem.getFofoId() != fofoId) {
817
            model.addAttribute("errorMessage", "IMEI not found for this partner.");
818
            return "imei-net-margin-modal";
819
        }
820
 
821
        List<ItemPurchaseSummaryModel> purchaseSummaries = inventoryItemRepository
822
                .selectPurchaseSummary(Arrays.asList(inventoryItem.getId()));
823
        if (purchaseSummaries.isEmpty() || purchaseSummaries.get(0).getInvoiceDate() == null) {
824
            model.addAttribute("errorMessage", "IMEI not yet billed-in — margin unavailable.");
825
            return "imei-net-margin-modal";
826
        }
827
        ItemPurchaseSummaryModel purchaseSummary = purchaseSummaries.get(0);
828
        LocalDate billedDate = purchaseSummary.getInvoiceDate().toLocalDate();
829
 
830
        Item item = purchaseSummary.getItem() != null
831
                ? purchaseSummary.getItem()
832
                : itemRepository.selectById(inventoryItem.getItemId());
833
        int catalogId = item.getCatalogItemId();
834
 
835
        PriceCircularModel priceCircularModel = priceCircularService
836
                .getPriceCircularByOffer(fofoId, Arrays.asList(catalogId), billedDate);
837
 
838
        com.spice.profitmandi.service.pricecircular.PriceCircularItemModelNew itemModel = null;
839
        if (priceCircularModel != null && priceCircularModel.getPriceCircularItemModelNews() != null) {
840
            itemModel = priceCircularModel.getPriceCircularItemModelNews().stream()
841
                    .filter(x -> x.getCatalogId() == catalogId)
842
                    .findFirst().orElse(null);
843
        }
844
 
845
        // Use the same DP basis as SchemeServiceImpl.createSchemeInOut →
846
        // PriceCircularService.getPayouts: actual purchase price stamped on
847
        // inventory_item at GRN time, minus any price-drop credited against
848
        // it. This is what the persisted scheme_in_out.amount values were
849
        // computed against.
850
        double purchasePrice = inventoryItem.getUnitPrice();
851
        double priceDropAmount = Math.max(0d, inventoryItem.getPriceDropAmount());
852
        double effectiveDP = purchasePrice - priceDropAmount;
853
 
854
        // Pull per-IMEI price-drop history for reference display.
855
        List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
856
                .selectByFofoIdImei(fofoId, searchImei);
857
        if (priceDropImeis != null && !priceDropImeis.isEmpty()) {
858
            List<Integer> priceDropIds = priceDropImeis.stream()
859
                    .map(PriceDropIMEI::getPriceDropId).distinct().collect(Collectors.toList());
860
            Map<Integer, PriceDrop> priceDropMap = priceDropRepository.selectByIds(priceDropIds)
861
                    .stream().collect(Collectors.toMap(PriceDrop::getId, x -> x));
862
            for (PriceDropIMEI pdi : priceDropImeis) {
863
                pdi.setPriceDrop(priceDropMap.get(pdi.getPriceDropId()));
864
            }
865
        }
866
 
867
        model.addAttribute("imei", searchImei);
868
        model.addAttribute("billedDate", billedDate);
869
        model.addAttribute("invoiceNumber", purchaseSummary.getInvoiceNumber());
870
        model.addAttribute("modelName", item.getItemDescriptionNoColor());
871
        model.addAttribute("purchasePrice", fmt2(purchasePrice));
872
        model.addAttribute("priceDropAmount", fmt2(priceDropAmount));
873
        model.addAttribute("hasPriceDrop", priceDropAmount > 0d);
874
        model.addAttribute("priceDropImeis", priceDropImeis == null ? Collections.emptyList() : priceDropImeis);
875
 
876
        if (itemModel == null || itemModel.getSchemeSummaryModels() == null
877
                || itemModel.getSchemeSummaryModels().isEmpty()) {
878
            model.addAttribute("noSchemes", true);
879
            model.addAttribute("dp", fmt2(effectiveDP));
880
            model.addAttribute("schemeSummaryModels", Collections.emptyList());
881
            model.addAttribute("contributionMap", Collections.emptyMap());
882
            model.addAttribute("rateMap", Collections.emptyMap());
883
            model.addAttribute("fixedSchemeAmount", fmt2(0d));
884
            model.addAttribute("percentageSchemeAmount", fmt2(0d));
885
            model.addAttribute("nlc", fmt2(effectiveDP));
886
            model.addAttribute("netMargin", fmt2(0d));
887
            return "imei-net-margin-modal";
888
        }
889
 
890
        double fixedTotal = itemModel.getFixedSchemeAmount();
891
        double percentageTotal = itemModel.getPercentageSchemeAmount();
892
        // Recompute NLC against effectiveDP — do NOT reuse
893
        // PriceCircularItemModelNew.getNlc() because it is derived from the
894
        // current TagListing list-DP, not the partner's actual purchase price.
895
        double nlc = (effectiveDP - fixedTotal) / (1d + percentageTotal / 100d);
896
        double netMargin = effectiveDP - nlc;
897
 
898
        Map<Integer, String> contributionMap = new HashMap<>();
899
        Map<Integer, String> rateMap = new HashMap<>();
900
        for (com.spice.profitmandi.service.pricecircular.SchemeSummaryModel ssm : itemModel.getSchemeSummaryModels()) {
901
            double contribution;
902
            if (ssm.getAmountType() == AmountType.FIXED) {
903
                contribution = ssm.getAmount() == null ? 0d : ssm.getAmount();
904
            } else if (ssm.getAmountType() == AmountType.PERCENTAGE && percentageTotal > 0) {
905
                double pct = ssm.getAmount() == null ? 0d : ssm.getAmount();
906
                contribution = effectiveDP * (pct / (100d + percentageTotal));
907
            } else {
908
                contribution = 0d;
909
            }
910
            contributionMap.put(ssm.getSchemeId(), fmt2(contribution));
911
            double rate = ssm.getAmount() == null ? 0d : ssm.getAmount();
912
            String rateStr = ssm.getAmountType() == AmountType.PERCENTAGE
913
                    ? fmt2(rate) + "%"
914
                    : "&#8377; " + fmt2(rate);
915
            rateMap.put(ssm.getSchemeId(), rateStr);
916
        }
917
 
918
        model.addAttribute("noSchemes", false);
919
        model.addAttribute("dp", fmt2(effectiveDP));
920
        model.addAttribute("schemeSummaryModels", itemModel.getSchemeSummaryModels());
921
        model.addAttribute("contributionMap", contributionMap);
922
        model.addAttribute("rateMap", rateMap);
923
        model.addAttribute("fixedSchemeAmount", fmt2(fixedTotal));
924
        model.addAttribute("percentageSchemeAmount", fmt2(percentageTotal));
925
        model.addAttribute("nlc", fmt2(nlc));
926
        model.addAttribute("netMargin", fmt2(netMargin));
927
 
928
        return "imei-net-margin-modal";
929
    }
930
 
931
    private static String fmt2(double v) {
932
        return String.format(Locale.ENGLISH, "%.2f", v);
933
    }
934
 
935
    /**
35775 ranu 936
     * New endpoint for modal model-wise margin search
937
     * Accepts fofoId as parameter to work for both admin and partner views
938
     */
939
    @RequestMapping(value = "/getModelMarginModal", method = RequestMethod.GET)
940
    public String getModelMarginModal(HttpServletRequest request,
941
                                      @RequestParam(name = "searchModel") int searchModel,
942
                                      @RequestParam(name = "fofoId") int fofoId,
943
                                      @RequestParam(required = false) LocalDate date,
944
                                      Model model) throws ProfitMandiBusinessException {
945
        if (date == null) {
946
            date = LocalDate.now();
947
        } else if (date.isAfter(LocalDate.now())) {
948
            date = LocalDate.now();
949
        }
950
 
951
        Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
952
        TagListing tagListing = tagListingRepository.selectByItemId(item.getId());
953
        if (tagListing != null) {
954
            model.addAttribute("dp", tagListing.getSellingPrice());
955
            model.addAttribute("mop", tagListing.getMop());
956
        }
957
        model.addAttribute("modelName", item.getItemDescriptionNoColor());
958
        model.addAttribute("searchModel", searchModel);
959
        model.addAttribute("date", date);
960
 
961
        PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, Arrays.asList(searchModel), date);
962
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
963
        priceDropController.getPriceCircularView(priceCircularModel, model, fs.getCode());
964
 
965
        return "schemes-model-modal";
966
    }
967
 
968
 
32232 amit.gupta 969
    @Autowired
970
    PriceDropController priceDropController;
971
 
33182 shampa 972
    @Autowired
973
    ActivatedImeiRepository activatedImeiRepository;
974
 
31352 amit.gupta 975
    @RequestMapping(value = "/getSchemes", method = RequestMethod.GET)
976
    public String getSchemes(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset,
977
                             @RequestParam(required = false) LocalDate date,
978
                             @RequestParam(name = "limit", required = false, defaultValue = "30") int limit,
979
                             @RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel,
980
                             @RequestParam(name = "searchScheme", required = false, defaultValue = "0") int searchScheme,
981
                             @RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
982
                             @RequestParam(name = "searchImei", required = false, defaultValue = "") String searchImei, Model model)
983
            throws ProfitMandiBusinessException {
984
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
985
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
986
        if (date != null) {
987
            date = date.isAfter(LocalDate.now()) ? LocalDate.now() : date;
988
        } else if (!isAdmin) {
989
            date = LocalDate.now();
990
        }
29608 amit.gupta 991
 
31352 amit.gupta 992
        List<Scheme> schemes = null;
993
        List<SchemeInOut> schemeInOuts = null;
29608 amit.gupta 994
 
31352 amit.gupta 995
        boolean fullAccess = this.getAccess(loginDetails.getEmailId());
29608 amit.gupta 996
 
31352 amit.gupta 997
        model.addAttribute("fullAccess", fullAccess);
998
        model.addAttribute("searchImei", searchImei);
999
        model.addAttribute("isAdmin", isAdmin);
1000
        model.addAttribute("searchModel", searchModel);
1001
        model.addAttribute("searchScheme", searchScheme);
1002
        model.addAttribute("partnerType", partnerType);
1003
        model.addAttribute("date", date);
29608 amit.gupta 1004
 
31352 amit.gupta 1005
        final LocalDate date1 = date;
1006
        if (searchScheme > 0) {
1007
            schemes = Arrays.asList(schemeRepository.selectById(searchScheme));
1008
            this.setSchemeAmountModel(schemes);
1009
            if (schemes.size() > 0) {
1010
                model.addAttribute("schemes", schemes);
1011
                List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
1012
                Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
1013
                model.addAttribute("schemeRegionMap", schemeRegionMap);
1014
                return "schemes";
1015
            } else {
1016
                throw new ProfitMandiBusinessException("SchemeId", searchScheme, "SchemeId Not Found");
1017
            }
1018
        } else if (searchModel > 0) {
1019
            Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
1020
            TagListing tagListing = tagListingRepository.selectByItemId(item.getId());
32331 amit.gupta 1021
            LOGGER.info("tagListing {}", tagListing);
31352 amit.gupta 1022
            if (tagListing != null) {
1023
                model.addAttribute("dp", tagListing.getSellingPrice());
1024
                model.addAttribute("mop", tagListing.getMop());
1025
            }
1026
            model.addAttribute("modelName", item.getItemDescriptionNoColor());
1027
            if (isAdmin) {
1028
                schemes = schemeService
1029
                        .selectSchemeByPartnerType(partnerType, date, searchModel, isAdmin, offset, limit).stream()
1030
                        .filter(x -> x.getId() != 411 && x.getId() != 612).collect(Collectors.toList());
1031
                this.setSchemeAmountModel(schemes);
1032
                model.addAttribute("schemes", schemes);
1033
                List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
31482 amit.gupta 1034
                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 1035
                model.addAttribute("schemeRegionMap", schemeRegionMap);
1036
                return "schemes";
1037
            } else {
32331 amit.gupta 1038
                PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(loginDetails.getFofoId(), Arrays.asList(searchModel), date);
32905 shampa 1039
                FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
33030 amit.gupta 1040
                priceDropController.getPriceCircularView(priceCircularModel, model, fs.getCode());
31352 amit.gupta 1041
            }
29608 amit.gupta 1042
 
31352 amit.gupta 1043
        } else if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
29608 amit.gupta 1044
 
31352 amit.gupta 1045
            LOGGER.info("searchImei" + searchImei);
29608 amit.gupta 1046
 
31352 amit.gupta 1047
            InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
1048
                    loginDetails.getFofoId());
1049
            Item item = itemRepository.selectById(inventoryItem.getItemId());
1050
            Map<Integer, Scheme> schemeMap = new HashMap<>();
1051
            double netEarnings = 0;
1052
            if (inventoryItem != null) {
32331 amit.gupta 1053
                /*date = inventoryItem.getCreateTimestamp().toLocalDate();
1054
                PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(loginDetails.getFofoId(), Arrays.asList(item.getCatalogItemId()), date);
1055
                priceDropController.getPriceCircularView(priceCircularModel, model);*/
31352 amit.gupta 1056
                // Offer payout
1057
                List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(loginDetails.getFofoId(),
1058
                        searchImei);
1059
                Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream()
33248 ranu 1060
                        .map(x -> {
1061
                            try {
1062
                                return offerService.getOffer(loginDetails.getFofoId(), (int) x.getOfferId());
1063
                            } catch (ProfitMandiBusinessException e) {
1064
                                throw new RuntimeException(e);
1065
                            }
1066
                        })
31352 amit.gupta 1067
                        .collect(Collectors.toMap(x -> x.getId(), x -> x));
29608 amit.gupta 1068
 
31352 amit.gupta 1069
                schemeInOuts = schemeInOutRepository
1070
                        .selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
25256 amit.gupta 1071
 
31352 amit.gupta 1072
                if (!schemeInOuts.isEmpty()) {
1073
                    netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED))
1074
                            .collect(Collectors.summingDouble(x -> x.getAmount()));
1075
                    List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId())
1076
                            .collect(Collectors.toList());
23914 govind 1077
 
31352 amit.gupta 1078
                    schemes = schemeRepository.selectBySchemeIds(schemeIds);
1079
                    for (Scheme scheme : schemes) {
1080
                        if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1081
                            scheme.setAmountModel(scheme.getAmount() + "%");
1082
                        } else {
1083
                            scheme.setAmountModel(scheme.getAmount() + "");
1084
                        }
1085
                    }
23914 govind 1086
 
31352 amit.gupta 1087
                    schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
1088
                }
32331 amit.gupta 1089
                netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
1090
 
31352 amit.gupta 1091
                List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
1092
                        .selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
1093
                if (priceDropImeis.size() > 0) {
35938 amit 1094
                    List<Integer> priceDropIds = priceDropImeis.stream().map(PriceDropIMEI::getPriceDropId).distinct().collect(Collectors.toList());
1095
                    List<PriceDrop> priceDrops = priceDropRepository.selectByIds(priceDropIds);
1096
                    Map<Integer, PriceDrop> priceDropMap = priceDrops.stream().collect(Collectors.toMap(PriceDrop::getId, x -> x));
31352 amit.gupta 1097
                    for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
35938 amit 1098
                        priceDropIMEI.setPriceDrop(priceDropMap.get(priceDropIMEI.getPriceDropId()));
31352 amit.gupta 1099
                    }
1100
                    model.addAttribute("priceDropImeis", priceDropImeis);
1101
                }
32331 amit.gupta 1102
 
31352 amit.gupta 1103
                model.addAttribute("offerPayouts", offerPayouts);
1104
                model.addAttribute("offerRequestMap", offerRequestMap);
1105
                model.addAttribute("inventoryItem", inventoryItem);
23914 govind 1106
 
31352 amit.gupta 1107
            }
32331 amit.gupta 1108
            model.addAttribute("netEarnings", netEarnings);
31352 amit.gupta 1109
            model.addAttribute("schemeMap", schemeMap);
1110
            model.addAttribute("item", item);
1111
            model.addAttribute("schemeInOut", schemeInOuts);
1112
        }
31170 amit.gupta 1113
 
31352 amit.gupta 1114
        if (isAdmin) {
34369 amit.gupta 1115
            schemes = schemeRepository.selectAll(0, 300);
31352 amit.gupta 1116
            this.setSchemeAmountModel(schemes);
1117
            List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
1118
            Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
1119
            model.addAttribute("schemes", schemes);
1120
            model.addAttribute("schemeRegionMap", schemeRegionMap);
31170 amit.gupta 1121
 
31352 amit.gupta 1122
            return "schemes";
1123
        } else {
1124
            FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
1125
            model.addAttribute("partnerCode", fs.getCode());
1126
            model.addAttribute("fofoId", fs.getId());
1127
            return "schemes-partner";
1128
        }
23914 govind 1129
 
31352 amit.gupta 1130
    }
23786 amit.gupta 1131
 
31352 amit.gupta 1132
    private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing) {
31505 amit.gupta 1133
        /*if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
31352 amit.gupta 1134
                .filter(x -> x.getId() == fofoId).count() > 0) {
1135
            schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
1136
                    .collect(Collectors.toList());
31505 amit.gupta 1137
        }*/
31352 amit.gupta 1138
        float nlc = tagListing.getSellingPrice();
1139
        for (Scheme scheme : schemes) {
1140
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1141
                if (tagListing != null) {
1142
                    float amount = tagListing.getSellingPrice() * scheme.getAmount() / 100;
1143
                    scheme.setAmountModel(FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
1144
                    nlc -= amount;
1145
                } else {
1146
                    scheme.setAmountModel(scheme.getAmount() + "%");
1147
                }
1148
            } else {
1149
                scheme.setAmountModel(scheme.getAmount() + "");
1150
                nlc -= scheme.getAmount();
1151
            }
1152
        }
23819 govind 1153
 
31352 amit.gupta 1154
        return Math.round(nlc);
23914 govind 1155
 
31352 amit.gupta 1156
    }
29899 tejbeer 1157
 
31352 amit.gupta 1158
    @RequestMapping(value = "/getLastMonthCreditIncome", method = RequestMethod.GET)
1159
    public String getLastMonthCreditIncome(HttpServletRequest request, Model model) throws Exception {
30122 amit.gupta 1160
 
31352 amit.gupta 1161
        String status = "CREDITED";
1162
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23786 amit.gupta 1163
 
31352 amit.gupta 1164
        LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
1165
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
31170 amit.gupta 1166
 
31352 amit.gupta 1167
        YearMonth yearMonth = YearMonth.now();
1168
        LOGGER.info("yearMonth" + yearMonth);
31170 amit.gupta 1169
 
31352 amit.gupta 1170
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), yearMonth);
31170 amit.gupta 1171
 
31352 amit.gupta 1172
        LOGGER.info("partnerType" + partnerType);
31170 amit.gupta 1173
 
31352 amit.gupta 1174
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
31170 amit.gupta 1175
 
31352 amit.gupta 1176
        if (partnerType) {
1177
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1178
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), currentStartMonth,
1179
                            currentDate)
1180
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1181
        }
1182
        List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
1183
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
31170 amit.gupta 1184
 
31352 amit.gupta 1185
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1186
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
31170 amit.gupta 1187
 
31352 amit.gupta 1188
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1189
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), currentStartMonth, currentDate);
26802 tejbeer 1190
 
31352 amit.gupta 1191
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = schemeInOutRepository
1192
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate).stream()
1193
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
28796 tejbeer 1194
 
34409 amit.gupta 1195
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
31352 amit.gupta 1196
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
29608 amit.gupta 1197
 
31352 amit.gupta 1198
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
1199
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30274 amit.gupta 1200
 
31352 amit.gupta 1201
        lastMonthFrontEndIncomes.stream().forEach(x -> {
1202
            if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
1203
                x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
1204
                lastMonthSaleMarginMap.put(x.getBrand(), x);
1205
            } else {
1206
                lastMonthSaleMarginMap.put(x.getBrand(), x);
1207
            }
30274 amit.gupta 1208
 
31352 amit.gupta 1209
        });
1210
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1211
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
30274 amit.gupta 1212
 
31352 amit.gupta 1213
        Set<String> keySet = new HashSet<>();
1214
        keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
1215
        keySet.addAll(lastMonthSaleMarginMap.keySet());
1216
        keySet.addAll(lastMonthPendingIncomeMap.keySet());
28795 tejbeer 1217
 
31352 amit.gupta 1218
        lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
1219
            String brand = x.getKey();
1220
            float amount = x.getValue().getAmount();
1221
            if (!totalAmountMap.containsKey(brand)) {
1222
                totalAmountMap.put(brand, 0f);
1223
            }
1224
            totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
30253 amit.gupta 1225
 
31352 amit.gupta 1226
        });
30122 amit.gupta 1227
 
31352 amit.gupta 1228
        lastMonthPendingIncomeMap.entrySet().stream().forEach(x -> {
1229
            String brand = x.getKey();
1230
            float amount = x.getValue().getAmount();
1231
            if (!totalAmountMap.containsKey(brand)) {
1232
                totalAmountMap.put(brand, 0f);
1233
            }
1234
            totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
28795 tejbeer 1235
 
31352 amit.gupta 1236
        });
28795 tejbeer 1237
 
1238
 
31352 amit.gupta 1239
        Map<Integer, String> monthValueMap = new HashMap<>();
1240
        for (int i = 0; i <= 5; i++) {
1241
            LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1242
            monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
1243
        }
1244
        model.addAttribute("month", 0);
1245
        model.addAttribute("monthValueMap", monthValueMap);
1246
        model.addAttribute("keySet", keySet);
1247
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
28795 tejbeer 1248
 
31352 amit.gupta 1249
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1250
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1251
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1252
        model.addAttribute("status", status);
1253
        model.addAttribute("totalAmountMap", totalAmountMap);
28795 tejbeer 1254
 
31352 amit.gupta 1255
        return "last-month-credited-income";
1256
    }
30651 amit.gupta 1257
 
31352 amit.gupta 1258
    @RequestMapping(value = "/getLastMonthPendingIncome", method = RequestMethod.GET)
1259
    public String getLastMonthPendingIncome(HttpServletRequest request, Model model) throws Exception {
30651 amit.gupta 1260
 
31352 amit.gupta 1261
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
28795 tejbeer 1262
 
31352 amit.gupta 1263
        LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
1264
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
1265
        String status = "PENDING";
31170 amit.gupta 1266
 
31352 amit.gupta 1267
        LOGGER.info("currentStartMonth" + currentStartMonth);
1268
        LOGGER.info("currentDate" + currentDate);
28795 tejbeer 1269
 
31352 amit.gupta 1270
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1271
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
29899 tejbeer 1272
 
31352 amit.gupta 1273
        Map<String, LastMonthCreditedIncomeModel> lastMonthMarginMap = new HashMap<>();
23786 amit.gupta 1274
 
31352 amit.gupta 1275
        for (LastMonthCreditedIncomeModel lastMonthPendingIncomeModel : lastMonthPendingIncomeModels) {
28795 tejbeer 1276
 
31352 amit.gupta 1277
            lastMonthMarginMap.put(lastMonthPendingIncomeModel.getBrand(), lastMonthPendingIncomeModel);
1278
        }
1279
        LOGGER.info("lastMonthPendingIncomeModel" + lastMonthPendingIncomeModels);
1280
        LOGGER.info("lastMonthMarginMap" + lastMonthMarginMap);
1281
        model.addAttribute("lastMonthCreditedIncomeModels", lastMonthPendingIncomeModels);
1282
        model.addAttribute("lastMonthMarginMap", lastMonthMarginMap);
1283
        model.addAttribute("status", status);
28795 tejbeer 1284
 
31352 amit.gupta 1285
        return "last-month-credited-income";
1286
    }
28795 tejbeer 1287
 
31352 amit.gupta 1288
    @RequestMapping(value = "/getLastMonthImeiWiseIncome", method = RequestMethod.GET)
1289
    public String getLastMonthImeiWiseIncome(HttpServletRequest request,
1290
                                             @RequestParam(name = "catalogItemId", required = false, defaultValue = "") int catalogItemId,
1291
                                             @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
1292
            throws Exception {
30053 manish 1293
 
31352 amit.gupta 1294
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 1295
 
31352 amit.gupta 1296
        LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1297
        LocalDateTime lastMonthEnd = lastMonthStart.plusMonths(1);
30053 manish 1298
 
31352 amit.gupta 1299
        HashSet<String> allImeiSet = new LinkedHashSet<>();
30053 manish 1300
 
31352 amit.gupta 1301
        List<LastMonthFrontEndImeiModel> lmfi = schemeInOutRepository
1302
                .selectLastMonthFrontEndImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart, lastMonthEnd);
1303
        List<LastMonthImeiModel> lmpi = schemeInOutRepository.selectLastMonthPurchaseInImei(loginDetails.getFofoId(),
1304
                catalogItemId, lastMonthStart, lastMonthEnd);
1305
        List<LastMonthImeiModel> lmci = schemeInOutRepository.selectLastMonthCreditedImei(loginDetails.getFofoId(),
1306
                catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 1307
 
31352 amit.gupta 1308
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(YearMonth.of(lastMonthStart.getYear(),
1309
                lastMonthStart.getMonth()), loginDetails.getFofoId(), null, catalogItemId);
30053 manish 1310
 
31352 amit.gupta 1311
        LOGGER.info("lmci {}", lmci);
30053 manish 1312
 
31352 amit.gupta 1313
        Map<String, Double> lastmonthCategoryUpgradeMargin = schemeInOutRepository
1314
                .selectLastMonthCategoryUpgradeMarginByImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart,
1315
                        lastMonthEnd)
1316
                .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
30053 manish 1317
 
31352 amit.gupta 1318
        allImeiSet.addAll(lmpi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
1319
        allImeiSet.addAll(lmci.stream().map(x -> x.getImei()).collect(Collectors.toList()));
1320
        allImeiSet.addAll(lmfi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
1321
        allImeiSet.addAll(offerPayoutImeiIncomeModels.stream().map(x -> x.getImei()).collect(Collectors.toList()));
30053 manish 1322
 
31352 amit.gupta 1323
        List<String> allImeiList = new ArrayList<>(allImeiSet);
30053 manish 1324
 
31352 amit.gupta 1325
        LOGGER.info("allImeiList" + allImeiList);
1326
        LOGGER.info("lmcm" + lastmonthCategoryUpgradeMargin);
30253 amit.gupta 1327
 
31352 amit.gupta 1328
        List<LastMonthFrontEndImeiModel> lastMonthFrontEndImeis = schemeInOutRepository
1329
                .selectLastMonthFrontEndByImei(loginDetails.getFofoId(), allImeiList);
31379 amit.gupta 1330
        Map<String, LastMonthFrontEndImeiModel> soldMap = lastMonthFrontEndImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x));
30053 manish 1331
 
31379 amit.gupta 1332
 
31352 amit.gupta 1333
        List<LastMonthImeiModel> lastMonthPurchaseInImeis = schemeInOutRepository
1334
                .selectLastMonthPurchaseInByImei(loginDetails.getFofoId(), allImeiList);
30053 manish 1335
 
31352 amit.gupta 1336
        List<LastMonthImeiModel> lastMonthCreditedImeis = schemeInOutRepository
1337
                .selectLastMonthCreditedByImei(loginDetails.getFofoId(), allImeiList);
1338
        List<OfferPayoutImeiIncomeModel> allOfferPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByImei(allImeiList);
30053 manish 1339
 
31352 amit.gupta 1340
        //Map<String, OfferPayoutImeiIncomeModel> imeisOfferPayoutMap = allOfferPayoutImeiIncomeModels.stream().collect(Collectors.toMap(x->x.getImei(), x->x));
1341
        Map<String, Double> imeiWisePendingSaleAmount = lastMonthCreditedImeis.stream()
1342
                .filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).collect(Collectors
1343
                        .groupingBy(x -> x.getImei(), Collectors.summingDouble(x -> x.getPendingSaleAmount())));
30053 manish 1344
 
31352 amit.gupta 1345
        allOfferPayoutImeiIncomeModels.stream().forEach(x -> {
1346
            if (x.getSaleDate() != null) {
1347
                LastMonthImeiModel lastMonthImeiModel = new LastMonthImeiModel(x.getImei(), (float) x.getSalePayout(),
1348
                        0, "Addnl Margin", x.getSaleDate(), SchemePayoutStatus.CREDITED);
1349
                lastMonthCreditedImeis.add(lastMonthImeiModel);
1350
            }
1351
            if (x.getGrnDate() != null) {
1352
                LastMonthImeiModel lastMonthImeiModel = new LastMonthImeiModel(x.getImei(), (float) x.getPurchasePayout(),
1353
                        0, "Booster Payout", x.getGrnDate(), SchemePayoutStatus.CREDITED);
1354
                lastMonthPurchaseInImeis.add(lastMonthImeiModel);
1355
            }
1356
        });
30053 manish 1357
 
31352 amit.gupta 1358
        Map<String, Map<String, Double>> lastMonthPurchaseInMapPairMap = lastMonthPurchaseInImeis.stream()
1359
                .collect(Collectors.groupingBy(x -> x.getImei(),
1360
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
1361
        Map<String, LocalDate> imeiPurchaseDateMap = lastMonthPurchaseInImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x.getCreateTimeStamp().toLocalDate(), (x, y) -> x));
32236 amit.gupta 1362
        LOGGER.info("Last month front end imeis - {}", lastMonthFrontEndImeis);
32232 amit.gupta 1363
        Map<String, LocalDate> imeiSaleDateMap = lastMonthFrontEndImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x.getCreated()));
31352 amit.gupta 1364
        Map<String, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
1365
                .collect(Collectors.groupingBy(x -> x.getImei(),
1366
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
30053 manish 1367
 
31352 amit.gupta 1368
        // descriptionSet.add("")
30053 manish 1369
 
34409 amit.gupta 1370
        List<String> purchaseList = lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).distinct().collect(Collectors.toList());
1371
        List<String> saleList = lastMonthCreditedImeis.stream().map(x -> x.getDescription()).distinct().collect(Collectors.toList());
30253 amit.gupta 1372
 
31352 amit.gupta 1373
        Map<String, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
30053 manish 1374
 
31352 amit.gupta 1375
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
30235 tejbeer 1376
 
31352 amit.gupta 1377
            String imei = entry.getKey();
1378
            ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imei,
1379
                    imeiPurchaseDateMap.get(imei), null);
1380
            imeiWiseIncomeMapOfMap.put(imei, modelImeiMap);
1381
            double totalAmount = entry.getValue().entrySet().stream()
1382
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1383
            imeiWiseIncomeMapOfMap.get(imei).setTotalIncome(totalAmount);
1384
        }
31283 amit.gupta 1385
 
31352 amit.gupta 1386
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
1387
            Map<String, Double> descriptionAmountMap = entry.getValue();
1388
            if (!imeiWiseIncomeMapOfMap.containsKey(entry.getKey())) {
32232 amit.gupta 1389
                imeiWiseIncomeMapOfMap.put(entry.getKey(), new ImeiWiseIncomePairAndMapModel(entry.getKey(), null, null));
31352 amit.gupta 1390
            }
32232 amit.gupta 1391
            ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(entry.getKey());
1392
            ;
1393
            modelImeiMap.setSaleDate(imeiSaleDateMap.get(entry.getKey()));
30053 manish 1394
 
31352 amit.gupta 1395
            double totalAmount = descriptionAmountMap.entrySet().stream()
1396
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1397
            imeiWiseIncomeMapOfMap.get(entry.getKey())
1398
                    .setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(entry.getKey()).getTotalIncome());
1399
        }
30053 manish 1400
 
31352 amit.gupta 1401
        //Imeis for pending activation
1402
        lastMonthCreditedImeis.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).forEach(x -> {
1403
            if (!imeiWiseIncomeMapOfMap.containsKey(x.getImei())) {
32232 amit.gupta 1404
                imeiWiseIncomeMapOfMap.put(x.getImei(), new ImeiWiseIncomePairAndMapModel(x.getImei()));
31352 amit.gupta 1405
            }
1406
            ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1407
                    .get(x.getImei());
1408
            imeiWiseIncomePairAndMapModel.setSaleDate(x.getCreateTimeStamp().toLocalDate());
1409
            imeiWiseIncomePairAndMapModel.setTotalIncome(x.getPendingSaleAmount() + imeiWiseIncomePairAndMapModel.getTotalIncome());
1410
        });
30053 manish 1411
 
31379 amit.gupta 1412
        lastMonthFrontEndImeis.stream().forEach(lastMonthFrontEndImeiModel -> {
32232 amit.gupta 1413
            if (!imeiWiseIncomeMapOfMap.containsKey(lastMonthFrontEndImeiModel.getImei())) {
1414
                imeiWiseIncomeMapOfMap.put(lastMonthFrontEndImeiModel.getImei(), new ImeiWiseIncomePairAndMapModel(lastMonthFrontEndImeiModel.getImei()));
31379 amit.gupta 1415
            }
32232 amit.gupta 1416
            ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1417
                    .get(lastMonthFrontEndImeiModel.getImei());
1418
            lastMonthFrontEndImeiModel.setNlc(lastMonthFrontEndImeiModel.getDp()
1419
                    - (float) imeiWiseIncomeMapOfMap.get(lastMonthFrontEndImeiModel.getImei()).getTotalIncome());
1420
            lastMonthFrontEndImeiModel.setNetIncome(lastMonthFrontEndImeiModel.getSellingPrice() - lastMonthFrontEndImeiModel.getNlc());
1421
            imeiWiseIncomePairAndMapModel.setSaleDate(lastMonthFrontEndImeiModel.getCreated());
31379 amit.gupta 1422
        });
1423
 
31352 amit.gupta 1424
        model.addAttribute("imeiWisePendingSaleAmount", imeiWisePendingSaleAmount);
1425
        model.addAttribute("month", month);
1426
        model.addAttribute("purchaseList", purchaseList);
1427
        model.addAttribute("saleList", saleList);
1428
        model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1429
        model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1430
        model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1431
        model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
31379 amit.gupta 1432
        model.addAttribute("soldMap", soldMap);
31352 amit.gupta 1433
        model.addAttribute("allOfferPayoutImeiIncomeModels", allOfferPayoutImeiIncomeModels);
1434
        //model.addAttribute("iimeiSaleDateMap", imeiSaleDateMap);
1435
        //model.addAttribute("imeiPurchaseDateMap", imeiPurchaseDateMap);
30053 manish 1436
 
31352 amit.gupta 1437
        return "last-month-imei-wise-income";
1438
    }
30053 manish 1439
 
31352 amit.gupta 1440
    @RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1441
    public String getBrandWiseIncome(HttpServletRequest request,
1442
                                     @RequestParam(name = "brand", required = false, defaultValue = "") String brand,
32232 amit.gupta 1443
                                     @RequestParam(name = "month", required = false, defaultValue = "") int month,
1444
                                     Model model)
31352 amit.gupta 1445
            throws ProfitMandiBusinessException {
1446
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1447
        LOGGER.info("loginDetails {}", loginDetails);
1448
        LOGGER.info("brand" + brand);
1449
        LOGGER.info("month {}", month);
30053 manish 1450
 
31352 amit.gupta 1451
        LocalDateTime monthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1452
        LocalDateTime monthEnd = monthStart.plusMonths(1);
30053 manish 1453
 
31352 amit.gupta 1454
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1455
                YearMonth.of(monthStart.getYear(), monthStart.getMonth()), loginDetails.getFofoId(), brand, null);
32232 amit.gupta 1456
        LOGGER.info("offerPayoutImeiIncomeModels - {}", offerPayoutImeiIncomeModels);
1457
        Map<Integer, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().filter(x -> x.getPurchasePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getPurchasePayout())));
1458
        Map<Integer, Integer> additionalPurchaseQty = offerPayoutImeiIncomeModels.stream().filter(x -> x.getPurchasePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingInt(x -> 1)));
1459
        Map<Integer, Double> additionalSalePayoutMap = offerPayoutImeiIncomeModels.stream().filter(x -> x.getSalePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getSalePayout())));
1460
        Map<Integer, Integer> additionalSaleQty = offerPayoutImeiIncomeModels.stream().filter(x -> x.getSalePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingInt(x -> 1)));
30053 manish 1461
 
32232 amit.gupta 1462
        Set<Integer> allCatalogIds = offerPayoutImeiIncomeModels.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
31352 amit.gupta 1463
        boolean partnerTypeUpgraded = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(),
1464
                YearMonth.now());
30053 manish 1465
 
31352 amit.gupta 1466
        LOGGER.info("partnerType" + partnerTypeUpgraded);
30053 manish 1467
 
31352 amit.gupta 1468
        Map<String, Double> categoryUpgradeBrandModelMap = null;
1469
        if (partnerTypeUpgraded) {
1470
            categoryUpgradeBrandModelMap = schemeInOutRepository
1471
                    .selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, monthStart,
1472
                            monthEnd)
1473
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1474
        }
30053 manish 1475
 
31352 amit.gupta 1476
        List<LastMonthFrontEndBrandWiseIncome> modelWiseSalesMargins = schemeInOutRepository
1477
                .selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand, monthStart, monthEnd);
32232 amit.gupta 1478
        Map<Integer, LastMonthFrontEndBrandWiseIncome> modelWiseSalesMarginsMap = modelWiseSalesMargins.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1479
 
32232 amit.gupta 1480
 
31352 amit.gupta 1481
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMargins = schemeInOutRepository
1482
                .selectLastMonthBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1483
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMarginsMap = modelWiseSchemeOutMargins.stream()
1484
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1485
 
31352 amit.gupta 1486
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeInMargins = schemeInOutRepository
1487
                .selectLastMonthPurchaseBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1488
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeInMarginsMap = modelWiseSchemeInMargins.stream()
1489
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1490
 
32232 amit.gupta 1491
        allCatalogIds.addAll(modelWiseSalesMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
1492
        allCatalogIds.addAll(modelWiseSchemeInMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
1493
        allCatalogIds.addAll(modelWiseSchemeOutMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
30053 manish 1494
 
32232 amit.gupta 1495
        Map<Integer, String> modelNameMap = itemRepository.selectAllByCatalogIds(allCatalogIds).stream().collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x.getModel(), (u, v) -> u));
1496
        Map<Integer, Double> modelIncomeMap = new HashMap<>();
1497
        Map<Integer, Integer> modelPurchaseQtyMap = new HashMap<>();
1498
        Map<Integer, Integer> modelSaleQtyMap = new HashMap<>();
1499
        for (int catalogItemId : modelNameMap.keySet()) {
1500
            int saleQty = 0;
1501
            int purchaseQty = 0;
1502
            double income = 0;
30253 amit.gupta 1503
 
32232 amit.gupta 1504
            if (modelWiseSchemeInMarginsMap.containsKey(catalogItemId)) {
34813 aman 1505
                income += (modelWiseSchemeInMarginsMap.get(catalogItemId).getAmount()) + modelWiseSchemeInMarginsMap.get(catalogItemId).getPendingSaleAmount();
32232 amit.gupta 1506
                purchaseQty += modelWiseSchemeInMarginsMap.get(catalogItemId).getQty();
31352 amit.gupta 1507
            }
32232 amit.gupta 1508
            if (modelWiseSchemeOutMarginsMap.containsKey(catalogItemId)) {
1509
                income += modelWiseSchemeOutMarginsMap.get(catalogItemId).getAmount() + modelWiseSchemeOutMarginsMap.get(catalogItemId).getPendingSaleAmount();
31352 amit.gupta 1510
            }
32232 amit.gupta 1511
            if (additionalSalePayoutMap.containsKey(catalogItemId)) {
1512
                income += additionalSalePayoutMap.get(catalogItemId);
31352 amit.gupta 1513
            }
32232 amit.gupta 1514
            if (additionalPurchasePayout.containsKey(catalogItemId)) {
1515
                income += additionalPurchasePayout.get(catalogItemId);
1516
            }
1517
            if (modelWiseSalesMarginsMap.containsKey(catalogItemId)) {
1518
                income += modelWiseSalesMarginsMap.get(catalogItemId).getAmount();
1519
                saleQty = (int) modelWiseSalesMarginsMap.get(catalogItemId).getQty();
1520
            }
1521
            if (additionalPurchaseQty.containsKey(catalogItemId)) {
1522
                purchaseQty = Math.max(additionalPurchaseQty.get(catalogItemId), purchaseQty);
30253 amit.gupta 1523
 
31352 amit.gupta 1524
            }
32232 amit.gupta 1525
            modelIncomeMap.put(catalogItemId, income);
1526
            modelSaleQtyMap.put(catalogItemId, saleQty);
1527
            modelPurchaseQtyMap.put(catalogItemId, purchaseQty);
30253 amit.gupta 1528
 
32232 amit.gupta 1529
        }
30253 amit.gupta 1530
 
31352 amit.gupta 1531
        model.addAttribute("month", month);
32232 amit.gupta 1532
        model.addAttribute("modelWiseSalesMarginsMap", modelWiseSalesMarginsMap);
31352 amit.gupta 1533
        model.addAttribute("modelWiseSchemeOutMarginsMap", modelWiseSchemeOutMarginsMap);
1534
        model.addAttribute("modelWiseSchemeInMarginsMap", modelWiseSchemeInMarginsMap);
1535
        model.addAttribute("modelNameMap", modelNameMap);
32232 amit.gupta 1536
        model.addAttribute("modelPurchaseQtyMap", modelPurchaseQtyMap);
1537
        model.addAttribute("modelSaleQtyMap", modelSaleQtyMap);
1538
        model.addAttribute("modelIncomeMap", modelIncomeMap);
31352 amit.gupta 1539
        model.addAttribute("categoryUpgradeBrandModelMap", categoryUpgradeBrandModelMap);
1540
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
32232 amit.gupta 1541
        model.addAttribute("additionalSalePayoutMap", additionalSalePayoutMap);
30253 amit.gupta 1542
 
31352 amit.gupta 1543
        return "monthly-brand-wise-income";
30053 manish 1544
 
31352 amit.gupta 1545
    }
30053 manish 1546
 
31352 amit.gupta 1547
    @RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
34813 aman 1548
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @RequestParam(required = false) boolean partnerTask, @PathVariable int yearMonth, Model model)
31352 amit.gupta 1549
            throws ProfitMandiBusinessException {
1550
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30253 amit.gupta 1551
 
31352 amit.gupta 1552
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1553
        LocalDateTime lastMonthEnd = startOfMonth.plusMonths(1);
30253 amit.gupta 1554
 
31352 amit.gupta 1555
        YearMonth monthYear = YearMonth.now();
30053 manish 1556
 
31352 amit.gupta 1557
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
30053 manish 1558
 
31352 amit.gupta 1559
        LOGGER.info("partnerType" + partnerType);
30053 manish 1560
 
31352 amit.gupta 1561
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
30053 manish 1562
 
31352 amit.gupta 1563
        if (partnerType) {
1564
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1565
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), startOfMonth,
1566
                            lastMonthEnd)
1567
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1568
        }
30053 manish 1569
 
31352 amit.gupta 1570
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1571
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30053 manish 1572
 
31352 amit.gupta 1573
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1574
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1575
 
31352 amit.gupta 1576
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1577
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
32232 amit.gupta 1578
        Map<String, LastMonthCreditedIncomeModel> lastMonthFrontEndIncomeMap = lastMonthFrontEndIncomes.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30235 tejbeer 1579
 
31352 amit.gupta 1580
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1581
                YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()), loginDetails.getFofoId(), null, null);
30235 tejbeer 1582
 
31352 amit.gupta 1583
        Map<String, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getPurchasePayout)));
1584
        Map<String, Double> additionSalePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getSalePayout)));
30235 tejbeer 1585
 
1586
 
31352 amit.gupta 1587
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
1588
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1589
 
34409 amit.gupta 1590
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = schemeInOutRepository
1591
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd).stream()
31352 amit.gupta 1592
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1593
 
1594
 
31352 amit.gupta 1595
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = lastMonthPendingIncomeModels.stream()
1596
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1597
 
31352 amit.gupta 1598
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1599
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1600
        Set<String> brandSet = new HashSet<>();
1601
        brandSet.addAll(lastMonthPurchaseInMarginMap.keySet());
1602
        brandSet.addAll(lastMonthSaleMarginMap.keySet());
1603
        brandSet.addAll(lastMonthPendingIncomeMap.keySet());
1604
        brandSet.addAll(additionalPurchasePayout.keySet());
1605
        brandSet.addAll(additionSalePayout.keySet());
33313 amit.gupta 1606
        brandSet.addAll(lastMonthFrontEndIncomeMap.keySet());
31352 amit.gupta 1607
        brandSet.stream().forEach(brand -> {
1608
            totalAmountMap.put(brand,
1609
                    (lastMonthSaleMarginMap.get(brand) == null ? 0 : lastMonthSaleMarginMap.get(brand).getAmount()) +
1610
                            (lastMonthPurchaseInMarginMap.get(brand) == null ? 0 : lastMonthPurchaseInMarginMap.get(brand).getAmount()) +
1611
                            (lastMonthPendingIncomeMap.get(brand) == null ? 0 : lastMonthPendingIncomeMap.get(brand).getAmount()) +
1612
                            (additionalPurchasePayout.get(brand) == null ? 0 : additionalPurchasePayout.get(brand).longValue()) +
32232 amit.gupta 1613
                            (additionSalePayout.get(brand) == null ? 0 : additionSalePayout.get(brand).longValue()) +
1614
                            (lastMonthFrontEndIncomeMap.get(brand) == null ? 0 : lastMonthFrontEndIncomeMap.get(brand).getAmount())
31352 amit.gupta 1615
            );
1616
        });
30053 manish 1617
 
31352 amit.gupta 1618
        Map<Integer, String> monthValueMap = new HashMap<>();
1619
        for (int i = 0; i <= 5; i++) {
1620
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1621
            monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
1622
        }
1623
        model.addAttribute("monthValueMap", monthValueMap);
30053 manish 1624
 
32232 amit.gupta 1625
        model.addAttribute("brandSet", brandSet);
31352 amit.gupta 1626
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1627
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1628
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
1629
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
1630
        model.addAttribute("additionalSalePayoutMap", additionSalePayout);
32232 amit.gupta 1631
        model.addAttribute("lastMonthFrontEndIncomeMap", lastMonthFrontEndIncomeMap);
30053 manish 1632
 
31352 amit.gupta 1633
        model.addAttribute("totalAmountMap", totalAmountMap);
1634
        model.addAttribute("month", yearMonth);
1635
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1636
        LOGGER.info("totalAmountMap {}", totalAmountMap);
1637
        LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
30253 amit.gupta 1638
 
34813 aman 1639
        if (partnerTask) {
1640
            return "monthly-credited-income";
1641
        } else return "last-month-credited-income";
31352 amit.gupta 1642
    }
30253 amit.gupta 1643
 
31352 amit.gupta 1644
    @RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
1645
    public String downloadPage(HttpServletRequest request, Model model) {
1646
        return "schemes-download";
1647
    }
30253 amit.gupta 1648
 
31352 amit.gupta 1649
    @RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
1650
    public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
1651
                                                                  @RequestParam LocalDateTime startDateTime, @RequestParam LocalDateTime endDateTime)
1652
            throws ProfitMandiBusinessException {
30253 amit.gupta 1653
 
31352 amit.gupta 1654
        List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
31334 amit.gupta 1655
 
31352 amit.gupta 1656
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1657
        ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
30253 amit.gupta 1658
 
31352 amit.gupta 1659
        final HttpHeaders headers = new HttpHeaders();
1660
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
1661
        headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
1662
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1663
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1664
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1665
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1666
    }
30053 manish 1667
 
31352 amit.gupta 1668
    @RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
1669
    public String getSchemeById(HttpServletRequest request,
1670
                                @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
1671
            throws ProfitMandiBusinessException {
1672
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 1673
 
31352 amit.gupta 1674
        boolean fullAccess = this.getAccess(loginDetails.getEmailId());
1675
        Scheme scheme = schemeService.getSchemeById(schemeId);
36394 amit 1676
        List<SchemeItem> schemeItems = schemeItemRepository.selectBySchemeId(schemeId);
1677
        List<Category> categories = categoryRepository.selectByIds(categoryIds);
1678
        categories = categories.stream().sorted(Comparator.comparing(Category::getId)).collect(Collectors.toList());
31352 amit.gupta 1679
        model.addAttribute("fullAccess", fullAccess);
1680
        model.addAttribute("scheme", scheme);
36394 amit 1681
        model.addAttribute("schemeItems", schemeItems);
1682
        model.addAttribute("categories", categories);
31352 amit.gupta 1683
        model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
1684
        return "scheme-details";
1685
    }
30053 manish 1686
 
31352 amit.gupta 1687
    @RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
1688
    public String activeSchemeById(@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1689
                                   @RequestParam(name = "offset", defaultValue = "0") int offset,
1690
                                   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1691
            throws ProfitMandiBusinessException {
1692
        schemeService.activeSchemeById(schemeId);
1693
        List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
1694
        for (Scheme scheme : schemes) {
1695
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1696
                scheme.setAmountModel(scheme.getAmount() + "%");
1697
            } else {
1698
                scheme.setAmountModel(scheme.getAmount() + "");
1699
            }
1700
        }
1701
        return "schemes";
1702
    }
30053 manish 1703
 
34568 vikas.jang 1704
    @RequestMapping(value = "/activeSchemeByIds", method = RequestMethod.PUT)
34575 vikas.jang 1705
    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 1706
        List<Integer> ids = Arrays.stream(schemeIds.split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(Integer::parseInt).collect(Collectors.toList());
1707
        List<Scheme> schemes = schemeRepository.selectBySchemeIds(ids);
1708
        schemeService.activeSchemeByIds(schemes);
34575 vikas.jang 1709
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1710
        return "response";
34568 vikas.jang 1711
    }
1712
 
35252 aman 1713
    @RequestMapping(value = "/expireSchemeByIds", method = RequestMethod.PUT)
1714
    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 {
1715
        List<Integer> ids = Arrays.stream(schemeIds.split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(Integer::parseInt).collect(Collectors.toList());
1716
        List<Scheme> schemes = schemeRepository.selectBySchemeIds(ids);
1717
        schemeService.expireSchemeByIds(schemes);
1718
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1719
        return "response";
1720
    }
1721
 
31352 amit.gupta 1722
    @RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
1723
    public String expireSchemeById(HttpServletRequest request,
1724
                                   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1725
                                   @RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp, Model model)
1726
            throws ProfitMandiBusinessException {
1727
        schemeService.expireSchemeById(schemeId, expiryTimestamp);
1728
        return getDefaultSchemes(request, model);
1729
    }
30053 manish 1730
 
36394 amit 1731
    @RequestMapping(value = "/scheme/item/window", method = RequestMethod.PUT)
1732
    public ResponseEntity<?> updateSchemeItemWindow(HttpServletRequest request,
1733
                                                    @RequestParam(name = "schemeItemId") long schemeItemId,
1734
                                                    @RequestParam(name = "startDate") LocalDateTime startDate,
1735
                                                    @RequestParam(name = "endDate") LocalDateTime endDate)
1736
            throws ProfitMandiBusinessException {
1737
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1738
        schemeService.updateSchemeItemWindow(schemeItemId, startDate, endDate, loginDetails.getFofoId());
1739
        return responseSender.ok("Scheme item window updated");
1740
    }
1741
 
1742
    @RequestMapping(value = "/scheme/item/add", method = RequestMethod.POST)
1743
    public ResponseEntity<?> addSchemeItemWithDates(HttpServletRequest request,
1744
                                                    @RequestParam(name = "schemeId") int schemeId,
1745
                                                    @RequestParam(name = "catalogId") int catalogId,
1746
                                                    @RequestParam(name = "startDate") LocalDateTime startDate,
1747
                                                    @RequestParam(name = "endDate") LocalDateTime endDate)
1748
            throws ProfitMandiBusinessException {
1749
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1750
        SchemeItem item = schemeService.addSchemeItemWithDates(schemeId, catalogId, startDate, endDate, loginDetails.getFofoId());
1751
        return responseSender.ok(item);
1752
    }
1753
 
1754
    @RequestMapping(value = "/scheme/items", method = RequestMethod.GET)
1755
    public ResponseEntity<?> getSchemeItems(@RequestParam(name = "schemeId") int schemeId)
1756
            throws ProfitMandiBusinessException {
1757
        List<SchemeItem> items = schemeItemRepository.selectBySchemeId(schemeId);
1758
        return responseSender.ok(items);
1759
    }
1760
 
31352 amit.gupta 1761
    @RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
1762
    public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
1763
                                            @RequestParam(name = "offset", defaultValue = "0") int offset,
1764
                                            @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1765
            throws ProfitMandiBusinessException {
1766
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1767
        return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1768
    }
30053 manish 1769
 
31352 amit.gupta 1770
    @RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1771
    public String getCustomerOffer(HttpServletRequest request,
33795 ranu 1772
                                   @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 1773
            throws ProfitMandiBusinessException {
1774
        List<CustomerOffer> customerOffers = null;
1775
        if (searchModel > 0) {
30053 manish 1776
 
31352 amit.gupta 1777
            Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
1778
            customerOffers = customerOfferRepository.selectActiveOfferByModel(searchModel, LocalDate.now());
1779
            model.addAttribute("modelName", item.getItemDescriptionNoColor());
33795 ranu 1780
        } else if (startDate != null && endDate != null) {
1781
            customerOffers = customerOfferRepository.selectOffersByDates(startDate, endDate);
31352 amit.gupta 1782
        } else {
33795 ranu 1783
            if (startDate == null) {
1784
                startDate = LocalDateTime.now().minusMonths(1);  // One month ago from today
1785
            }
1786
            if (endDate == null) {
1787
                endDate = LocalDateTime.now();  // Current date and time
1788
            }
1789
            customerOffers = customerOfferRepository.selectOffersByDates(startDate, endDate);
31352 amit.gupta 1790
        }
30053 manish 1791
 
31352 amit.gupta 1792
        LOGGER.info("customerOffers" + customerOffers);
30053 manish 1793
 
31352 amit.gupta 1794
        for (CustomerOffer customerOffer : customerOffers) {
30053 manish 1795
 
31352 amit.gupta 1796
            LOGGER.info("ss" + searchModel);
30053 manish 1797
 
31352 amit.gupta 1798
            if (!StringUtils.isEmpty(customerOffer.getPartnerCriteria())) {
33030 amit.gupta 1799
                String partnerCriteria = offerService.getPartnerCriteriaString(gson.fromJson(customerOffer.getPartnerCriteria(), PartnerCriteria.class));
31352 amit.gupta 1800
                customerOffer.setPartnerCriteriaString(partnerCriteria);
1801
            }
30053 manish 1802
 
31352 amit.gupta 1803
        }
30053 manish 1804
 
31352 amit.gupta 1805
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1806
                .collect(Collectors.toList());
31281 amit.gupta 1807
 
31352 amit.gupta 1808
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30053 manish 1809
 
31352 amit.gupta 1810
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1811
                .filter(x -> x != null).collect(Collectors.toList()).stream()
1812
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30053 manish 1813
 
31352 amit.gupta 1814
        model.addAttribute("customRetailersMap", customRetailersMap);
1815
        model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
1816
        model.addAttribute("searchModel", searchModel);
30053 manish 1817
 
31352 amit.gupta 1818
        model.addAttribute("customerOffers", customerOffers);
1819
        return "customer-offer";
30053 manish 1820
 
31352 amit.gupta 1821
    }
30053 manish 1822
 
31352 amit.gupta 1823
    @RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1824
    public String createCustomerOffer(HttpServletRequest request, @RequestBody CustomerOfferModel customerOfferModel,
1825
                                      Model model) throws Exception {
30053 manish 1826
 
31352 amit.gupta 1827
        CustomerOffer co = new CustomerOffer();
1828
        co.setOfferName(customerOfferModel.getOfferName());
1829
        co.setStartDate(customerOfferModel.getStartDate());
1830
        co.setEndDate(customerOfferModel.getEndDate());
1831
        co.setPartnerCriteria(gson.toJson(customerOfferModel.getPartnerCriteria()));
1832
        co.setCreatedTimestamp(LocalDateTime.now());
1833
        co.setUpdatedTimestamp(LocalDateTime.now());
1834
        customerOfferRepository.persist(co);
31281 amit.gupta 1835
 
31352 amit.gupta 1836
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31281 amit.gupta 1837
 
31352 amit.gupta 1838
        return "response";
30053 manish 1839
 
31352 amit.gupta 1840
    }
30053 manish 1841
 
31352 amit.gupta 1842
    @RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1843
    public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1844
        List<List<?>> rows = new ArrayList<>();
30053 manish 1845
 
31352 amit.gupta 1846
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("id",
33795 ranu 1847
                        "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date (dd-mm-yyyy)", "End Date (dd-mm-yyyy)", "Offer Type"),
31352 amit.gupta 1848
                rows);
30053 manish 1849
 
31352 amit.gupta 1850
        final HttpHeaders headers = new HttpHeaders();
1851
        headers.set("Content-Type", "text/csv");
1852
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1853
        headers.setContentLength(baos.toByteArray().length);
30053 manish 1854
 
31352 amit.gupta 1855
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1856
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1857
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
30053 manish 1858
 
31352 amit.gupta 1859
    }
30053 manish 1860
 
31352 amit.gupta 1861
    @RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1862
    public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
1863
                                          HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
23786 amit.gupta 1864
 
31352 amit.gupta 1865
        List<CSVRecord> records = FileUtil.readFile(file);
1866
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
23914 govind 1867
 
31352 amit.gupta 1868
        CustomerOffer customerOffer = customerOfferRepository.selectById(offerId);
1869
        List<Integer> catalogIds = new ArrayList<>();
1870
        for (CSVRecord record : records) {
23786 amit.gupta 1871
 
31352 amit.gupta 1872
            CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
23786 amit.gupta 1873
 
31352 amit.gupta 1874
            if (coi == null) {
1875
                coi = new CustomerOfferItem();
1876
                coi.setCatalogId(Integer.parseInt(record.get(1)));
1877
                coi.setSchemePayout(Integer.parseInt(record.get(2)));
1878
                coi.setDealerPayout(Integer.parseInt(record.get(3)));
33795 ranu 1879
                coi.setOfferType(OfferType.valueOf(record.get(6)));
31352 amit.gupta 1880
                coi.setCustomerOfferId(offerId);
34516 ranu 1881
                coi.setAdditionalInfo(String.valueOf(record.get(7)));
31352 amit.gupta 1882
                coi.setCreatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1883
 
31352 amit.gupta 1884
                customerOfferItemRepository.persist(coi);
29899 tejbeer 1885
 
31352 amit.gupta 1886
            }
1887
            coi.setSchemePayout(Integer.parseInt(record.get(2)));
1888
            coi.setDealerPayout(Integer.parseInt(record.get(3)));
33795 ranu 1889
            coi.setOfferType(OfferType.valueOf(record.get(6)));
34516 ranu 1890
            coi.setAdditionalInfo(String.valueOf(record.get(7)));
31352 amit.gupta 1891
            coi.setCustomerOfferId(offerId);
1892
            coi.setUpdatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1893
 
31352 amit.gupta 1894
            LOGGER.info(record.get(4));
23786 amit.gupta 1895
 
31352 amit.gupta 1896
            LocalDate startDate = LocalDate.parse(record.get(4), formatter);
1897
            LocalDate endDate = LocalDate.parse(record.get(5), formatter);
23786 amit.gupta 1898
 
31352 amit.gupta 1899
            if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1900
                    || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1901
                    && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1902
                    || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1903
                coi.setStartDate(startDate);
26802 tejbeer 1904
 
31352 amit.gupta 1905
            } else {
29707 tejbeer 1906
 
31352 amit.gupta 1907
                catalogIds.add(coi.getCatalogId());
1908
            }
29707 tejbeer 1909
 
31352 amit.gupta 1910
            if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1911
                    || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1912
                    && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1913
                    || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1914
 
31352 amit.gupta 1915
                coi.setEndDate(endDate);
31147 tejbeer 1916
 
31352 amit.gupta 1917
            } else {
1918
                catalogIds.add(coi.getCatalogId());
1919
            }
31147 tejbeer 1920
 
31352 amit.gupta 1921
        }
31147 tejbeer 1922
 
31352 amit.gupta 1923
        if (!catalogIds.isEmpty()) {
1924
            throw new ProfitMandiBusinessException("Please set accurate start and end date", catalogIds,
1925
                    "Please set accurate start and end date");
1926
        }
1927
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1928
 
31352 amit.gupta 1929
        return "response";
31147 tejbeer 1930
 
31352 amit.gupta 1931
    }
31147 tejbeer 1932
 
34788 ranu 1933
 
1934
    @RequestMapping(value = "/CheckIfExistCustomerOfferItem", method = RequestMethod.POST)
1935
    public String CheckIfExistCustomerOfferItem(HttpServletRequest request,
1936
                                                @RequestBody CustomerOfferItemModel customerOfferItemModel, Model model) throws Throwable {
1937
 
1938
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItemModel.getOfferId());
1939
 
1940
        if (!(customerOffer.getEndDate().toLocalDate().equals(LocalDate.now()))
1941
                && customerOffer.getEndDate().isBefore(LocalDateTime.now())) {
1942
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(), "Offer is Expired");
1943
 
1944
        }
1945
 
1946
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
1947
                .selectByOfferAndCatalogId(customerOfferItemModel.getOfferId(), customerOfferItemModel.getCatalogId());
1948
        boolean response = true;
1949
        if (!customerOfferItems.isEmpty()) {
1950
            for (CustomerOfferItem coi : customerOfferItems) {
1951
                if (!(coi.getEndDate().equals(LocalDate.now())) && coi.getEndDate().isAfter(LocalDate.now())) {
1952
                    response = false;
1953
 
1954
                }
1955
            }
1956
        }
1957
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
1958
        return "response";
1959
 
1960
    }
1961
 
31352 amit.gupta 1962
    @RequestMapping(value = "/addCustomerOfferItem", method = RequestMethod.POST)
1963
    public String addCustomerOfferItem(HttpServletRequest request,
1964
                                       @RequestBody CustomerOfferItemModel customerOfferItemModel, Model model) throws Throwable {
31147 tejbeer 1965
 
31352 amit.gupta 1966
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItemModel.getOfferId());
31147 tejbeer 1967
 
31352 amit.gupta 1968
        if (!(customerOffer.getEndDate().toLocalDate().equals(LocalDate.now()))
1969
                && customerOffer.getEndDate().isBefore(LocalDateTime.now())) {
1970
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(), "Offer is Expired");
29707 tejbeer 1971
 
31352 amit.gupta 1972
        }
29707 tejbeer 1973
 
34788 ranu 1974
       /* List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
31352 amit.gupta 1975
                .selectByOfferAndCatalogId(customerOfferItemModel.getOfferId(), customerOfferItemModel.getCatalogId());
29707 tejbeer 1976
 
31352 amit.gupta 1977
        if (!customerOfferItems.isEmpty()) {
29707 tejbeer 1978
 
31352 amit.gupta 1979
            for (CustomerOfferItem coi : customerOfferItems) {
1980
                if (!(coi.getEndDate().equals(LocalDate.now())) && coi.getEndDate().isAfter(LocalDate.now())) {
1981
                    throw new ProfitMandiBusinessException("Catalog Id", coi.getCatalogId(), "Item is already exist.");
1982
                }
1983
            }
29707 tejbeer 1984
 
34788 ranu 1985
        }*/
29707 tejbeer 1986
 
31352 amit.gupta 1987
        LocalDate startDate = customerOfferItemModel.getStartDate().toLocalDate();
1988
        LocalDate endDate = customerOfferItemModel.getEndDate().toLocalDate();
1989
        CustomerOfferItem coi = new CustomerOfferItem();
1990
        coi.setCatalogId(customerOfferItemModel.getCatalogId());
1991
        coi.setSchemePayout(customerOfferItemModel.getSchemePayout());
34516 ranu 1992
        coi.setAdditionalInfo(customerOfferItemModel.getAdditionalInfo());
31352 amit.gupta 1993
        coi.setDealerPayout(customerOfferItemModel.getDealerPayout());
33795 ranu 1994
        coi.setOfferType(customerOfferItemModel.getOfferType());
31352 amit.gupta 1995
        coi.setCustomerOfferId(customerOfferItemModel.getOfferId());
1996
        coi.setUpdatedTimestamp(LocalDateTime.now());
1997
        coi.setCreatedTimestamp(LocalDateTime.now());
29707 tejbeer 1998
 
31352 amit.gupta 1999
        if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
2000
                || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
2001
                && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
2002
                || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 2003
 
31352 amit.gupta 2004
            coi.setStartDate(startDate);
29707 tejbeer 2005
 
31352 amit.gupta 2006
        } else {
29707 tejbeer 2007
 
31352 amit.gupta 2008
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
2009
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
2010
                            + customerOffer.getEndDate());
29707 tejbeer 2011
 
31352 amit.gupta 2012
        }
29707 tejbeer 2013
 
31352 amit.gupta 2014
        if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
2015
                || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
2016
                && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
2017
                || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 2018
 
31352 amit.gupta 2019
            coi.setEndDate(endDate);
29707 tejbeer 2020
 
31352 amit.gupta 2021
        } else {
2022
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
2023
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
2024
                            + customerOffer.getEndDate());
2025
        }
31147 tejbeer 2026
 
31352 amit.gupta 2027
        customerOfferItemRepository.persist(coi);
31147 tejbeer 2028
 
31352 amit.gupta 2029
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 2030
 
31352 amit.gupta 2031
        return "response";
29707 tejbeer 2032
 
31352 amit.gupta 2033
    }
31147 tejbeer 2034
 
31352 amit.gupta 2035
    @RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
2036
    public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
31147 tejbeer 2037
 
31352 amit.gupta 2038
        List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
2039
        List<List<?>> rows = new ArrayList<>();
2040
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
31147 tejbeer 2041
 
31352 amit.gupta 2042
        for (CustomerOfferItem coi : cois) {
2043
            rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout(),
34516 ranu 2044
                    coi.getStartDate().format(formatter), coi.getEndDate().format(formatter), coi.getOfferType(), coi.getAdditionalInfo()));
31147 tejbeer 2045
 
31352 amit.gupta 2046
        }
31147 tejbeer 2047
 
31352 amit.gupta 2048
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
34516 ranu 2049
                Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date", "End Date", "Offer Type", "Additional Info"), rows);
29707 tejbeer 2050
 
31352 amit.gupta 2051
        final HttpHeaders headers = new HttpHeaders();
2052
        headers.set("Content-Type", "text/csv");
2053
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
2054
        headers.setContentLength(baos.toByteArray().length);
31147 tejbeer 2055
 
31352 amit.gupta 2056
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
2057
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
2058
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
31147 tejbeer 2059
 
31352 amit.gupta 2060
    }
31147 tejbeer 2061
 
31352 amit.gupta 2062
    @RequestMapping(value = "/getCustomerOfferItem", method = RequestMethod.GET)
2063
    public String getCustomerOfferItem(HttpServletRequest request, @RequestParam int offerId, Model model)
2064
            throws Exception {
29707 tejbeer 2065
 
31352 amit.gupta 2066
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository.selectByOfferId(offerId);
2067
        List<Integer> catalogIds = customerOfferItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
29707 tejbeer 2068
 
31352 amit.gupta 2069
        Map<Integer, List<Item>> catalogItemMap = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds))
2070
                .stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
29707 tejbeer 2071
 
33795 ranu 2072
        List<OfferType> offerTypes = Arrays.asList(OfferType.values());
2073
 
31352 amit.gupta 2074
        model.addAttribute("catalogItemMap", catalogItemMap);
29707 tejbeer 2075
 
31352 amit.gupta 2076
        model.addAttribute("offerId", offerId);
31147 tejbeer 2077
 
31352 amit.gupta 2078
        model.addAttribute("customerOfferItems", customerOfferItems);
33795 ranu 2079
 
2080
        model.addAttribute("offerTypes", offerTypes);
2081
 
31352 amit.gupta 2082
        return "customer-offer-item";
31147 tejbeer 2083
 
31352 amit.gupta 2084
    }
31147 tejbeer 2085
 
31352 amit.gupta 2086
    @RequestMapping(value = "/expiredCustomerOfferItem", method = RequestMethod.POST)
2087
    public String expiredCustomerOfferItem(HttpServletRequest request, @RequestParam int id,
2088
                                           @RequestParam LocalDateTime endDate, Model model) throws Exception {
31147 tejbeer 2089
 
31352 amit.gupta 2090
        CustomerOfferItem customerOfferItem = customerOfferItemRepository.selectById(id);
31147 tejbeer 2091
 
31352 amit.gupta 2092
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItem.getCustomerOfferId());
31147 tejbeer 2093
 
31352 amit.gupta 2094
        if ((endDate.toLocalDate().equals(customerOffer.getStartDate().toLocalDate())
2095
                || endDate.toLocalDate().isAfter(customerOffer.getStartDate().toLocalDate()))
2096
                && (endDate.toLocalDate().isEqual(customerOffer.getEndDate().toLocalDate())
2097
                || endDate.toLocalDate().isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 2098
 
31352 amit.gupta 2099
            customerOfferItem.setEndDate(endDate.toLocalDate());
31147 tejbeer 2100
 
31352 amit.gupta 2101
        } else {
2102
            throw new ProfitMandiBusinessException("Date", customerOffer.getOfferName(),
2103
                    "customer offer expired on " + customerOffer.getEndDate());
2104
        }
2105
        Map<Integer, List<Item>> catalogItemMap = itemRepository
2106
                .selectAllByCatalogItemId(customerOfferItem.getCatalogId()).stream()
2107
                .collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
2108
        model.addAttribute("catalogItemMap", catalogItemMap);
31147 tejbeer 2109
 
31352 amit.gupta 2110
        model.addAttribute("coi", customerOfferItem);
31147 tejbeer 2111
 
31352 amit.gupta 2112
        return "customer-offer-item-index";
31147 tejbeer 2113
 
31352 amit.gupta 2114
    }
31147 tejbeer 2115
 
31352 amit.gupta 2116
    @RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
2117
    public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
2118
                                      @RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 2119
 
31352 amit.gupta 2120
        CustomerOffer co = customerOfferRepository.selectById(id);
2121
        co.setEndDate(endDate);
2122
        co.setUpdatedTimestamp(LocalDateTime.now());
31147 tejbeer 2123
 
31352 amit.gupta 2124
        model.addAttribute("co", co);
31147 tejbeer 2125
 
31352 amit.gupta 2126
        return "customer-index-offer";
31147 tejbeer 2127
 
31352 amit.gupta 2128
    }
31147 tejbeer 2129
 
31352 amit.gupta 2130
    @RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
2131
    public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 2132
 
31352 amit.gupta 2133
        List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
2134
        List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
2135
                uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
31147 tejbeer 2136
 
31352 amit.gupta 2137
        model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
2138
        return "samsung-upgrade-offer";
31147 tejbeer 2139
 
31352 amit.gupta 2140
    }
31147 tejbeer 2141
 
31352 amit.gupta 2142
    @RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
2143
    public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
2144
            throws ProfitMandiBusinessException {
29707 tejbeer 2145
 
31352 amit.gupta 2146
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
2147
        suo.setStatus(UpgradeOfferStatus.approved);
2148
        suo.setApprovedTimestamp(LocalDateTime.now());
2149
        model.addAttribute("suo", suo);
2150
        return "samsung-upgrade-offer-index";
29707 tejbeer 2151
 
31352 amit.gupta 2152
    }
29707 tejbeer 2153
 
31352 amit.gupta 2154
    @RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
2155
    public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
2156
            throws ProfitMandiBusinessException {
29707 tejbeer 2157
 
31352 amit.gupta 2158
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
2159
        suo.setStatus(UpgradeOfferStatus.rejected);
29707 tejbeer 2160
 
31352 amit.gupta 2161
        model.addAttribute("suo", suo);
2162
        return "samsung-upgrade-offer-index";
29707 tejbeer 2163
 
31352 amit.gupta 2164
    }
29707 tejbeer 2165
 
35628 amit 2166
    @RequestMapping(value = "/schemes/rejectActivatedSchemeIds", method = RequestMethod.GET)
2167
    public String rejectActivatedSchemeIds(HttpServletRequest request, @RequestParam String schemeIds, Model model)
2168
            throws Exception {
2169
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2170
        String emailId = loginDetails.getEmailId();
2171
 
2172
        List<String> techEmails = new ArrayList<>();
2173
        for (EscalationType et : Arrays.asList(EscalationType.L2, EscalationType.L3, EscalationType.L4, EscalationType.L5)) {
2174
            techEmails.addAll(csService.getAuthUserByCategoryId(ProfitMandiConstants.TICKET_CATEGORY_TECHNOLOGY, et)
2175
                    .stream().map(x -> x.getEmailId()).collect(Collectors.toList()));
2176
        }
2177
        if (!techEmails.contains(emailId)) {
2178
            throw new ProfitMandiBusinessException("User", emailId, "Unauthorised access");
2179
        }
2180
 
2181
        List<Integer> schemeIdList = Arrays.stream(schemeIds.split(","))
2182
                .map(String::trim).filter(s -> !s.isEmpty())
2183
                .map(Integer::parseInt).collect(Collectors.toList());
2184
 
2185
        schemeService.rejectActivatedSchemeIds(schemeIdList);
2186
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
2187
        return "response";
2188
    }
2189
 
22860 ashik.ali 2190
}