Subversion Repositories SmartDukaan

Rev

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