Subversion Repositories SmartDukaan

Rev

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

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