Subversion Repositories SmartDukaan

Rev

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