Subversion Repositories SmartDukaan

Rev

Rev 36628 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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