Subversion Repositories SmartDukaan

Rev

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