Subversion Repositories SmartDukaan

Rev

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