Subversion Repositories SmartDukaan

Rev

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