Subversion Repositories SmartDukaan

Rev

Rev 32232 | Rev 32236 | 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()));
32235 amit.gupta 1069
        LOGGER.info("Last month front end imeis - {}", lastMonthFrontEndImeis);
31352 amit.gupta 1070
        Map<String, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
1071
                .collect(Collectors.groupingBy(x -> x.getImei(),
1072
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
30053 manish 1073
 
31352 amit.gupta 1074
        // descriptionSet.add("")
1075
        purchaseSet.addAll(lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
1076
        saleSet.addAll(lastMonthCreditedImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
30053 manish 1077
 
31352 amit.gupta 1078
        List<String> purchaseList = new ArrayList<>(purchaseSet);
1079
        List<String> saleList = new ArrayList<>(saleSet);
30253 amit.gupta 1080
 
31352 amit.gupta 1081
        Map<String, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
30053 manish 1082
 
31352 amit.gupta 1083
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
30235 tejbeer 1084
 
31352 amit.gupta 1085
            String imei = entry.getKey();
1086
            ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imei,
1087
                    imeiPurchaseDateMap.get(imei), null);
1088
            imeiWiseIncomeMapOfMap.put(imei, modelImeiMap);
1089
            double totalAmount = entry.getValue().entrySet().stream()
1090
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1091
            imeiWiseIncomeMapOfMap.get(imei).setTotalIncome(totalAmount);
1092
        }
31283 amit.gupta 1093
 
31352 amit.gupta 1094
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
1095
            Map<String, Double> descriptionAmountMap = entry.getValue();
1096
            if (!imeiWiseIncomeMapOfMap.containsKey(entry.getKey())) {
32232 amit.gupta 1097
                imeiWiseIncomeMapOfMap.put(entry.getKey(), new ImeiWiseIncomePairAndMapModel(entry.getKey(), null, null));
31352 amit.gupta 1098
            }
32232 amit.gupta 1099
            ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(entry.getKey());
1100
            ;
1101
            modelImeiMap.setSaleDate(imeiSaleDateMap.get(entry.getKey()));
30053 manish 1102
 
31352 amit.gupta 1103
            double totalAmount = descriptionAmountMap.entrySet().stream()
1104
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1105
            imeiWiseIncomeMapOfMap.get(entry.getKey())
1106
                    .setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(entry.getKey()).getTotalIncome());
1107
        }
30053 manish 1108
 
31352 amit.gupta 1109
        //Imeis for pending activation
1110
        lastMonthCreditedImeis.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).forEach(x -> {
1111
            if (!imeiWiseIncomeMapOfMap.containsKey(x.getImei())) {
32232 amit.gupta 1112
                imeiWiseIncomeMapOfMap.put(x.getImei(), new ImeiWiseIncomePairAndMapModel(x.getImei()));
31352 amit.gupta 1113
            }
1114
            ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1115
                    .get(x.getImei());
1116
            imeiWiseIncomePairAndMapModel.setSaleDate(x.getCreateTimeStamp().toLocalDate());
1117
            imeiWiseIncomePairAndMapModel.setTotalIncome(x.getPendingSaleAmount() + imeiWiseIncomePairAndMapModel.getTotalIncome());
1118
        });
30053 manish 1119
 
31379 amit.gupta 1120
        lastMonthFrontEndImeis.stream().forEach(lastMonthFrontEndImeiModel -> {
32232 amit.gupta 1121
            if (!imeiWiseIncomeMapOfMap.containsKey(lastMonthFrontEndImeiModel.getImei())) {
1122
                imeiWiseIncomeMapOfMap.put(lastMonthFrontEndImeiModel.getImei(), new ImeiWiseIncomePairAndMapModel(lastMonthFrontEndImeiModel.getImei()));
31379 amit.gupta 1123
            }
32232 amit.gupta 1124
            ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1125
                    .get(lastMonthFrontEndImeiModel.getImei());
1126
            lastMonthFrontEndImeiModel.setNlc(lastMonthFrontEndImeiModel.getDp()
1127
                    - (float) imeiWiseIncomeMapOfMap.get(lastMonthFrontEndImeiModel.getImei()).getTotalIncome());
1128
            lastMonthFrontEndImeiModel.setNetIncome(lastMonthFrontEndImeiModel.getSellingPrice() - lastMonthFrontEndImeiModel.getNlc());
1129
            imeiWiseIncomePairAndMapModel.setSaleDate(lastMonthFrontEndImeiModel.getCreated());
31379 amit.gupta 1130
        });
1131
 
31352 amit.gupta 1132
        model.addAttribute("imeiWisePendingSaleAmount", imeiWisePendingSaleAmount);
1133
        model.addAttribute("month", month);
1134
        model.addAttribute("purchaseList", purchaseList);
1135
        model.addAttribute("saleList", saleList);
1136
        model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1137
        model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1138
        model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1139
        model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
31379 amit.gupta 1140
        model.addAttribute("soldMap", soldMap);
31352 amit.gupta 1141
        model.addAttribute("allOfferPayoutImeiIncomeModels", allOfferPayoutImeiIncomeModels);
1142
        //model.addAttribute("iimeiSaleDateMap", imeiSaleDateMap);
1143
        //model.addAttribute("imeiPurchaseDateMap", imeiPurchaseDateMap);
30053 manish 1144
 
31352 amit.gupta 1145
        return "last-month-imei-wise-income";
1146
    }
30053 manish 1147
 
31352 amit.gupta 1148
    @RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1149
    public String getBrandWiseIncome(HttpServletRequest request,
1150
                                     @RequestParam(name = "brand", required = false, defaultValue = "") String brand,
32232 amit.gupta 1151
                                     @RequestParam(name = "month", required = false, defaultValue = "") int month,
1152
                                     Model model)
31352 amit.gupta 1153
            throws ProfitMandiBusinessException {
1154
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1155
        LOGGER.info("loginDetails {}", loginDetails);
1156
        LOGGER.info("brand" + brand);
1157
        LOGGER.info("month {}", month);
30053 manish 1158
 
31352 amit.gupta 1159
        LocalDateTime monthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1160
        LocalDateTime monthEnd = monthStart.plusMonths(1);
30053 manish 1161
 
31352 amit.gupta 1162
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1163
                YearMonth.of(monthStart.getYear(), monthStart.getMonth()), loginDetails.getFofoId(), brand, null);
32232 amit.gupta 1164
        LOGGER.info("offerPayoutImeiIncomeModels - {}", offerPayoutImeiIncomeModels);
1165
        Map<Integer, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().filter(x -> x.getPurchasePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getPurchasePayout())));
1166
        Map<Integer, Integer> additionalPurchaseQty = offerPayoutImeiIncomeModels.stream().filter(x -> x.getPurchasePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingInt(x -> 1)));
1167
        Map<Integer, Double> additionalSalePayoutMap = offerPayoutImeiIncomeModels.stream().filter(x -> x.getSalePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getSalePayout())));
1168
        Map<Integer, Integer> additionalSaleQty = offerPayoutImeiIncomeModels.stream().filter(x -> x.getSalePayout() > 0).collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingInt(x -> 1)));
30053 manish 1169
 
32232 amit.gupta 1170
        Set<Integer> allCatalogIds = offerPayoutImeiIncomeModels.stream().map(x -> x.getCatalogId()).collect(Collectors.toSet());
31352 amit.gupta 1171
        boolean partnerTypeUpgraded = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(),
1172
                YearMonth.now());
30053 manish 1173
 
31352 amit.gupta 1174
        LOGGER.info("partnerType" + partnerTypeUpgraded);
30053 manish 1175
 
31352 amit.gupta 1176
        Map<String, Double> categoryUpgradeBrandModelMap = null;
1177
        if (partnerTypeUpgraded) {
1178
            categoryUpgradeBrandModelMap = schemeInOutRepository
1179
                    .selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, monthStart,
1180
                            monthEnd)
1181
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1182
        }
30053 manish 1183
 
31352 amit.gupta 1184
        List<LastMonthFrontEndBrandWiseIncome> modelWiseSalesMargins = schemeInOutRepository
1185
                .selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand, monthStart, monthEnd);
32232 amit.gupta 1186
        Map<Integer, LastMonthFrontEndBrandWiseIncome> modelWiseSalesMarginsMap = modelWiseSalesMargins.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1187
 
32232 amit.gupta 1188
 
31352 amit.gupta 1189
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMargins = schemeInOutRepository
1190
                .selectLastMonthBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1191
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMarginsMap = modelWiseSchemeOutMargins.stream()
1192
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1193
 
31352 amit.gupta 1194
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeInMargins = schemeInOutRepository
1195
                .selectLastMonthPurchaseBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1196
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeInMarginsMap = modelWiseSchemeInMargins.stream()
1197
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1198
 
32232 amit.gupta 1199
        allCatalogIds.addAll(modelWiseSalesMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
1200
        allCatalogIds.addAll(modelWiseSchemeInMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
1201
        allCatalogIds.addAll(modelWiseSchemeOutMargins.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet()));
30053 manish 1202
 
32232 amit.gupta 1203
        Map<Integer, String> modelNameMap = itemRepository.selectAllByCatalogIds(allCatalogIds).stream().collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x.getModel(), (u, v) -> u));
1204
        Map<Integer, Double> modelIncomeMap = new HashMap<>();
1205
        Map<Integer, Integer> modelPurchaseQtyMap = new HashMap<>();
1206
        Map<Integer, Integer> modelSaleQtyMap = new HashMap<>();
1207
        for (int catalogItemId : modelNameMap.keySet()) {
1208
            int saleQty = 0;
1209
            int purchaseQty = 0;
1210
            double income = 0;
30253 amit.gupta 1211
 
32232 amit.gupta 1212
            if (modelWiseSchemeInMarginsMap.containsKey(catalogItemId)) {
1213
                income += modelWiseSchemeInMarginsMap.get(catalogItemId).getAmount() + modelWiseSchemeInMarginsMap.get(catalogItemId).getPendingSaleAmount();
1214
                purchaseQty += modelWiseSchemeInMarginsMap.get(catalogItemId).getQty();
31352 amit.gupta 1215
            }
32232 amit.gupta 1216
            if (modelWiseSchemeOutMarginsMap.containsKey(catalogItemId)) {
1217
                income += modelWiseSchemeOutMarginsMap.get(catalogItemId).getAmount() + modelWiseSchemeOutMarginsMap.get(catalogItemId).getPendingSaleAmount();
31352 amit.gupta 1218
            }
32232 amit.gupta 1219
            if (additionalSalePayoutMap.containsKey(catalogItemId)) {
1220
                income += additionalSalePayoutMap.get(catalogItemId);
31352 amit.gupta 1221
            }
32232 amit.gupta 1222
            if (additionalPurchasePayout.containsKey(catalogItemId)) {
1223
                income += additionalPurchasePayout.get(catalogItemId);
1224
            }
1225
            if (modelWiseSalesMarginsMap.containsKey(catalogItemId)) {
1226
                income += modelWiseSalesMarginsMap.get(catalogItemId).getAmount();
1227
                saleQty = (int) modelWiseSalesMarginsMap.get(catalogItemId).getQty();
1228
            }
1229
            if (additionalPurchaseQty.containsKey(catalogItemId)) {
1230
                purchaseQty = Math.max(additionalPurchaseQty.get(catalogItemId), purchaseQty);
30253 amit.gupta 1231
 
31352 amit.gupta 1232
            }
32232 amit.gupta 1233
            modelIncomeMap.put(catalogItemId, income);
1234
            modelSaleQtyMap.put(catalogItemId, saleQty);
1235
            modelPurchaseQtyMap.put(catalogItemId, purchaseQty);
30253 amit.gupta 1236
 
32232 amit.gupta 1237
        }
30253 amit.gupta 1238
 
31352 amit.gupta 1239
        model.addAttribute("month", month);
32232 amit.gupta 1240
        model.addAttribute("modelWiseSalesMarginsMap", modelWiseSalesMarginsMap);
31352 amit.gupta 1241
        model.addAttribute("modelWiseSchemeOutMarginsMap", modelWiseSchemeOutMarginsMap);
1242
        model.addAttribute("modelWiseSchemeInMarginsMap", modelWiseSchemeInMarginsMap);
1243
        model.addAttribute("modelNameMap", modelNameMap);
32232 amit.gupta 1244
        model.addAttribute("modelPurchaseQtyMap", modelPurchaseQtyMap);
1245
        model.addAttribute("modelSaleQtyMap", modelSaleQtyMap);
1246
        model.addAttribute("modelIncomeMap", modelIncomeMap);
31352 amit.gupta 1247
        model.addAttribute("categoryUpgradeBrandModelMap", categoryUpgradeBrandModelMap);
1248
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
32232 amit.gupta 1249
        model.addAttribute("additionalSalePayoutMap", additionalSalePayoutMap);
30253 amit.gupta 1250
 
31352 amit.gupta 1251
        return "monthly-brand-wise-income";
30053 manish 1252
 
31352 amit.gupta 1253
    }
30053 manish 1254
 
31352 amit.gupta 1255
    @RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
1256
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
1257
            throws ProfitMandiBusinessException {
1258
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30253 amit.gupta 1259
 
31352 amit.gupta 1260
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1261
        LocalDateTime lastMonthEnd = startOfMonth.plusMonths(1);
30253 amit.gupta 1262
 
31352 amit.gupta 1263
        YearMonth monthYear = YearMonth.now();
30053 manish 1264
 
31352 amit.gupta 1265
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
30053 manish 1266
 
31352 amit.gupta 1267
        LOGGER.info("partnerType" + partnerType);
30053 manish 1268
 
31352 amit.gupta 1269
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
30053 manish 1270
 
31352 amit.gupta 1271
        if (partnerType) {
1272
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1273
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), startOfMonth,
1274
                            lastMonthEnd)
1275
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1276
        }
30053 manish 1277
 
31352 amit.gupta 1278
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1279
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30053 manish 1280
 
31352 amit.gupta 1281
        List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
1282
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1283
 
31352 amit.gupta 1284
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1285
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1286
 
31352 amit.gupta 1287
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1288
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
32232 amit.gupta 1289
        Map<String, LastMonthCreditedIncomeModel> lastMonthFrontEndIncomeMap = lastMonthFrontEndIncomes.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30235 tejbeer 1290
 
31352 amit.gupta 1291
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1292
                YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()), loginDetails.getFofoId(), null, null);
30235 tejbeer 1293
 
31352 amit.gupta 1294
        Map<String, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getPurchasePayout)));
1295
        Map<String, Double> additionSalePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getSalePayout)));
30235 tejbeer 1296
 
1297
 
31352 amit.gupta 1298
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
1299
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1300
 
31352 amit.gupta 1301
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
1302
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1303
 
1304
 
31352 amit.gupta 1305
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = lastMonthPendingIncomeModels.stream()
1306
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1307
 
31352 amit.gupta 1308
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1309
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1310
        Set<String> brandSet = new HashSet<>();
1311
        brandSet.addAll(lastMonthPurchaseInMarginMap.keySet());
1312
        brandSet.addAll(lastMonthSaleMarginMap.keySet());
1313
        brandSet.addAll(lastMonthPendingIncomeMap.keySet());
1314
        brandSet.addAll(additionalPurchasePayout.keySet());
1315
        brandSet.addAll(additionSalePayout.keySet());
1316
        brandSet.stream().forEach(brand -> {
1317
            totalAmountMap.put(brand,
1318
                    (lastMonthSaleMarginMap.get(brand) == null ? 0 : lastMonthSaleMarginMap.get(brand).getAmount()) +
1319
                            (lastMonthPurchaseInMarginMap.get(brand) == null ? 0 : lastMonthPurchaseInMarginMap.get(brand).getAmount()) +
1320
                            (lastMonthPendingIncomeMap.get(brand) == null ? 0 : lastMonthPendingIncomeMap.get(brand).getAmount()) +
1321
                            (additionalPurchasePayout.get(brand) == null ? 0 : additionalPurchasePayout.get(brand).longValue()) +
32232 amit.gupta 1322
                            (additionSalePayout.get(brand) == null ? 0 : additionSalePayout.get(brand).longValue()) +
1323
                            (lastMonthFrontEndIncomeMap.get(brand) == null ? 0 : lastMonthFrontEndIncomeMap.get(brand).getAmount())
31352 amit.gupta 1324
            );
1325
        });
30053 manish 1326
 
31352 amit.gupta 1327
        Map<Integer, String> monthValueMap = new HashMap<>();
1328
        for (int i = 0; i <= 5; i++) {
1329
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1330
            monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
1331
        }
1332
        model.addAttribute("monthValueMap", monthValueMap);
30053 manish 1333
 
32232 amit.gupta 1334
        model.addAttribute("brandSet", brandSet);
31352 amit.gupta 1335
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1336
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1337
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
1338
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
1339
        model.addAttribute("additionalSalePayoutMap", additionSalePayout);
32232 amit.gupta 1340
        model.addAttribute("lastMonthFrontEndIncomeMap", lastMonthFrontEndIncomeMap);
30053 manish 1341
 
31352 amit.gupta 1342
        model.addAttribute("totalAmountMap", totalAmountMap);
1343
        model.addAttribute("month", yearMonth);
1344
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1345
        LOGGER.info("totalAmountMap {}", totalAmountMap);
1346
        LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
30253 amit.gupta 1347
 
31352 amit.gupta 1348
        return "last-month-credited-income";
1349
    }
30253 amit.gupta 1350
 
31352 amit.gupta 1351
    @RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
1352
    public String downloadPage(HttpServletRequest request, Model model) {
1353
        return "schemes-download";
1354
    }
30253 amit.gupta 1355
 
31352 amit.gupta 1356
    @RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
1357
    public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
1358
                                                                  @RequestParam LocalDateTime startDateTime, @RequestParam LocalDateTime endDateTime)
1359
            throws ProfitMandiBusinessException {
30253 amit.gupta 1360
 
31352 amit.gupta 1361
        List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
31334 amit.gupta 1362
 
31352 amit.gupta 1363
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1364
        ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
30253 amit.gupta 1365
 
31352 amit.gupta 1366
        final HttpHeaders headers = new HttpHeaders();
1367
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
1368
        headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
1369
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1370
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1371
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1372
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1373
    }
30053 manish 1374
 
31352 amit.gupta 1375
    @RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
1376
    public String getSchemeById(HttpServletRequest request,
1377
                                @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
1378
            throws ProfitMandiBusinessException {
1379
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 1380
 
31352 amit.gupta 1381
        boolean fullAccess = this.getAccess(loginDetails.getEmailId());
1382
        Scheme scheme = schemeService.getSchemeById(schemeId);
1383
        model.addAttribute("fullAccess", fullAccess);
1384
        model.addAttribute("scheme", scheme);
1385
        model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
1386
        return "scheme-details";
1387
    }
30053 manish 1388
 
31352 amit.gupta 1389
    @RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
1390
    public String activeSchemeById(@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1391
                                   @RequestParam(name = "offset", defaultValue = "0") int offset,
1392
                                   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1393
            throws ProfitMandiBusinessException {
1394
        schemeService.activeSchemeById(schemeId);
1395
        List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
1396
        for (Scheme scheme : schemes) {
1397
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1398
                scheme.setAmountModel(scheme.getAmount() + "%");
1399
            } else {
1400
                scheme.setAmountModel(scheme.getAmount() + "");
1401
            }
1402
        }
1403
        return "schemes";
1404
    }
30053 manish 1405
 
31352 amit.gupta 1406
    @RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
1407
    public String expireSchemeById(HttpServletRequest request,
1408
                                   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1409
                                   @RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp, Model model)
1410
            throws ProfitMandiBusinessException {
1411
        schemeService.expireSchemeById(schemeId, expiryTimestamp);
1412
        return getDefaultSchemes(request, model);
1413
    }
30053 manish 1414
 
31352 amit.gupta 1415
    @RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
1416
    public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
1417
                                            @RequestParam(name = "offset", defaultValue = "0") int offset,
1418
                                            @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1419
            throws ProfitMandiBusinessException {
1420
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1421
        return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1422
    }
30053 manish 1423
 
31352 amit.gupta 1424
    @RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1425
    public String getCustomerOffer(HttpServletRequest request,
1426
                                   @RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel, Model model)
1427
            throws ProfitMandiBusinessException {
1428
        List<CustomerOffer> customerOffers = null;
1429
        if (searchModel > 0) {
30053 manish 1430
 
31352 amit.gupta 1431
            Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
1432
            customerOffers = customerOfferRepository.selectActiveOfferByModel(searchModel, LocalDate.now());
1433
            model.addAttribute("modelName", item.getItemDescriptionNoColor());
1434
        } else {
1435
            customerOffers = customerOfferRepository.selectAll();
1436
        }
30053 manish 1437
 
31352 amit.gupta 1438
        LOGGER.info("customerOffers" + customerOffers);
30053 manish 1439
 
31352 amit.gupta 1440
        for (CustomerOffer customerOffer : customerOffers) {
30053 manish 1441
 
31352 amit.gupta 1442
            LOGGER.info("ss" + searchModel);
30053 manish 1443
 
31352 amit.gupta 1444
            if (!StringUtils.isEmpty(customerOffer.getPartnerCriteria())) {
1445
                String partnerCriteria = retailerService.getPartnerCriteriaString(
1446
                        gson.fromJson(customerOffer.getPartnerCriteria(), PartnerCriteria.class));
1447
                customerOffer.setPartnerCriteriaString(partnerCriteria);
1448
            }
30053 manish 1449
 
31352 amit.gupta 1450
        }
30053 manish 1451
 
31352 amit.gupta 1452
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1453
                .collect(Collectors.toList());
31281 amit.gupta 1454
 
31352 amit.gupta 1455
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30053 manish 1456
 
31352 amit.gupta 1457
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1458
                .filter(x -> x != null).collect(Collectors.toList()).stream()
1459
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30053 manish 1460
 
31352 amit.gupta 1461
        model.addAttribute("customRetailersMap", customRetailersMap);
1462
        model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
1463
        model.addAttribute("searchModel", searchModel);
30053 manish 1464
 
31352 amit.gupta 1465
        model.addAttribute("customerOffers", customerOffers);
1466
        return "customer-offer";
30053 manish 1467
 
31352 amit.gupta 1468
    }
30053 manish 1469
 
31352 amit.gupta 1470
    @RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1471
    public String createCustomerOffer(HttpServletRequest request, @RequestBody CustomerOfferModel customerOfferModel,
1472
                                      Model model) throws Exception {
30053 manish 1473
 
31352 amit.gupta 1474
        CustomerOffer co = new CustomerOffer();
1475
        co.setOfferName(customerOfferModel.getOfferName());
1476
        co.setStartDate(customerOfferModel.getStartDate());
1477
        co.setEndDate(customerOfferModel.getEndDate());
1478
        co.setPartnerCriteria(gson.toJson(customerOfferModel.getPartnerCriteria()));
1479
        co.setCreatedTimestamp(LocalDateTime.now());
1480
        co.setUpdatedTimestamp(LocalDateTime.now());
1481
        customerOfferRepository.persist(co);
31281 amit.gupta 1482
 
31352 amit.gupta 1483
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31281 amit.gupta 1484
 
31352 amit.gupta 1485
        return "response";
30053 manish 1486
 
31352 amit.gupta 1487
    }
30053 manish 1488
 
31352 amit.gupta 1489
    @RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1490
    public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1491
        List<List<?>> rows = new ArrayList<>();
30053 manish 1492
 
31352 amit.gupta 1493
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("id",
1494
                        "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date (dd-mm-yyyy)", "End Date (dd-mm-yyyy)"),
1495
                rows);
30053 manish 1496
 
31352 amit.gupta 1497
        final HttpHeaders headers = new HttpHeaders();
1498
        headers.set("Content-Type", "text/csv");
1499
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1500
        headers.setContentLength(baos.toByteArray().length);
30053 manish 1501
 
31352 amit.gupta 1502
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1503
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1504
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
30053 manish 1505
 
31352 amit.gupta 1506
    }
30053 manish 1507
 
31352 amit.gupta 1508
    @RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1509
    public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
1510
                                          HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
23786 amit.gupta 1511
 
31352 amit.gupta 1512
        List<CSVRecord> records = FileUtil.readFile(file);
1513
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
23914 govind 1514
 
31352 amit.gupta 1515
        CustomerOffer customerOffer = customerOfferRepository.selectById(offerId);
1516
        List<Integer> catalogIds = new ArrayList<>();
1517
        for (CSVRecord record : records) {
23786 amit.gupta 1518
 
31352 amit.gupta 1519
            CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
23786 amit.gupta 1520
 
31352 amit.gupta 1521
            if (coi == null) {
1522
                coi = new CustomerOfferItem();
1523
                coi.setCatalogId(Integer.parseInt(record.get(1)));
1524
                coi.setSchemePayout(Integer.parseInt(record.get(2)));
1525
                coi.setDealerPayout(Integer.parseInt(record.get(3)));
1526
                coi.setCustomerOfferId(offerId);
1527
                coi.setCreatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1528
 
31352 amit.gupta 1529
                customerOfferItemRepository.persist(coi);
29899 tejbeer 1530
 
31352 amit.gupta 1531
            }
1532
            coi.setSchemePayout(Integer.parseInt(record.get(2)));
1533
            coi.setDealerPayout(Integer.parseInt(record.get(3)));
1534
            coi.setCustomerOfferId(offerId);
1535
            coi.setUpdatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1536
 
31352 amit.gupta 1537
            LOGGER.info(record.get(4));
23786 amit.gupta 1538
 
31352 amit.gupta 1539
            LocalDate startDate = LocalDate.parse(record.get(4), formatter);
1540
            LocalDate endDate = LocalDate.parse(record.get(5), formatter);
23786 amit.gupta 1541
 
31352 amit.gupta 1542
            if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1543
                    || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1544
                    && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1545
                    || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1546
                coi.setStartDate(startDate);
26802 tejbeer 1547
 
31352 amit.gupta 1548
            } else {
29707 tejbeer 1549
 
31352 amit.gupta 1550
                catalogIds.add(coi.getCatalogId());
1551
            }
29707 tejbeer 1552
 
31352 amit.gupta 1553
            if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1554
                    || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1555
                    && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1556
                    || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1557
 
31352 amit.gupta 1558
                coi.setEndDate(endDate);
31147 tejbeer 1559
 
31352 amit.gupta 1560
            } else {
1561
                catalogIds.add(coi.getCatalogId());
1562
            }
31147 tejbeer 1563
 
31352 amit.gupta 1564
        }
31147 tejbeer 1565
 
31352 amit.gupta 1566
        if (!catalogIds.isEmpty()) {
1567
            throw new ProfitMandiBusinessException("Please set accurate start and end date", catalogIds,
1568
                    "Please set accurate start and end date");
1569
        }
1570
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1571
 
31352 amit.gupta 1572
        return "response";
31147 tejbeer 1573
 
31352 amit.gupta 1574
    }
31147 tejbeer 1575
 
31352 amit.gupta 1576
    @RequestMapping(value = "/addCustomerOfferItem", method = RequestMethod.POST)
1577
    public String addCustomerOfferItem(HttpServletRequest request,
1578
                                       @RequestBody CustomerOfferItemModel customerOfferItemModel, Model model) throws Throwable {
31147 tejbeer 1579
 
31352 amit.gupta 1580
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItemModel.getOfferId());
31147 tejbeer 1581
 
31352 amit.gupta 1582
        if (!(customerOffer.getEndDate().toLocalDate().equals(LocalDate.now()))
1583
                && customerOffer.getEndDate().isBefore(LocalDateTime.now())) {
1584
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(), "Offer is Expired");
29707 tejbeer 1585
 
31352 amit.gupta 1586
        }
29707 tejbeer 1587
 
31352 amit.gupta 1588
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
1589
                .selectByOfferAndCatalogId(customerOfferItemModel.getOfferId(), customerOfferItemModel.getCatalogId());
29707 tejbeer 1590
 
31352 amit.gupta 1591
        if (!customerOfferItems.isEmpty()) {
29707 tejbeer 1592
 
31352 amit.gupta 1593
            for (CustomerOfferItem coi : customerOfferItems) {
1594
                if (!(coi.getEndDate().equals(LocalDate.now())) && coi.getEndDate().isAfter(LocalDate.now())) {
1595
                    throw new ProfitMandiBusinessException("Catalog Id", coi.getCatalogId(), "Item is already exist.");
1596
                }
1597
            }
29707 tejbeer 1598
 
31352 amit.gupta 1599
        }
29707 tejbeer 1600
 
31352 amit.gupta 1601
        LocalDate startDate = customerOfferItemModel.getStartDate().toLocalDate();
1602
        LocalDate endDate = customerOfferItemModel.getEndDate().toLocalDate();
1603
        CustomerOfferItem coi = new CustomerOfferItem();
1604
        coi.setCatalogId(customerOfferItemModel.getCatalogId());
1605
        coi.setSchemePayout(customerOfferItemModel.getSchemePayout());
1606
        coi.setDealerPayout(customerOfferItemModel.getDealerPayout());
1607
        coi.setCustomerOfferId(customerOfferItemModel.getOfferId());
1608
        coi.setUpdatedTimestamp(LocalDateTime.now());
1609
        coi.setCreatedTimestamp(LocalDateTime.now());
29707 tejbeer 1610
 
31352 amit.gupta 1611
        if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1612
                || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1613
                && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1614
                || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 1615
 
31352 amit.gupta 1616
            coi.setStartDate(startDate);
29707 tejbeer 1617
 
31352 amit.gupta 1618
        } else {
29707 tejbeer 1619
 
31352 amit.gupta 1620
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1621
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1622
                            + customerOffer.getEndDate());
29707 tejbeer 1623
 
31352 amit.gupta 1624
        }
29707 tejbeer 1625
 
31352 amit.gupta 1626
        if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1627
                || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1628
                && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1629
                || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 1630
 
31352 amit.gupta 1631
            coi.setEndDate(endDate);
29707 tejbeer 1632
 
31352 amit.gupta 1633
        } else {
1634
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1635
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1636
                            + customerOffer.getEndDate());
1637
        }
31147 tejbeer 1638
 
31352 amit.gupta 1639
        customerOfferItemRepository.persist(coi);
31147 tejbeer 1640
 
31352 amit.gupta 1641
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1642
 
31352 amit.gupta 1643
        return "response";
29707 tejbeer 1644
 
31352 amit.gupta 1645
    }
31147 tejbeer 1646
 
31352 amit.gupta 1647
    @RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1648
    public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
31147 tejbeer 1649
 
31352 amit.gupta 1650
        List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1651
        List<List<?>> rows = new ArrayList<>();
1652
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
31147 tejbeer 1653
 
31352 amit.gupta 1654
        for (CustomerOfferItem coi : cois) {
1655
            rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout(),
1656
                    coi.getStartDate().format(formatter), coi.getEndDate().format(formatter)));
31147 tejbeer 1657
 
31352 amit.gupta 1658
        }
31147 tejbeer 1659
 
31352 amit.gupta 1660
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1661
                Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date", "End Date"), rows);
29707 tejbeer 1662
 
31352 amit.gupta 1663
        final HttpHeaders headers = new HttpHeaders();
1664
        headers.set("Content-Type", "text/csv");
1665
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1666
        headers.setContentLength(baos.toByteArray().length);
31147 tejbeer 1667
 
31352 amit.gupta 1668
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1669
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1670
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
31147 tejbeer 1671
 
31352 amit.gupta 1672
    }
31147 tejbeer 1673
 
31352 amit.gupta 1674
    @RequestMapping(value = "/getCustomerOfferItem", method = RequestMethod.GET)
1675
    public String getCustomerOfferItem(HttpServletRequest request, @RequestParam int offerId, Model model)
1676
            throws Exception {
29707 tejbeer 1677
 
31352 amit.gupta 1678
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository.selectByOfferId(offerId);
1679
        List<Integer> catalogIds = customerOfferItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
29707 tejbeer 1680
 
31352 amit.gupta 1681
        Map<Integer, List<Item>> catalogItemMap = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds))
1682
                .stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
29707 tejbeer 1683
 
31352 amit.gupta 1684
        model.addAttribute("catalogItemMap", catalogItemMap);
29707 tejbeer 1685
 
31352 amit.gupta 1686
        model.addAttribute("offerId", offerId);
31147 tejbeer 1687
 
31352 amit.gupta 1688
        model.addAttribute("customerOfferItems", customerOfferItems);
1689
        return "customer-offer-item";
31147 tejbeer 1690
 
31352 amit.gupta 1691
    }
31147 tejbeer 1692
 
31352 amit.gupta 1693
    @RequestMapping(value = "/expiredCustomerOfferItem", method = RequestMethod.POST)
1694
    public String expiredCustomerOfferItem(HttpServletRequest request, @RequestParam int id,
1695
                                           @RequestParam LocalDateTime endDate, Model model) throws Exception {
31147 tejbeer 1696
 
31352 amit.gupta 1697
        CustomerOfferItem customerOfferItem = customerOfferItemRepository.selectById(id);
31147 tejbeer 1698
 
31352 amit.gupta 1699
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItem.getCustomerOfferId());
31147 tejbeer 1700
 
31352 amit.gupta 1701
        if ((endDate.toLocalDate().equals(customerOffer.getStartDate().toLocalDate())
1702
                || endDate.toLocalDate().isAfter(customerOffer.getStartDate().toLocalDate()))
1703
                && (endDate.toLocalDate().isEqual(customerOffer.getEndDate().toLocalDate())
1704
                || endDate.toLocalDate().isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1705
 
31352 amit.gupta 1706
            customerOfferItem.setEndDate(endDate.toLocalDate());
31147 tejbeer 1707
 
31352 amit.gupta 1708
        } else {
1709
            throw new ProfitMandiBusinessException("Date", customerOffer.getOfferName(),
1710
                    "customer offer expired on " + customerOffer.getEndDate());
1711
        }
1712
        Map<Integer, List<Item>> catalogItemMap = itemRepository
1713
                .selectAllByCatalogItemId(customerOfferItem.getCatalogId()).stream()
1714
                .collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
1715
        model.addAttribute("catalogItemMap", catalogItemMap);
31147 tejbeer 1716
 
31352 amit.gupta 1717
        model.addAttribute("coi", customerOfferItem);
31147 tejbeer 1718
 
31352 amit.gupta 1719
        return "customer-offer-item-index";
31147 tejbeer 1720
 
31352 amit.gupta 1721
    }
31147 tejbeer 1722
 
31352 amit.gupta 1723
    @RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1724
    public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
1725
                                      @RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 1726
 
31352 amit.gupta 1727
        CustomerOffer co = customerOfferRepository.selectById(id);
1728
        co.setEndDate(endDate);
1729
        co.setUpdatedTimestamp(LocalDateTime.now());
31147 tejbeer 1730
 
31352 amit.gupta 1731
        model.addAttribute("co", co);
31147 tejbeer 1732
 
31352 amit.gupta 1733
        return "customer-index-offer";
31147 tejbeer 1734
 
31352 amit.gupta 1735
    }
31147 tejbeer 1736
 
31352 amit.gupta 1737
    @RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1738
    public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 1739
 
31352 amit.gupta 1740
        List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1741
        List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1742
                uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
31147 tejbeer 1743
 
31352 amit.gupta 1744
        model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1745
        return "samsung-upgrade-offer";
31147 tejbeer 1746
 
31352 amit.gupta 1747
    }
31147 tejbeer 1748
 
31352 amit.gupta 1749
    @RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1750
    public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1751
            throws ProfitMandiBusinessException {
29707 tejbeer 1752
 
31352 amit.gupta 1753
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1754
        suo.setStatus(UpgradeOfferStatus.approved);
1755
        suo.setApprovedTimestamp(LocalDateTime.now());
1756
        model.addAttribute("suo", suo);
1757
        return "samsung-upgrade-offer-index";
29707 tejbeer 1758
 
31352 amit.gupta 1759
    }
29707 tejbeer 1760
 
31352 amit.gupta 1761
    @RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1762
    public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1763
            throws ProfitMandiBusinessException {
29707 tejbeer 1764
 
31352 amit.gupta 1765
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1766
        suo.setStatus(UpgradeOfferStatus.rejected);
29707 tejbeer 1767
 
31352 amit.gupta 1768
        model.addAttribute("suo", suo);
1769
        return "samsung-upgrade-offer-index";
29707 tejbeer 1770
 
31352 amit.gupta 1771
    }
29707 tejbeer 1772
 
22860 ashik.ali 1773
}