Subversion Repositories SmartDukaan

Rev

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