Subversion Repositories SmartDukaan

Rev

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

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