Subversion Repositories SmartDukaan

Rev

Rev 31352 | Rev 31383 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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