Subversion Repositories SmartDukaan

Rev

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