Subversion Repositories SmartDukaan

Rev

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