Subversion Repositories SmartDukaan

Rev

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