Subversion Repositories SmartDukaan

Rev

Rev 34568 | Rev 34587 | 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;
57
import org.springframework.ui.Model;
58
import org.springframework.web.bind.annotation.*;
59
import org.springframework.web.multipart.MultipartFile;
29585 manish 60
 
31170 amit.gupta 61
import javax.servlet.http.HttpServletRequest;
62
import javax.servlet.http.HttpServletResponse;
63
import javax.transaction.Transactional;
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
25369 amit.gupta 73
@Transactional(rollbackOn = 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,
610
                                   @RequestParam (defaultValue = "") String searchImei, Model model) throws ProfitMandiBusinessException {
31762 tejbeer 611
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
612
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
613
 
614
            List<Scheme> schemes = null;
615
            List<SchemeInOut> schemeInOuts = null;
616
 
617
            InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumber(searchImei);
618
            int fofoId = inventoryItem.getFofoId();
33306 amit.gupta 619
           List<ItemPurchaseSummaryModel> itemPurchaseSummaryModels = inventoryItemRepository.selectPurchaseSummary(new ArrayList<>(Arrays.asList(inventoryItem.getId())));
31762 tejbeer 620
 
33182 shampa 621
            List<FofoOrder> fofoOrders=fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchImei ,null, null, 0, 0);
622
            LOGGER.info("fofoOrder {}", fofoOrders);
623
            List<FofoOrder> filterOrders = fofoOrders.stream().filter(x -> x.getCancelledTimestamp() == null).collect(Collectors.toList());
31762 tejbeer 624
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
625
            Item item = itemRepository.selectById(inventoryItem.getItemId());
626
            Map<Integer, Scheme> schemeMap = new HashMap<>();
627
            double netEarnings = 0;
628
            if (inventoryItem != null) {
629
                // Offer payout
630
                List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(fofoId, searchImei);
33030 amit.gupta 631
                Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream().map(x -> x.getOfferId())
33248 ranu 632
                        .distinct().map(offerId -> {
633
                            try {
634
                                return offerService.getOffer(fofoId, offerId.intValue());
635
                            } catch (ProfitMandiBusinessException e) {
636
                                throw new RuntimeException(e);
637
                            }
638
                        }).collect(Collectors.toMap(x -> x.getId(), x -> x));
31762 tejbeer 639
 
640
                schemeInOuts = schemeInOutRepository.selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
33182 shampa 641
                ActivatedImei activatedImei = activatedImeiRepository.selectBySerialNumber(searchImei);
31762 tejbeer 642
 
643
                if (!schemeInOuts.isEmpty()) {
644
                    netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED)).collect(Collectors.summingDouble(x -> x.getAmount()));
645
                    List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId()).collect(Collectors.toList());
646
 
647
                    schemes = schemeRepository.selectBySchemeIds(schemeIds);
648
                    for (Scheme scheme : schemes) {
649
                        if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
650
                            scheme.setAmountModel(scheme.getAmount() + "%");
651
                        } else {
652
                            scheme.setAmountModel(scheme.getAmount() + "");
653
                        }
654
                    }
655
 
656
                    schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
657
                }
33182 shampa 658
                List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByFofoIdImei(fofoId, searchImei);
31762 tejbeer 659
                if (priceDropImeis.size() > 0) {
660
 
661
                    for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
662
                        int priceDropId = priceDropIMEI.getPriceDropId();
663
                        PriceDrop pd = priceDropRepository.selectById(priceDropId);
664
                        priceDropIMEI.setPriceDrop(pd);
665
                    }
666
                    model.addAttribute("priceDropImeis", priceDropImeis);
667
                }
668
                netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
669
                model.addAttribute("offerPayouts", offerPayouts);
670
                model.addAttribute("offerRequestMap", offerRequestMap);
671
                model.addAttribute("inventoryItem", inventoryItem);
33306 amit.gupta 672
                model.addAttribute("itemPurchaseSummaryModels", itemPurchaseSummaryModels);
33182 shampa 673
                model.addAttribute("fofoOrders", filterOrders);
674
                model.addAttribute("activatedImei", activatedImei);
31762 tejbeer 675
 
33182 shampa 676
 
677
 
31762 tejbeer 678
            }
32331 amit.gupta 679
            LOGGER.info("Net Earnings {}", netEarnings);
31762 tejbeer 680
            model.addAttribute("netEarnings", netEarnings);
681
            model.addAttribute("fofoId", fofoId);
682
            model.addAttribute("schemeMap", schemeMap);
683
            model.addAttribute("item", item);
684
            model.addAttribute("schemeInOut", schemeInOuts);
685
            model.addAttribute("schemes", schemes);
686
            model.addAttribute("customRetailer", customRetailer);
33182 shampa 687
            model.addAttribute("searchImei", searchImei);
31762 tejbeer 688
        }
689
        return "scheme-imei-history";
690
    }
691
 
32232 amit.gupta 692
 
693
    @Autowired
694
    PriceDropController priceDropController;
695
 
33182 shampa 696
    @Autowired
697
    ActivatedImeiRepository activatedImeiRepository;
698
 
31352 amit.gupta 699
    @RequestMapping(value = "/getSchemes", method = RequestMethod.GET)
700
    public String getSchemes(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset,
701
                             @RequestParam(required = false) LocalDate date,
702
                             @RequestParam(name = "limit", required = false, defaultValue = "30") int limit,
703
                             @RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel,
704
                             @RequestParam(name = "searchScheme", required = false, defaultValue = "0") int searchScheme,
705
                             @RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
706
                             @RequestParam(name = "searchImei", required = false, defaultValue = "") String searchImei, Model model)
707
            throws ProfitMandiBusinessException {
708
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
709
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
710
        if (date != null) {
711
            date = date.isAfter(LocalDate.now()) ? LocalDate.now() : date;
712
        } else if (!isAdmin) {
713
            date = LocalDate.now();
714
        }
29608 amit.gupta 715
 
31352 amit.gupta 716
        List<Scheme> schemes = null;
717
        List<SchemeInOut> schemeInOuts = null;
29608 amit.gupta 718
 
31352 amit.gupta 719
        boolean fullAccess = this.getAccess(loginDetails.getEmailId());
29608 amit.gupta 720
 
31352 amit.gupta 721
        model.addAttribute("fullAccess", fullAccess);
722
        model.addAttribute("searchImei", searchImei);
723
        model.addAttribute("isAdmin", isAdmin);
724
        model.addAttribute("searchModel", searchModel);
725
        model.addAttribute("searchScheme", searchScheme);
726
        model.addAttribute("partnerType", partnerType);
727
        model.addAttribute("date", date);
29608 amit.gupta 728
 
31352 amit.gupta 729
        final LocalDate date1 = date;
730
        if (searchScheme > 0) {
731
            schemes = Arrays.asList(schemeRepository.selectById(searchScheme));
732
            this.setSchemeAmountModel(schemes);
733
            if (schemes.size() > 0) {
734
                model.addAttribute("schemes", schemes);
735
                List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
736
                Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
737
                model.addAttribute("schemeRegionMap", schemeRegionMap);
738
                return "schemes";
739
            } else {
740
                throw new ProfitMandiBusinessException("SchemeId", searchScheme, "SchemeId Not Found");
741
            }
742
        } else if (searchModel > 0) {
743
            Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
744
            TagListing tagListing = tagListingRepository.selectByItemId(item.getId());
32331 amit.gupta 745
            LOGGER.info("tagListing {}", tagListing);
31352 amit.gupta 746
            if (tagListing != null) {
747
                model.addAttribute("dp", tagListing.getSellingPrice());
748
                model.addAttribute("mop", tagListing.getMop());
749
            }
750
            model.addAttribute("modelName", item.getItemDescriptionNoColor());
751
            if (isAdmin) {
752
                schemes = schemeService
753
                        .selectSchemeByPartnerType(partnerType, date, searchModel, isAdmin, offset, limit).stream()
754
                        .filter(x -> x.getId() != 411 && x.getId() != 612).collect(Collectors.toList());
755
                this.setSchemeAmountModel(schemes);
756
                model.addAttribute("schemes", schemes);
757
                List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
31482 amit.gupta 758
                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 759
                model.addAttribute("schemeRegionMap", schemeRegionMap);
760
                return "schemes";
761
            } else {
32331 amit.gupta 762
                PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(loginDetails.getFofoId(), Arrays.asList(searchModel), date);
32905 shampa 763
                FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
33030 amit.gupta 764
                priceDropController.getPriceCircularView(priceCircularModel, model, fs.getCode());
31352 amit.gupta 765
            }
29608 amit.gupta 766
 
31352 amit.gupta 767
        } else if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
29608 amit.gupta 768
 
31352 amit.gupta 769
            LOGGER.info("searchImei" + searchImei);
29608 amit.gupta 770
 
31352 amit.gupta 771
            InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
772
                    loginDetails.getFofoId());
773
            Item item = itemRepository.selectById(inventoryItem.getItemId());
774
            Map<Integer, Scheme> schemeMap = new HashMap<>();
775
            double netEarnings = 0;
776
            if (inventoryItem != null) {
32331 amit.gupta 777
                /*date = inventoryItem.getCreateTimestamp().toLocalDate();
778
                PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(loginDetails.getFofoId(), Arrays.asList(item.getCatalogItemId()), date);
779
                priceDropController.getPriceCircularView(priceCircularModel, model);*/
31352 amit.gupta 780
                // Offer payout
781
                List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(loginDetails.getFofoId(),
782
                        searchImei);
783
                Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream()
33248 ranu 784
                        .map(x -> {
785
                            try {
786
                                return offerService.getOffer(loginDetails.getFofoId(), (int) x.getOfferId());
787
                            } catch (ProfitMandiBusinessException e) {
788
                                throw new RuntimeException(e);
789
                            }
790
                        })
31352 amit.gupta 791
                        .collect(Collectors.toMap(x -> x.getId(), x -> x));
29608 amit.gupta 792
 
31352 amit.gupta 793
                schemeInOuts = schemeInOutRepository
794
                        .selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
25256 amit.gupta 795
 
31352 amit.gupta 796
                if (!schemeInOuts.isEmpty()) {
797
                    netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED))
798
                            .collect(Collectors.summingDouble(x -> x.getAmount()));
799
                    List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId())
800
                            .collect(Collectors.toList());
23914 govind 801
 
31352 amit.gupta 802
                    schemes = schemeRepository.selectBySchemeIds(schemeIds);
803
                    for (Scheme scheme : schemes) {
804
                        if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
805
                            scheme.setAmountModel(scheme.getAmount() + "%");
806
                        } else {
807
                            scheme.setAmountModel(scheme.getAmount() + "");
808
                        }
809
                    }
23914 govind 810
 
31352 amit.gupta 811
                    schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
812
                }
32331 amit.gupta 813
                netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
814
 
31352 amit.gupta 815
                List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
816
                        .selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
817
                if (priceDropImeis.size() > 0) {
23914 govind 818
 
31352 amit.gupta 819
                    for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
820
                        int priceDropId = priceDropIMEI.getPriceDropId();
821
                        PriceDrop pd = priceDropRepository.selectById(priceDropId);
822
                        priceDropIMEI.setPriceDrop(pd);
823
                    }
824
                    model.addAttribute("priceDropImeis", priceDropImeis);
825
                }
32331 amit.gupta 826
 
31352 amit.gupta 827
                model.addAttribute("offerPayouts", offerPayouts);
828
                model.addAttribute("offerRequestMap", offerRequestMap);
829
                model.addAttribute("inventoryItem", inventoryItem);
23914 govind 830
 
31352 amit.gupta 831
            }
32331 amit.gupta 832
            model.addAttribute("netEarnings", netEarnings);
31352 amit.gupta 833
            model.addAttribute("schemeMap", schemeMap);
834
            model.addAttribute("item", item);
835
            model.addAttribute("schemeInOut", schemeInOuts);
836
        }
31170 amit.gupta 837
 
31352 amit.gupta 838
        if (isAdmin) {
34369 amit.gupta 839
            schemes = schemeRepository.selectAll(0, 300);
31352 amit.gupta 840
            this.setSchemeAmountModel(schemes);
841
            List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
842
            Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
843
            model.addAttribute("schemes", schemes);
844
            model.addAttribute("schemeRegionMap", schemeRegionMap);
31170 amit.gupta 845
 
31352 amit.gupta 846
            return "schemes";
847
        } else {
848
            FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
849
            model.addAttribute("partnerCode", fs.getCode());
850
            model.addAttribute("fofoId", fs.getId());
851
            return "schemes-partner";
852
        }
23914 govind 853
 
31352 amit.gupta 854
    }
23786 amit.gupta 855
 
31352 amit.gupta 856
    private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing) {
31505 amit.gupta 857
        /*if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
31352 amit.gupta 858
                .filter(x -> x.getId() == fofoId).count() > 0) {
859
            schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
860
                    .collect(Collectors.toList());
31505 amit.gupta 861
        }*/
31352 amit.gupta 862
        float nlc = tagListing.getSellingPrice();
863
        for (Scheme scheme : schemes) {
864
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
865
                if (tagListing != null) {
866
                    float amount = tagListing.getSellingPrice() * scheme.getAmount() / 100;
867
                    scheme.setAmountModel(FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
868
                    nlc -= amount;
869
                } else {
870
                    scheme.setAmountModel(scheme.getAmount() + "%");
871
                }
872
            } else {
873
                scheme.setAmountModel(scheme.getAmount() + "");
874
                nlc -= scheme.getAmount();
875
            }
876
        }
23819 govind 877
 
31352 amit.gupta 878
        return Math.round(nlc);
23914 govind 879
 
31352 amit.gupta 880
    }
29899 tejbeer 881
 
31352 amit.gupta 882
    @RequestMapping(value = "/getLastMonthCreditIncome", method = RequestMethod.GET)
883
    public String getLastMonthCreditIncome(HttpServletRequest request, Model model) throws Exception {
30122 amit.gupta 884
 
31352 amit.gupta 885
        String status = "CREDITED";
886
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23786 amit.gupta 887
 
31352 amit.gupta 888
        LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
889
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
31170 amit.gupta 890
 
31352 amit.gupta 891
        YearMonth yearMonth = YearMonth.now();
892
        LOGGER.info("yearMonth" + yearMonth);
31170 amit.gupta 893
 
31352 amit.gupta 894
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), yearMonth);
31170 amit.gupta 895
 
31352 amit.gupta 896
        LOGGER.info("partnerType" + partnerType);
31170 amit.gupta 897
 
31352 amit.gupta 898
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
31170 amit.gupta 899
 
31352 amit.gupta 900
        if (partnerType) {
901
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
902
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), currentStartMonth,
903
                            currentDate)
904
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
905
        }
906
        List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
907
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
31170 amit.gupta 908
 
31352 amit.gupta 909
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
910
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
31170 amit.gupta 911
 
31352 amit.gupta 912
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
913
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), currentStartMonth, currentDate);
26802 tejbeer 914
 
31352 amit.gupta 915
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = schemeInOutRepository
916
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate).stream()
917
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
28796 tejbeer 918
 
34409 amit.gupta 919
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
31352 amit.gupta 920
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
29608 amit.gupta 921
 
31352 amit.gupta 922
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
923
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30274 amit.gupta 924
 
31352 amit.gupta 925
        lastMonthFrontEndIncomes.stream().forEach(x -> {
926
            if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
927
                x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
928
                lastMonthSaleMarginMap.put(x.getBrand(), x);
929
            } else {
930
                lastMonthSaleMarginMap.put(x.getBrand(), x);
931
            }
30274 amit.gupta 932
 
31352 amit.gupta 933
        });
934
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
935
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
30274 amit.gupta 936
 
31352 amit.gupta 937
        Set<String> keySet = new HashSet<>();
938
        keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
939
        keySet.addAll(lastMonthSaleMarginMap.keySet());
940
        keySet.addAll(lastMonthPendingIncomeMap.keySet());
28795 tejbeer 941
 
31352 amit.gupta 942
        lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
943
            String brand = x.getKey();
944
            float amount = x.getValue().getAmount();
945
            if (!totalAmountMap.containsKey(brand)) {
946
                totalAmountMap.put(brand, 0f);
947
            }
948
            totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
30253 amit.gupta 949
 
31352 amit.gupta 950
        });
30122 amit.gupta 951
 
31352 amit.gupta 952
        lastMonthPendingIncomeMap.entrySet().stream().forEach(x -> {
953
            String brand = x.getKey();
954
            float amount = x.getValue().getAmount();
955
            if (!totalAmountMap.containsKey(brand)) {
956
                totalAmountMap.put(brand, 0f);
957
            }
958
            totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
28795 tejbeer 959
 
31352 amit.gupta 960
        });
28795 tejbeer 961
 
962
 
31352 amit.gupta 963
        Map<Integer, String> monthValueMap = new HashMap<>();
964
        for (int i = 0; i <= 5; i++) {
965
            LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
966
            monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
967
        }
968
        model.addAttribute("month", 0);
969
        model.addAttribute("monthValueMap", monthValueMap);
970
        model.addAttribute("keySet", keySet);
971
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
28795 tejbeer 972
 
31352 amit.gupta 973
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
974
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
975
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
976
        model.addAttribute("status", status);
977
        model.addAttribute("totalAmountMap", totalAmountMap);
28795 tejbeer 978
 
31352 amit.gupta 979
        return "last-month-credited-income";
980
    }
30651 amit.gupta 981
 
31352 amit.gupta 982
    @RequestMapping(value = "/getLastMonthPendingIncome", method = RequestMethod.GET)
983
    public String getLastMonthPendingIncome(HttpServletRequest request, Model model) throws Exception {
30651 amit.gupta 984
 
31352 amit.gupta 985
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
28795 tejbeer 986
 
31352 amit.gupta 987
        LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
988
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
989
        String status = "PENDING";
31170 amit.gupta 990
 
31352 amit.gupta 991
        LOGGER.info("currentStartMonth" + currentStartMonth);
992
        LOGGER.info("currentDate" + currentDate);
28795 tejbeer 993
 
31352 amit.gupta 994
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
995
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
29899 tejbeer 996
 
31352 amit.gupta 997
        Map<String, LastMonthCreditedIncomeModel> lastMonthMarginMap = new HashMap<>();
23786 amit.gupta 998
 
31352 amit.gupta 999
        for (LastMonthCreditedIncomeModel lastMonthPendingIncomeModel : lastMonthPendingIncomeModels) {
28795 tejbeer 1000
 
31352 amit.gupta 1001
            lastMonthMarginMap.put(lastMonthPendingIncomeModel.getBrand(), lastMonthPendingIncomeModel);
1002
        }
1003
        LOGGER.info("lastMonthPendingIncomeModel" + lastMonthPendingIncomeModels);
1004
        LOGGER.info("lastMonthMarginMap" + lastMonthMarginMap);
1005
        model.addAttribute("lastMonthCreditedIncomeModels", lastMonthPendingIncomeModels);
1006
        model.addAttribute("lastMonthMarginMap", lastMonthMarginMap);
1007
        model.addAttribute("status", status);
28795 tejbeer 1008
 
31352 amit.gupta 1009
        return "last-month-credited-income";
1010
    }
28795 tejbeer 1011
 
31352 amit.gupta 1012
    @RequestMapping(value = "/getLastMonthImeiWiseIncome", method = RequestMethod.GET)
1013
    public String getLastMonthImeiWiseIncome(HttpServletRequest request,
1014
                                             @RequestParam(name = "catalogItemId", required = false, defaultValue = "") int catalogItemId,
1015
                                             @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
1016
            throws Exception {
30053 manish 1017
 
31352 amit.gupta 1018
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 1019
 
31352 amit.gupta 1020
        LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1021
        LocalDateTime lastMonthEnd = lastMonthStart.plusMonths(1);
30053 manish 1022
 
31352 amit.gupta 1023
        HashSet<String> allImeiSet = new LinkedHashSet<>();
30053 manish 1024
 
31352 amit.gupta 1025
        List<LastMonthFrontEndImeiModel> lmfi = schemeInOutRepository
1026
                .selectLastMonthFrontEndImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart, lastMonthEnd);
1027
        List<LastMonthImeiModel> lmpi = schemeInOutRepository.selectLastMonthPurchaseInImei(loginDetails.getFofoId(),
1028
                catalogItemId, lastMonthStart, lastMonthEnd);
1029
        List<LastMonthImeiModel> lmci = schemeInOutRepository.selectLastMonthCreditedImei(loginDetails.getFofoId(),
1030
                catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 1031
 
31352 amit.gupta 1032
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(YearMonth.of(lastMonthStart.getYear(),
1033
                lastMonthStart.getMonth()), loginDetails.getFofoId(), null, catalogItemId);
30053 manish 1034
 
31352 amit.gupta 1035
        LOGGER.info("lmci {}", lmci);
30053 manish 1036
 
31352 amit.gupta 1037
        Map<String, Double> lastmonthCategoryUpgradeMargin = schemeInOutRepository
1038
                .selectLastMonthCategoryUpgradeMarginByImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart,
1039
                        lastMonthEnd)
1040
                .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
30053 manish 1041
 
31352 amit.gupta 1042
        allImeiSet.addAll(lmpi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
1043
        allImeiSet.addAll(lmci.stream().map(x -> x.getImei()).collect(Collectors.toList()));
1044
        allImeiSet.addAll(lmfi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
1045
        allImeiSet.addAll(offerPayoutImeiIncomeModels.stream().map(x -> x.getImei()).collect(Collectors.toList()));
30053 manish 1046
 
31352 amit.gupta 1047
        List<String> allImeiList = new ArrayList<>(allImeiSet);
30053 manish 1048
 
31352 amit.gupta 1049
        LOGGER.info("allImeiList" + allImeiList);
1050
        LOGGER.info("lmcm" + lastmonthCategoryUpgradeMargin);
30253 amit.gupta 1051
 
31352 amit.gupta 1052
        List<LastMonthFrontEndImeiModel> lastMonthFrontEndImeis = schemeInOutRepository
1053
                .selectLastMonthFrontEndByImei(loginDetails.getFofoId(), allImeiList);
31379 amit.gupta 1054
        Map<String, LastMonthFrontEndImeiModel> soldMap = lastMonthFrontEndImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x));
30053 manish 1055
 
31379 amit.gupta 1056
 
31352 amit.gupta 1057
        List<LastMonthImeiModel> lastMonthPurchaseInImeis = schemeInOutRepository
1058
                .selectLastMonthPurchaseInByImei(loginDetails.getFofoId(), allImeiList);
30053 manish 1059
 
31352 amit.gupta 1060
        List<LastMonthImeiModel> lastMonthCreditedImeis = schemeInOutRepository
1061
                .selectLastMonthCreditedByImei(loginDetails.getFofoId(), allImeiList);
1062
        List<OfferPayoutImeiIncomeModel> allOfferPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByImei(allImeiList);
30053 manish 1063
 
31352 amit.gupta 1064
        //Map<String, OfferPayoutImeiIncomeModel> imeisOfferPayoutMap = allOfferPayoutImeiIncomeModels.stream().collect(Collectors.toMap(x->x.getImei(), x->x));
1065
        Map<String, Double> imeiWisePendingSaleAmount = lastMonthCreditedImeis.stream()
1066
                .filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).collect(Collectors
1067
                        .groupingBy(x -> x.getImei(), Collectors.summingDouble(x -> x.getPendingSaleAmount())));
30053 manish 1068
 
31352 amit.gupta 1069
        allOfferPayoutImeiIncomeModels.stream().forEach(x -> {
1070
            if (x.getSaleDate() != null) {
1071
                LastMonthImeiModel lastMonthImeiModel = new LastMonthImeiModel(x.getImei(), (float) x.getSalePayout(),
1072
                        0, "Addnl Margin", x.getSaleDate(), SchemePayoutStatus.CREDITED);
1073
                lastMonthCreditedImeis.add(lastMonthImeiModel);
1074
            }
1075
            if (x.getGrnDate() != null) {
1076
                LastMonthImeiModel lastMonthImeiModel = new LastMonthImeiModel(x.getImei(), (float) x.getPurchasePayout(),
1077
                        0, "Booster Payout", x.getGrnDate(), SchemePayoutStatus.CREDITED);
1078
                lastMonthPurchaseInImeis.add(lastMonthImeiModel);
1079
            }
1080
        });
30053 manish 1081
 
31352 amit.gupta 1082
        Map<String, Map<String, Double>> lastMonthPurchaseInMapPairMap = lastMonthPurchaseInImeis.stream()
1083
                .collect(Collectors.groupingBy(x -> x.getImei(),
1084
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
1085
        Map<String, LocalDate> imeiPurchaseDateMap = lastMonthPurchaseInImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x.getCreateTimeStamp().toLocalDate(), (x, y) -> x));
32236 amit.gupta 1086
        LOGGER.info("Last month front end imeis - {}", lastMonthFrontEndImeis);
32232 amit.gupta 1087
        Map<String, LocalDate> imeiSaleDateMap = lastMonthFrontEndImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x.getCreated()));
31352 amit.gupta 1088
        Map<String, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
1089
                .collect(Collectors.groupingBy(x -> x.getImei(),
1090
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
30053 manish 1091
 
31352 amit.gupta 1092
        // descriptionSet.add("")
30053 manish 1093
 
34409 amit.gupta 1094
        List<String> purchaseList = lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).distinct().collect(Collectors.toList());
1095
        List<String> saleList = lastMonthCreditedImeis.stream().map(x -> x.getDescription()).distinct().collect(Collectors.toList());
30253 amit.gupta 1096
 
31352 amit.gupta 1097
        Map<String, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
30053 manish 1098
 
31352 amit.gupta 1099
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
30235 tejbeer 1100
 
31352 amit.gupta 1101
            String imei = entry.getKey();
1102
            ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imei,
1103
                    imeiPurchaseDateMap.get(imei), null);
1104
            imeiWiseIncomeMapOfMap.put(imei, modelImeiMap);
1105
            double totalAmount = entry.getValue().entrySet().stream()
1106
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1107
            imeiWiseIncomeMapOfMap.get(imei).setTotalIncome(totalAmount);
1108
        }
31283 amit.gupta 1109
 
31352 amit.gupta 1110
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
1111
            Map<String, Double> descriptionAmountMap = entry.getValue();
1112
            if (!imeiWiseIncomeMapOfMap.containsKey(entry.getKey())) {
32232 amit.gupta 1113
                imeiWiseIncomeMapOfMap.put(entry.getKey(), new ImeiWiseIncomePairAndMapModel(entry.getKey(), null, null));
31352 amit.gupta 1114
            }
32232 amit.gupta 1115
            ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(entry.getKey());
1116
            ;
1117
            modelImeiMap.setSaleDate(imeiSaleDateMap.get(entry.getKey()));
30053 manish 1118
 
31352 amit.gupta 1119
            double totalAmount = descriptionAmountMap.entrySet().stream()
1120
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1121
            imeiWiseIncomeMapOfMap.get(entry.getKey())
1122
                    .setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(entry.getKey()).getTotalIncome());
1123
        }
30053 manish 1124
 
31352 amit.gupta 1125
        //Imeis for pending activation
1126
        lastMonthCreditedImeis.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).forEach(x -> {
1127
            if (!imeiWiseIncomeMapOfMap.containsKey(x.getImei())) {
32232 amit.gupta 1128
                imeiWiseIncomeMapOfMap.put(x.getImei(), new ImeiWiseIncomePairAndMapModel(x.getImei()));
31352 amit.gupta 1129
            }
1130
            ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1131
                    .get(x.getImei());
1132
            imeiWiseIncomePairAndMapModel.setSaleDate(x.getCreateTimeStamp().toLocalDate());
1133
            imeiWiseIncomePairAndMapModel.setTotalIncome(x.getPendingSaleAmount() + imeiWiseIncomePairAndMapModel.getTotalIncome());
1134
        });
30053 manish 1135
 
31379 amit.gupta 1136
        lastMonthFrontEndImeis.stream().forEach(lastMonthFrontEndImeiModel -> {
32232 amit.gupta 1137
            if (!imeiWiseIncomeMapOfMap.containsKey(lastMonthFrontEndImeiModel.getImei())) {
1138
                imeiWiseIncomeMapOfMap.put(lastMonthFrontEndImeiModel.getImei(), new ImeiWiseIncomePairAndMapModel(lastMonthFrontEndImeiModel.getImei()));
31379 amit.gupta 1139
            }
32232 amit.gupta 1140
            ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1141
                    .get(lastMonthFrontEndImeiModel.getImei());
1142
            lastMonthFrontEndImeiModel.setNlc(lastMonthFrontEndImeiModel.getDp()
1143
                    - (float) imeiWiseIncomeMapOfMap.get(lastMonthFrontEndImeiModel.getImei()).getTotalIncome());
1144
            lastMonthFrontEndImeiModel.setNetIncome(lastMonthFrontEndImeiModel.getSellingPrice() - lastMonthFrontEndImeiModel.getNlc());
1145
            imeiWiseIncomePairAndMapModel.setSaleDate(lastMonthFrontEndImeiModel.getCreated());
31379 amit.gupta 1146
        });
1147
 
31352 amit.gupta 1148
        model.addAttribute("imeiWisePendingSaleAmount", imeiWisePendingSaleAmount);
1149
        model.addAttribute("month", month);
1150
        model.addAttribute("purchaseList", purchaseList);
1151
        model.addAttribute("saleList", saleList);
1152
        model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1153
        model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1154
        model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1155
        model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
31379 amit.gupta 1156
        model.addAttribute("soldMap", soldMap);
31352 amit.gupta 1157
        model.addAttribute("allOfferPayoutImeiIncomeModels", allOfferPayoutImeiIncomeModels);
1158
        //model.addAttribute("iimeiSaleDateMap", imeiSaleDateMap);
1159
        //model.addAttribute("imeiPurchaseDateMap", imeiPurchaseDateMap);
30053 manish 1160
 
31352 amit.gupta 1161
        return "last-month-imei-wise-income";
1162
    }
30053 manish 1163
 
31352 amit.gupta 1164
    @RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1165
    public String getBrandWiseIncome(HttpServletRequest request,
1166
                                     @RequestParam(name = "brand", required = false, defaultValue = "") String brand,
32232 amit.gupta 1167
                                     @RequestParam(name = "month", required = false, defaultValue = "") int month,
1168
                                     Model model)
31352 amit.gupta 1169
            throws ProfitMandiBusinessException {
1170
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1171
        LOGGER.info("loginDetails {}", loginDetails);
1172
        LOGGER.info("brand" + brand);
1173
        LOGGER.info("month {}", month);
30053 manish 1174
 
31352 amit.gupta 1175
        LocalDateTime monthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1176
        LocalDateTime monthEnd = monthStart.plusMonths(1);
30053 manish 1177
 
31352 amit.gupta 1178
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1179
                YearMonth.of(monthStart.getYear(), monthStart.getMonth()), loginDetails.getFofoId(), brand, null);
32232 amit.gupta 1180
        LOGGER.info("offerPayoutImeiIncomeModels - {}", offerPayoutImeiIncomeModels);
1181
        Map<Integer, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().filter(x -> x.getPurchasePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getPurchasePayout())));
1182
        Map<Integer, Integer> additionalPurchaseQty = offerPayoutImeiIncomeModels.stream().filter(x -> x.getPurchasePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingInt(x -> 1)));
1183
        Map<Integer, Double> additionalSalePayoutMap = offerPayoutImeiIncomeModels.stream().filter(x -> x.getSalePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getSalePayout())));
1184
        Map<Integer, Integer> additionalSaleQty = offerPayoutImeiIncomeModels.stream().filter(x -> x.getSalePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingInt(x -> 1)));
30053 manish 1185
 
32232 amit.gupta 1186
        Set<Integer> allCatalogIds = offerPayoutImeiIncomeModels.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
31352 amit.gupta 1187
        boolean partnerTypeUpgraded = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(),
1188
                YearMonth.now());
30053 manish 1189
 
31352 amit.gupta 1190
        LOGGER.info("partnerType" + partnerTypeUpgraded);
30053 manish 1191
 
31352 amit.gupta 1192
        Map<String, Double> categoryUpgradeBrandModelMap = null;
1193
        if (partnerTypeUpgraded) {
1194
            categoryUpgradeBrandModelMap = schemeInOutRepository
1195
                    .selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, monthStart,
1196
                            monthEnd)
1197
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1198
        }
30053 manish 1199
 
31352 amit.gupta 1200
        List<LastMonthFrontEndBrandWiseIncome> modelWiseSalesMargins = schemeInOutRepository
1201
                .selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand, monthStart, monthEnd);
32232 amit.gupta 1202
        Map<Integer, LastMonthFrontEndBrandWiseIncome> modelWiseSalesMarginsMap = modelWiseSalesMargins.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1203
 
32232 amit.gupta 1204
 
31352 amit.gupta 1205
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMargins = schemeInOutRepository
1206
                .selectLastMonthBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1207
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMarginsMap = modelWiseSchemeOutMargins.stream()
1208
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1209
 
31352 amit.gupta 1210
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeInMargins = schemeInOutRepository
1211
                .selectLastMonthPurchaseBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1212
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeInMarginsMap = modelWiseSchemeInMargins.stream()
1213
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1214
 
32232 amit.gupta 1215
        allCatalogIds.addAll(modelWiseSalesMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
1216
        allCatalogIds.addAll(modelWiseSchemeInMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
1217
        allCatalogIds.addAll(modelWiseSchemeOutMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
30053 manish 1218
 
32232 amit.gupta 1219
        Map<Integer, String> modelNameMap = itemRepository.selectAllByCatalogIds(allCatalogIds).stream().collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x.getModel(), (u, v) -> u));
1220
        Map<Integer, Double> modelIncomeMap = new HashMap<>();
1221
        Map<Integer, Integer> modelPurchaseQtyMap = new HashMap<>();
1222
        Map<Integer, Integer> modelSaleQtyMap = new HashMap<>();
1223
        for (int catalogItemId : modelNameMap.keySet()) {
1224
            int saleQty = 0;
1225
            int purchaseQty = 0;
1226
            double income = 0;
30253 amit.gupta 1227
 
32232 amit.gupta 1228
            if (modelWiseSchemeInMarginsMap.containsKey(catalogItemId)) {
1229
                income += modelWiseSchemeInMarginsMap.get(catalogItemId).getAmount() + modelWiseSchemeInMarginsMap.get(catalogItemId).getPendingSaleAmount();
1230
                purchaseQty += modelWiseSchemeInMarginsMap.get(catalogItemId).getQty();
31352 amit.gupta 1231
            }
32232 amit.gupta 1232
            if (modelWiseSchemeOutMarginsMap.containsKey(catalogItemId)) {
1233
                income += modelWiseSchemeOutMarginsMap.get(catalogItemId).getAmount() + modelWiseSchemeOutMarginsMap.get(catalogItemId).getPendingSaleAmount();
31352 amit.gupta 1234
            }
32232 amit.gupta 1235
            if (additionalSalePayoutMap.containsKey(catalogItemId)) {
1236
                income += additionalSalePayoutMap.get(catalogItemId);
31352 amit.gupta 1237
            }
32232 amit.gupta 1238
            if (additionalPurchasePayout.containsKey(catalogItemId)) {
1239
                income += additionalPurchasePayout.get(catalogItemId);
1240
            }
1241
            if (modelWiseSalesMarginsMap.containsKey(catalogItemId)) {
1242
                income += modelWiseSalesMarginsMap.get(catalogItemId).getAmount();
1243
                saleQty = (int) modelWiseSalesMarginsMap.get(catalogItemId).getQty();
1244
            }
1245
            if (additionalPurchaseQty.containsKey(catalogItemId)) {
1246
                purchaseQty = Math.max(additionalPurchaseQty.get(catalogItemId), purchaseQty);
30253 amit.gupta 1247
 
31352 amit.gupta 1248
            }
32232 amit.gupta 1249
            modelIncomeMap.put(catalogItemId, income);
1250
            modelSaleQtyMap.put(catalogItemId, saleQty);
1251
            modelPurchaseQtyMap.put(catalogItemId, purchaseQty);
30253 amit.gupta 1252
 
32232 amit.gupta 1253
        }
30253 amit.gupta 1254
 
31352 amit.gupta 1255
        model.addAttribute("month", month);
32232 amit.gupta 1256
        model.addAttribute("modelWiseSalesMarginsMap", modelWiseSalesMarginsMap);
31352 amit.gupta 1257
        model.addAttribute("modelWiseSchemeOutMarginsMap", modelWiseSchemeOutMarginsMap);
1258
        model.addAttribute("modelWiseSchemeInMarginsMap", modelWiseSchemeInMarginsMap);
1259
        model.addAttribute("modelNameMap", modelNameMap);
32232 amit.gupta 1260
        model.addAttribute("modelPurchaseQtyMap", modelPurchaseQtyMap);
1261
        model.addAttribute("modelSaleQtyMap", modelSaleQtyMap);
1262
        model.addAttribute("modelIncomeMap", modelIncomeMap);
31352 amit.gupta 1263
        model.addAttribute("categoryUpgradeBrandModelMap", categoryUpgradeBrandModelMap);
1264
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
32232 amit.gupta 1265
        model.addAttribute("additionalSalePayoutMap", additionalSalePayoutMap);
30253 amit.gupta 1266
 
31352 amit.gupta 1267
        return "monthly-brand-wise-income";
30053 manish 1268
 
31352 amit.gupta 1269
    }
30053 manish 1270
 
31352 amit.gupta 1271
    @RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
1272
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
1273
            throws ProfitMandiBusinessException {
1274
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30253 amit.gupta 1275
 
31352 amit.gupta 1276
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1277
        LocalDateTime lastMonthEnd = startOfMonth.plusMonths(1);
30253 amit.gupta 1278
 
31352 amit.gupta 1279
        YearMonth monthYear = YearMonth.now();
30053 manish 1280
 
31352 amit.gupta 1281
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
30053 manish 1282
 
31352 amit.gupta 1283
        LOGGER.info("partnerType" + partnerType);
30053 manish 1284
 
31352 amit.gupta 1285
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
30053 manish 1286
 
31352 amit.gupta 1287
        if (partnerType) {
1288
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1289
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), startOfMonth,
1290
                            lastMonthEnd)
1291
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1292
        }
30053 manish 1293
 
31352 amit.gupta 1294
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1295
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30053 manish 1296
 
31352 amit.gupta 1297
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1298
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1299
 
31352 amit.gupta 1300
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1301
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
32232 amit.gupta 1302
        Map<String, LastMonthCreditedIncomeModel> lastMonthFrontEndIncomeMap = lastMonthFrontEndIncomes.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30235 tejbeer 1303
 
31352 amit.gupta 1304
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1305
                YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()), loginDetails.getFofoId(), null, null);
30235 tejbeer 1306
 
31352 amit.gupta 1307
        Map<String, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getPurchasePayout)));
1308
        Map<String, Double> additionSalePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getSalePayout)));
30235 tejbeer 1309
 
1310
 
31352 amit.gupta 1311
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
1312
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1313
 
34409 amit.gupta 1314
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = schemeInOutRepository
1315
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd).stream()
31352 amit.gupta 1316
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1317
 
1318
 
31352 amit.gupta 1319
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = lastMonthPendingIncomeModels.stream()
1320
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1321
 
31352 amit.gupta 1322
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1323
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1324
        Set<String> brandSet = new HashSet<>();
1325
        brandSet.addAll(lastMonthPurchaseInMarginMap.keySet());
1326
        brandSet.addAll(lastMonthSaleMarginMap.keySet());
1327
        brandSet.addAll(lastMonthPendingIncomeMap.keySet());
1328
        brandSet.addAll(additionalPurchasePayout.keySet());
1329
        brandSet.addAll(additionSalePayout.keySet());
33313 amit.gupta 1330
        brandSet.addAll(lastMonthFrontEndIncomeMap.keySet());
31352 amit.gupta 1331
        brandSet.stream().forEach(brand -> {
1332
            totalAmountMap.put(brand,
1333
                    (lastMonthSaleMarginMap.get(brand) == null ? 0 : lastMonthSaleMarginMap.get(brand).getAmount()) +
1334
                            (lastMonthPurchaseInMarginMap.get(brand) == null ? 0 : lastMonthPurchaseInMarginMap.get(brand).getAmount()) +
1335
                            (lastMonthPendingIncomeMap.get(brand) == null ? 0 : lastMonthPendingIncomeMap.get(brand).getAmount()) +
1336
                            (additionalPurchasePayout.get(brand) == null ? 0 : additionalPurchasePayout.get(brand).longValue()) +
32232 amit.gupta 1337
                            (additionSalePayout.get(brand) == null ? 0 : additionSalePayout.get(brand).longValue()) +
1338
                            (lastMonthFrontEndIncomeMap.get(brand) == null ? 0 : lastMonthFrontEndIncomeMap.get(brand).getAmount())
31352 amit.gupta 1339
            );
1340
        });
30053 manish 1341
 
31352 amit.gupta 1342
        Map<Integer, String> monthValueMap = new HashMap<>();
1343
        for (int i = 0; i <= 5; i++) {
1344
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1345
            monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
1346
        }
1347
        model.addAttribute("monthValueMap", monthValueMap);
30053 manish 1348
 
32232 amit.gupta 1349
        model.addAttribute("brandSet", brandSet);
31352 amit.gupta 1350
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1351
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1352
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
1353
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
1354
        model.addAttribute("additionalSalePayoutMap", additionSalePayout);
32232 amit.gupta 1355
        model.addAttribute("lastMonthFrontEndIncomeMap", lastMonthFrontEndIncomeMap);
30053 manish 1356
 
31352 amit.gupta 1357
        model.addAttribute("totalAmountMap", totalAmountMap);
1358
        model.addAttribute("month", yearMonth);
1359
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1360
        LOGGER.info("totalAmountMap {}", totalAmountMap);
1361
        LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
30253 amit.gupta 1362
 
31352 amit.gupta 1363
        return "last-month-credited-income";
1364
    }
30253 amit.gupta 1365
 
31352 amit.gupta 1366
    @RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
1367
    public String downloadPage(HttpServletRequest request, Model model) {
1368
        return "schemes-download";
1369
    }
30253 amit.gupta 1370
 
31352 amit.gupta 1371
    @RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
1372
    public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
1373
                                                                  @RequestParam LocalDateTime startDateTime, @RequestParam LocalDateTime endDateTime)
1374
            throws ProfitMandiBusinessException {
30253 amit.gupta 1375
 
31352 amit.gupta 1376
        List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
31334 amit.gupta 1377
 
31352 amit.gupta 1378
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1379
        ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
30253 amit.gupta 1380
 
31352 amit.gupta 1381
        final HttpHeaders headers = new HttpHeaders();
1382
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
1383
        headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
1384
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1385
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1386
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1387
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1388
    }
30053 manish 1389
 
31352 amit.gupta 1390
    @RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
1391
    public String getSchemeById(HttpServletRequest request,
1392
                                @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
1393
            throws ProfitMandiBusinessException {
1394
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 1395
 
31352 amit.gupta 1396
        boolean fullAccess = this.getAccess(loginDetails.getEmailId());
1397
        Scheme scheme = schemeService.getSchemeById(schemeId);
1398
        model.addAttribute("fullAccess", fullAccess);
1399
        model.addAttribute("scheme", scheme);
1400
        model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
1401
        return "scheme-details";
1402
    }
30053 manish 1403
 
31352 amit.gupta 1404
    @RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
1405
    public String activeSchemeById(@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1406
                                   @RequestParam(name = "offset", defaultValue = "0") int offset,
1407
                                   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1408
            throws ProfitMandiBusinessException {
1409
        schemeService.activeSchemeById(schemeId);
1410
        List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
1411
        for (Scheme scheme : schemes) {
1412
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1413
                scheme.setAmountModel(scheme.getAmount() + "%");
1414
            } else {
1415
                scheme.setAmountModel(scheme.getAmount() + "");
1416
            }
1417
        }
1418
        return "schemes";
1419
    }
30053 manish 1420
 
34568 vikas.jang 1421
    @RequestMapping(value = "/activeSchemeByIds", method = RequestMethod.PUT)
34575 vikas.jang 1422
    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 1423
        List<Integer> ids = Arrays.stream(schemeIds.split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(Integer::parseInt).collect(Collectors.toList());
1424
        List<Scheme> schemes = schemeRepository.selectBySchemeIds(ids);
1425
        schemeService.activeSchemeByIds(schemes);
1426
        List<Scheme> allSchemes = schemeRepository.selectAll(offset, limit);
1427
        for (Scheme scheme : allSchemes) {
1428
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1429
                scheme.setAmountModel(scheme.getAmount() + "%");
1430
            } else {
1431
                scheme.setAmountModel(scheme.getAmount() + "");
1432
            }
1433
        }
34575 vikas.jang 1434
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1435
        return "response";
34568 vikas.jang 1436
    }
1437
 
31352 amit.gupta 1438
    @RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
1439
    public String expireSchemeById(HttpServletRequest request,
1440
                                   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1441
                                   @RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp, Model model)
1442
            throws ProfitMandiBusinessException {
1443
        schemeService.expireSchemeById(schemeId, expiryTimestamp);
1444
        return getDefaultSchemes(request, model);
1445
    }
30053 manish 1446
 
31352 amit.gupta 1447
    @RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
1448
    public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
1449
                                            @RequestParam(name = "offset", defaultValue = "0") int offset,
1450
                                            @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1451
            throws ProfitMandiBusinessException {
1452
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1453
        return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1454
    }
30053 manish 1455
 
31352 amit.gupta 1456
    @RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1457
    public String getCustomerOffer(HttpServletRequest request,
33795 ranu 1458
                                   @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 1459
            throws ProfitMandiBusinessException {
1460
        List<CustomerOffer> customerOffers = null;
1461
        if (searchModel > 0) {
30053 manish 1462
 
31352 amit.gupta 1463
            Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
1464
            customerOffers = customerOfferRepository.selectActiveOfferByModel(searchModel, LocalDate.now());
1465
            model.addAttribute("modelName", item.getItemDescriptionNoColor());
33795 ranu 1466
        } else if (startDate != null && endDate != null) {
1467
            customerOffers = customerOfferRepository.selectOffersByDates(startDate, endDate);
31352 amit.gupta 1468
        } else {
33795 ranu 1469
            if (startDate == null) {
1470
                startDate = LocalDateTime.now().minusMonths(1);  // One month ago from today
1471
            }
1472
            if (endDate == null) {
1473
                endDate = LocalDateTime.now();  // Current date and time
1474
            }
1475
            customerOffers = customerOfferRepository.selectOffersByDates(startDate, endDate);
31352 amit.gupta 1476
        }
30053 manish 1477
 
31352 amit.gupta 1478
        LOGGER.info("customerOffers" + customerOffers);
30053 manish 1479
 
31352 amit.gupta 1480
        for (CustomerOffer customerOffer : customerOffers) {
30053 manish 1481
 
31352 amit.gupta 1482
            LOGGER.info("ss" + searchModel);
30053 manish 1483
 
31352 amit.gupta 1484
            if (!StringUtils.isEmpty(customerOffer.getPartnerCriteria())) {
33030 amit.gupta 1485
                String partnerCriteria = offerService.getPartnerCriteriaString(gson.fromJson(customerOffer.getPartnerCriteria(), PartnerCriteria.class));
31352 amit.gupta 1486
                customerOffer.setPartnerCriteriaString(partnerCriteria);
1487
            }
30053 manish 1488
 
31352 amit.gupta 1489
        }
30053 manish 1490
 
31352 amit.gupta 1491
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1492
                .collect(Collectors.toList());
31281 amit.gupta 1493
 
31352 amit.gupta 1494
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30053 manish 1495
 
31352 amit.gupta 1496
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1497
                .filter(x -> x != null).collect(Collectors.toList()).stream()
1498
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30053 manish 1499
 
31352 amit.gupta 1500
        model.addAttribute("customRetailersMap", customRetailersMap);
1501
        model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
1502
        model.addAttribute("searchModel", searchModel);
30053 manish 1503
 
31352 amit.gupta 1504
        model.addAttribute("customerOffers", customerOffers);
1505
        return "customer-offer";
30053 manish 1506
 
31352 amit.gupta 1507
    }
30053 manish 1508
 
31352 amit.gupta 1509
    @RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1510
    public String createCustomerOffer(HttpServletRequest request, @RequestBody CustomerOfferModel customerOfferModel,
1511
                                      Model model) throws Exception {
30053 manish 1512
 
31352 amit.gupta 1513
        CustomerOffer co = new CustomerOffer();
1514
        co.setOfferName(customerOfferModel.getOfferName());
1515
        co.setStartDate(customerOfferModel.getStartDate());
1516
        co.setEndDate(customerOfferModel.getEndDate());
1517
        co.setPartnerCriteria(gson.toJson(customerOfferModel.getPartnerCriteria()));
1518
        co.setCreatedTimestamp(LocalDateTime.now());
1519
        co.setUpdatedTimestamp(LocalDateTime.now());
1520
        customerOfferRepository.persist(co);
31281 amit.gupta 1521
 
31352 amit.gupta 1522
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31281 amit.gupta 1523
 
31352 amit.gupta 1524
        return "response";
30053 manish 1525
 
31352 amit.gupta 1526
    }
30053 manish 1527
 
31352 amit.gupta 1528
    @RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1529
    public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1530
        List<List<?>> rows = new ArrayList<>();
30053 manish 1531
 
31352 amit.gupta 1532
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("id",
33795 ranu 1533
                        "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date (dd-mm-yyyy)", "End Date (dd-mm-yyyy)", "Offer Type"),
31352 amit.gupta 1534
                rows);
30053 manish 1535
 
31352 amit.gupta 1536
        final HttpHeaders headers = new HttpHeaders();
1537
        headers.set("Content-Type", "text/csv");
1538
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1539
        headers.setContentLength(baos.toByteArray().length);
30053 manish 1540
 
31352 amit.gupta 1541
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1542
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1543
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
30053 manish 1544
 
31352 amit.gupta 1545
    }
30053 manish 1546
 
31352 amit.gupta 1547
    @RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1548
    public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
1549
                                          HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
23786 amit.gupta 1550
 
31352 amit.gupta 1551
        List<CSVRecord> records = FileUtil.readFile(file);
1552
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
23914 govind 1553
 
31352 amit.gupta 1554
        CustomerOffer customerOffer = customerOfferRepository.selectById(offerId);
1555
        List<Integer> catalogIds = new ArrayList<>();
1556
        for (CSVRecord record : records) {
23786 amit.gupta 1557
 
31352 amit.gupta 1558
            CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
23786 amit.gupta 1559
 
31352 amit.gupta 1560
            if (coi == null) {
1561
                coi = new CustomerOfferItem();
1562
                coi.setCatalogId(Integer.parseInt(record.get(1)));
1563
                coi.setSchemePayout(Integer.parseInt(record.get(2)));
1564
                coi.setDealerPayout(Integer.parseInt(record.get(3)));
33795 ranu 1565
                coi.setOfferType(OfferType.valueOf(record.get(6)));
31352 amit.gupta 1566
                coi.setCustomerOfferId(offerId);
34516 ranu 1567
                coi.setAdditionalInfo(String.valueOf(record.get(7)));
31352 amit.gupta 1568
                coi.setCreatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1569
 
31352 amit.gupta 1570
                customerOfferItemRepository.persist(coi);
29899 tejbeer 1571
 
31352 amit.gupta 1572
            }
1573
            coi.setSchemePayout(Integer.parseInt(record.get(2)));
1574
            coi.setDealerPayout(Integer.parseInt(record.get(3)));
33795 ranu 1575
            coi.setOfferType(OfferType.valueOf(record.get(6)));
34516 ranu 1576
            coi.setAdditionalInfo(String.valueOf(record.get(7)));
31352 amit.gupta 1577
            coi.setCustomerOfferId(offerId);
1578
            coi.setUpdatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1579
 
31352 amit.gupta 1580
            LOGGER.info(record.get(4));
23786 amit.gupta 1581
 
31352 amit.gupta 1582
            LocalDate startDate = LocalDate.parse(record.get(4), formatter);
1583
            LocalDate endDate = LocalDate.parse(record.get(5), formatter);
23786 amit.gupta 1584
 
31352 amit.gupta 1585
            if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1586
                    || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1587
                    && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1588
                    || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1589
                coi.setStartDate(startDate);
26802 tejbeer 1590
 
31352 amit.gupta 1591
            } else {
29707 tejbeer 1592
 
31352 amit.gupta 1593
                catalogIds.add(coi.getCatalogId());
1594
            }
29707 tejbeer 1595
 
31352 amit.gupta 1596
            if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1597
                    || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1598
                    && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1599
                    || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1600
 
31352 amit.gupta 1601
                coi.setEndDate(endDate);
31147 tejbeer 1602
 
31352 amit.gupta 1603
            } else {
1604
                catalogIds.add(coi.getCatalogId());
1605
            }
31147 tejbeer 1606
 
31352 amit.gupta 1607
        }
31147 tejbeer 1608
 
31352 amit.gupta 1609
        if (!catalogIds.isEmpty()) {
1610
            throw new ProfitMandiBusinessException("Please set accurate start and end date", catalogIds,
1611
                    "Please set accurate start and end date");
1612
        }
1613
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1614
 
31352 amit.gupta 1615
        return "response";
31147 tejbeer 1616
 
31352 amit.gupta 1617
    }
31147 tejbeer 1618
 
31352 amit.gupta 1619
    @RequestMapping(value = "/addCustomerOfferItem", method = RequestMethod.POST)
1620
    public String addCustomerOfferItem(HttpServletRequest request,
1621
                                       @RequestBody CustomerOfferItemModel customerOfferItemModel, Model model) throws Throwable {
31147 tejbeer 1622
 
31352 amit.gupta 1623
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItemModel.getOfferId());
31147 tejbeer 1624
 
31352 amit.gupta 1625
        if (!(customerOffer.getEndDate().toLocalDate().equals(LocalDate.now()))
1626
                && customerOffer.getEndDate().isBefore(LocalDateTime.now())) {
1627
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(), "Offer is Expired");
29707 tejbeer 1628
 
31352 amit.gupta 1629
        }
29707 tejbeer 1630
 
31352 amit.gupta 1631
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
1632
                .selectByOfferAndCatalogId(customerOfferItemModel.getOfferId(), customerOfferItemModel.getCatalogId());
29707 tejbeer 1633
 
31352 amit.gupta 1634
        if (!customerOfferItems.isEmpty()) {
29707 tejbeer 1635
 
31352 amit.gupta 1636
            for (CustomerOfferItem coi : customerOfferItems) {
1637
                if (!(coi.getEndDate().equals(LocalDate.now())) && coi.getEndDate().isAfter(LocalDate.now())) {
1638
                    throw new ProfitMandiBusinessException("Catalog Id", coi.getCatalogId(), "Item is already exist.");
1639
                }
1640
            }
29707 tejbeer 1641
 
31352 amit.gupta 1642
        }
29707 tejbeer 1643
 
31352 amit.gupta 1644
        LocalDate startDate = customerOfferItemModel.getStartDate().toLocalDate();
1645
        LocalDate endDate = customerOfferItemModel.getEndDate().toLocalDate();
1646
        CustomerOfferItem coi = new CustomerOfferItem();
1647
        coi.setCatalogId(customerOfferItemModel.getCatalogId());
1648
        coi.setSchemePayout(customerOfferItemModel.getSchemePayout());
34516 ranu 1649
        coi.setAdditionalInfo(customerOfferItemModel.getAdditionalInfo());
31352 amit.gupta 1650
        coi.setDealerPayout(customerOfferItemModel.getDealerPayout());
33795 ranu 1651
        coi.setOfferType(customerOfferItemModel.getOfferType());
31352 amit.gupta 1652
        coi.setCustomerOfferId(customerOfferItemModel.getOfferId());
1653
        coi.setUpdatedTimestamp(LocalDateTime.now());
1654
        coi.setCreatedTimestamp(LocalDateTime.now());
29707 tejbeer 1655
 
31352 amit.gupta 1656
        if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1657
                || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1658
                && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1659
                || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 1660
 
31352 amit.gupta 1661
            coi.setStartDate(startDate);
29707 tejbeer 1662
 
31352 amit.gupta 1663
        } else {
29707 tejbeer 1664
 
31352 amit.gupta 1665
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1666
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1667
                            + customerOffer.getEndDate());
29707 tejbeer 1668
 
31352 amit.gupta 1669
        }
29707 tejbeer 1670
 
31352 amit.gupta 1671
        if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1672
                || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1673
                && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1674
                || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 1675
 
31352 amit.gupta 1676
            coi.setEndDate(endDate);
29707 tejbeer 1677
 
31352 amit.gupta 1678
        } else {
1679
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1680
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1681
                            + customerOffer.getEndDate());
1682
        }
31147 tejbeer 1683
 
31352 amit.gupta 1684
        customerOfferItemRepository.persist(coi);
31147 tejbeer 1685
 
31352 amit.gupta 1686
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1687
 
31352 amit.gupta 1688
        return "response";
29707 tejbeer 1689
 
31352 amit.gupta 1690
    }
31147 tejbeer 1691
 
31352 amit.gupta 1692
    @RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1693
    public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
31147 tejbeer 1694
 
31352 amit.gupta 1695
        List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1696
        List<List<?>> rows = new ArrayList<>();
1697
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
31147 tejbeer 1698
 
31352 amit.gupta 1699
        for (CustomerOfferItem coi : cois) {
1700
            rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout(),
34516 ranu 1701
                    coi.getStartDate().format(formatter), coi.getEndDate().format(formatter), coi.getOfferType(), coi.getAdditionalInfo()));
31147 tejbeer 1702
 
31352 amit.gupta 1703
        }
31147 tejbeer 1704
 
31352 amit.gupta 1705
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
34516 ranu 1706
                Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date", "End Date", "Offer Type", "Additional Info"), rows);
29707 tejbeer 1707
 
31352 amit.gupta 1708
        final HttpHeaders headers = new HttpHeaders();
1709
        headers.set("Content-Type", "text/csv");
1710
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1711
        headers.setContentLength(baos.toByteArray().length);
31147 tejbeer 1712
 
31352 amit.gupta 1713
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1714
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1715
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
31147 tejbeer 1716
 
31352 amit.gupta 1717
    }
31147 tejbeer 1718
 
31352 amit.gupta 1719
    @RequestMapping(value = "/getCustomerOfferItem", method = RequestMethod.GET)
1720
    public String getCustomerOfferItem(HttpServletRequest request, @RequestParam int offerId, Model model)
1721
            throws Exception {
29707 tejbeer 1722
 
31352 amit.gupta 1723
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository.selectByOfferId(offerId);
1724
        List<Integer> catalogIds = customerOfferItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
29707 tejbeer 1725
 
31352 amit.gupta 1726
        Map<Integer, List<Item>> catalogItemMap = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds))
1727
                .stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
29707 tejbeer 1728
 
33795 ranu 1729
        List<OfferType> offerTypes = Arrays.asList(OfferType.values());
1730
 
31352 amit.gupta 1731
        model.addAttribute("catalogItemMap", catalogItemMap);
29707 tejbeer 1732
 
31352 amit.gupta 1733
        model.addAttribute("offerId", offerId);
31147 tejbeer 1734
 
31352 amit.gupta 1735
        model.addAttribute("customerOfferItems", customerOfferItems);
33795 ranu 1736
 
1737
        model.addAttribute("offerTypes", offerTypes);
1738
 
31352 amit.gupta 1739
        return "customer-offer-item";
31147 tejbeer 1740
 
31352 amit.gupta 1741
    }
31147 tejbeer 1742
 
31352 amit.gupta 1743
    @RequestMapping(value = "/expiredCustomerOfferItem", method = RequestMethod.POST)
1744
    public String expiredCustomerOfferItem(HttpServletRequest request, @RequestParam int id,
1745
                                           @RequestParam LocalDateTime endDate, Model model) throws Exception {
31147 tejbeer 1746
 
31352 amit.gupta 1747
        CustomerOfferItem customerOfferItem = customerOfferItemRepository.selectById(id);
31147 tejbeer 1748
 
31352 amit.gupta 1749
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItem.getCustomerOfferId());
31147 tejbeer 1750
 
31352 amit.gupta 1751
        if ((endDate.toLocalDate().equals(customerOffer.getStartDate().toLocalDate())
1752
                || endDate.toLocalDate().isAfter(customerOffer.getStartDate().toLocalDate()))
1753
                && (endDate.toLocalDate().isEqual(customerOffer.getEndDate().toLocalDate())
1754
                || endDate.toLocalDate().isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1755
 
31352 amit.gupta 1756
            customerOfferItem.setEndDate(endDate.toLocalDate());
31147 tejbeer 1757
 
31352 amit.gupta 1758
        } else {
1759
            throw new ProfitMandiBusinessException("Date", customerOffer.getOfferName(),
1760
                    "customer offer expired on " + customerOffer.getEndDate());
1761
        }
1762
        Map<Integer, List<Item>> catalogItemMap = itemRepository
1763
                .selectAllByCatalogItemId(customerOfferItem.getCatalogId()).stream()
1764
                .collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
1765
        model.addAttribute("catalogItemMap", catalogItemMap);
31147 tejbeer 1766
 
31352 amit.gupta 1767
        model.addAttribute("coi", customerOfferItem);
31147 tejbeer 1768
 
31352 amit.gupta 1769
        return "customer-offer-item-index";
31147 tejbeer 1770
 
31352 amit.gupta 1771
    }
31147 tejbeer 1772
 
31352 amit.gupta 1773
    @RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1774
    public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
1775
                                      @RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 1776
 
31352 amit.gupta 1777
        CustomerOffer co = customerOfferRepository.selectById(id);
1778
        co.setEndDate(endDate);
1779
        co.setUpdatedTimestamp(LocalDateTime.now());
31147 tejbeer 1780
 
31352 amit.gupta 1781
        model.addAttribute("co", co);
31147 tejbeer 1782
 
31352 amit.gupta 1783
        return "customer-index-offer";
31147 tejbeer 1784
 
31352 amit.gupta 1785
    }
31147 tejbeer 1786
 
31352 amit.gupta 1787
    @RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1788
    public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 1789
 
31352 amit.gupta 1790
        List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1791
        List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1792
                uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
31147 tejbeer 1793
 
31352 amit.gupta 1794
        model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1795
        return "samsung-upgrade-offer";
31147 tejbeer 1796
 
31352 amit.gupta 1797
    }
31147 tejbeer 1798
 
31352 amit.gupta 1799
    @RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1800
    public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1801
            throws ProfitMandiBusinessException {
29707 tejbeer 1802
 
31352 amit.gupta 1803
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1804
        suo.setStatus(UpgradeOfferStatus.approved);
1805
        suo.setApprovedTimestamp(LocalDateTime.now());
1806
        model.addAttribute("suo", suo);
1807
        return "samsung-upgrade-offer-index";
29707 tejbeer 1808
 
31352 amit.gupta 1809
    }
29707 tejbeer 1810
 
31352 amit.gupta 1811
    @RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1812
    public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1813
            throws ProfitMandiBusinessException {
29707 tejbeer 1814
 
31352 amit.gupta 1815
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1816
        suo.setStatus(UpgradeOfferStatus.rejected);
29707 tejbeer 1817
 
31352 amit.gupta 1818
        model.addAttribute("suo", suo);
1819
        return "samsung-upgrade-offer-index";
29707 tejbeer 1820
 
31352 amit.gupta 1821
    }
29707 tejbeer 1822
 
22860 ashik.ali 1823
}