Subversion Repositories SmartDukaan

Rev

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

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