Subversion Repositories SmartDukaan

Rev

Rev 31335 | Rev 31379 | 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);
343
        LOGGER.info("reportResponse {}", evaluateSchemeInvestmentPayouts);
31147 tejbeer 344
 
31352 amit.gupta 345
        int referenceId = Integer.parseInt(FormattingUtils.getYearMonth(startOfPreviousMonth.atStartOfDay()));
346
        List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
347
                .selectAll(startOfPreviousMonth, lastOfPreviousMonth);
348
        Map<Integer, Long> investmentMaintainedDaysMap = partnerDailyInvestments.stream()
349
                .filter(x -> x.getShortPercentage() <= 10)
350
                .collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.counting()));
29899 tejbeer 351
 
31352 amit.gupta 352
        for (EvaluateSchemeInvestmentPayoutModel esip : evaluateSchemeInvestmentPayouts) {
29608 amit.gupta 353
 
31352 amit.gupta 354
            long investmentMaintainedDays = investmentMaintainedDaysMap.get(esip.getFofoId()) == null ? 0
355
                    : investmentMaintainedDaysMap.get(esip.getFofoId());
29899 tejbeer 356
 
31352 amit.gupta 357
            esip.setInvestmentDays(investmentMaintainedDays);
29899 tejbeer 358
 
31352 amit.gupta 359
            float processAmount = esip.getPaidAmount() / 2;
29899 tejbeer 360
 
31352 amit.gupta 361
            esip.setProcessAmount(processAmount);
29899 tejbeer 362
 
31352 amit.gupta 363
            rows.add(Arrays.asList(esip.getCode(), esip.getStoreName(), esip.getFofoId(), esip.getItemId(),
364
                    esip.getBrand(), esip.getModelName(), esip.getModelNumber(), esip.getColor(), esip.getSchemeInDp(),
365
                    esip.getSchemeOutDp(), esip.getSchemeId(), esip.getName(), esip.getType(), esip.getPartnerType(),
366
                    esip.getAmountType(), esip.getAmount(), esip.getPurchaseInvoice(), esip.getSaleInovoice(),
367
                    esip.getPaidAmount(), esip.getCreateTimestamp(), esip.getRolledBackTimestamp(),
368
                    esip.getSerialNumber(), esip.getInRef(), esip.getOutRef(), esip.getBusinessDate(), esip.getStatus(),
369
                    esip.getDescription(), esip.getProcessAmount(), esip.getInvestmentDays()));
370
        }
29899 tejbeer 371
 
31352 amit.gupta 372
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
373
                .getCSVByteStream(Arrays.asList("Code", "Store Name", "Fofo Id", "Item Id", "Brand", "Model Name",
374
                        "Model Number", "Color", "Scheme In Dp", "Scheme Out Dp", "Scheme Id", "Name", "Type",
375
                        "Partner Type", "Amount Type", "Amount", "Purchase Invoice", "Sale Inovoice", "Paid Amount",
376
                        "Create Timestamp", "Rolled Back Timestamp", "Serial Number", "In Ref", "Out Ref",
377
                        "Business Date", "Status", "Description", "Process Amount", "Investment Days"), rows);
29899 tejbeer 378
 
31352 amit.gupta 379
        final HttpHeaders headers = new HttpHeaders();
380
        headers.set("Content-Type", "text/csv");
381
        headers.set("Content-disposition", "inline; filename=schemePayout.csv");
382
        headers.setContentLength(baos.toByteArray().length);
29899 tejbeer 383
 
31352 amit.gupta 384
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
385
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
23914 govind 386
 
31352 amit.gupta 387
        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
30494 amit.gupta 388
 
31352 amit.gupta 389
    }
30494 amit.gupta 390
 
31352 amit.gupta 391
    @RequestMapping(value = "/schemes/update", method = RequestMethod.POST)
392
    public String updateShcemes(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
393
            throws Exception {
394
        for (int schemeId : schemeItems.getSchemeIds()) {
395
            if (schemeRepository.selectById(schemeId) != null)
396
                for (int catalogId : schemeItems.getCatalogIds()) {
397
                    if (tagListingRepository.selectAllByCatalogIds(Arrays.asList(catalogId)).size() > 0) {
398
                        SchemeItem si = new SchemeItem();
399
                        si.setCatalogId(catalogId);
400
                        si.setSchemeId(schemeId);
401
                        si.setCreateTimestamp(LocalDateTime.now());
402
                        try {
403
                            schemeItemRepository.persist(si);
404
                        } catch (Exception e) {
405
                            LOGGER.info("Scheme aleady exist");
406
                        }
407
                        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
408
                    } else {
409
                        model.addAttribute("response1", mvcResponseSender.createResponseString(false));
410
                        throw new ProfitMandiBusinessException("Catalog Id ", catalogId, "Invalid Catalog Id");
411
                    }
412
                }
413
        }
414
        return "response";
415
    }
29608 amit.gupta 416
 
31352 amit.gupta 417
    @RequestMapping(value = "/addItemToScheme", method = RequestMethod.POST)
418
    public String updateScheme(HttpServletRequest request, @RequestBody SchemeItems schemeItems, Model model)
419
            throws Exception {
420
        for (int schemeId : schemeItems.getSchemeIds()) {
421
            List<Integer> catalogIds = schemeItemRepository.selectCatalogIdsBySchemeId(schemeId);
422
            if (schemeRepository.selectById(schemeId) != null)
423
                for (int catalogId : schemeItems.getCatalogIds()) {
424
                    if (!(catalogIds.contains(catalogId))) {
425
                        SchemeItem si = new SchemeItem();
426
                        si.setCatalogId(catalogId);
427
                        si.setSchemeId(schemeId);
428
                        si.setCreateTimestamp(LocalDateTime.now());
429
                        try {
430
                            schemeItemRepository.persist(si);
431
                        } catch (Exception e) {
432
                            LOGGER.info("Scheme already exist");
433
                        }
434
                        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
435
                    } else {
436
                        throw new ProfitMandiBusinessException("Catalog exist for scheme",
437
                                "SchemeId= " + schemeId + ", CatalogId= " + catalogId, "Catalog exist for scheme");
438
                    }
439
                }
440
        }
441
        return "response";
442
    }
30768 amit.gupta 443
 
31352 amit.gupta 444
    @RequestMapping(value = "/createScheme", method = RequestMethod.GET)
445
    public String createScheme(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
446
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29608 amit.gupta 447
 
31352 amit.gupta 448
        LocalDate currentdate = LocalDate.now();
449
        Month month = currentdate.getMonth().minus(1);
450
        model.addAttribute("month", month);
29608 amit.gupta 451
 
31352 amit.gupta 452
        // Map<Integer, String> itemIdItemDescriptionMap =
453
        // inventoryService.getAllItemIdItemDescriptionMap();
454
        // model.addAttribute("itemIdItemDescriptionMap", itemIdItemDescriptionMap);
455
        // List<Category> categories = inventoryService.getAllCategories();
456
        List<Category> categories = categoryRepository.selectByIds(categoryIds);
457
        categories = categories.stream().sorted(Comparator.comparing(Category::getId)).collect(Collectors.toList());
458
        // Set<String> brands =
459
        // inventoryService.getAllTagListingBrands(ProfitMandiConstants.MOBILE_CATEGORY_ID);
460
        // brands.addAll(inventoryService.getAllTagListingBrands(14206));
29608 amit.gupta 461
 
31352 amit.gupta 462
        boolean fullAccesss = this.getAccess(loginDetails.getEmailId());
25256 amit.gupta 463
 
31352 amit.gupta 464
        List<Region> regionList = regionRepository.selectAll();
29608 amit.gupta 465
 
31352 amit.gupta 466
        model.addAttribute("fullAccesss", fullAccesss);
467
        model.addAttribute("regionList", regionList);
29608 amit.gupta 468
 
31352 amit.gupta 469
        model.addAttribute("categories", categories);
470
        model.addAttribute("retailerTypes", PartnerType.values());
471
        return "create-scheme";
472
    }
29663 manish 473
 
31352 amit.gupta 474
    @RequestMapping(value = "/extendAllSchemes", method = RequestMethod.POST)
475
    public String extendAllScheme(HttpServletRequest request, @RequestBody LocalDateTime extendDatetime, Model model)
476
            throws Exception {
477
        List<Scheme> schemes = schemeRepository.selectActiveAll();
478
        if (schemes.size() > 0) {
479
            for (Scheme scheme : schemes) {
480
                if (scheme.getExpireTimestamp() == null) {
481
                    scheme.setEndDateTime(extendDatetime);
482
                    schemeRepository.persist(scheme);
483
                }
484
            }
485
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
486
            return "response";
487
        }
488
        model.addAttribute("response1", mvcResponseSender.createResponseString(false));
489
        return "response";
490
    }
29608 amit.gupta 491
 
31352 amit.gupta 492
    @RequestMapping(value = "/getCatalogDescriptionByBrands", method = RequestMethod.GET)
493
    public String getTagListingItemsByBrand(HttpServletRequest request, @RequestParam int categoryId,
494
                                            @RequestParam List<String> brands, Model model) throws Exception {
495
        Map<Integer, String> catalogIdItemDescriptionMap = inventoryService.getModelDescriptionMap(categoryId, brands);
496
        model.addAttribute("catalogIdItemDescriptionMap", catalogIdItemDescriptionMap);
497
        // model.addAttribute("brands", inventoryService.getAllBrands());
29585 manish 498
 
31352 amit.gupta 499
        return "tag-listing-items-description";
500
    }
29663 manish 501
 
31352 amit.gupta 502
    @RequestMapping(value = "/createScheme", method = RequestMethod.POST)
503
    public String createScheme(HttpServletRequest request, @RequestBody CreateSchemeRequest createSchemeRequest,
504
                               Model model) throws ProfitMandiBusinessException {
505
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
506
        LOGGER.info("CreateSchemeRequest {}", createSchemeRequest);
507
        schemeService.saveScheme(loginDetails.getFofoId(), createSchemeRequest);
508
        return getDefaultSchemes(request, model);
509
    }
29663 manish 510
 
31352 amit.gupta 511
    private String getDefaultSchemes(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
512
        return getSchemes(request, 0, null, 30, 0, 0, PartnerType.ALL, "", model);
513
    }
29663 manish 514
 
31352 amit.gupta 515
    private List<Scheme> setSchemeAmountModel(List<Scheme> schemes) {
516
        for (Scheme scheme : schemes) {
517
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
518
                scheme.setAmountModel(scheme.getAmount() + "%");
519
            } else {
520
                scheme.setAmountModel(scheme.getAmount() + "");
521
            }
522
        }
523
        return schemes;
524
    }
29663 manish 525
 
31352 amit.gupta 526
    // Show 20 recents
29663 manish 527
 
31352 amit.gupta 528
    @RequestMapping(value = "/schemes/delete", method = RequestMethod.DELETE)
529
    public String deleteShcemes(HttpServletRequest request,
530
                                @RequestParam(name = "schemeId", required = false, defaultValue = "0") int schemeId,
531
                                @RequestParam(name = "catalogId", required = false, defaultValue = "0") int catalogId, Model model)
532
            throws Exception {
533
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
534
        if (schemeId > 0 && catalogId > 0) {
535
            schemeItemRepository.deleteByCatalogIdsAndSchemeIds(catalogId, schemeId);
29608 amit.gupta 536
 
31352 amit.gupta 537
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
29585 manish 538
 
31352 amit.gupta 539
            model.addAttribute("roleType", roleManager.isAdmin(loginDetails.getRoleIds()));
29585 manish 540
 
31352 amit.gupta 541
        }
542
        return "response";
543
    }
29585 manish 544
 
31352 amit.gupta 545
    @RequestMapping(value = "/extendSchemeById", method = RequestMethod.POST)
546
    public String extendSchemeById(HttpServletRequest request,
29585 manish 547
 
31352 amit.gupta 548
                                   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
549
                                   @RequestBody LocalDateTime extendDatetime, Model model) throws Exception {
550
        Scheme scheme = schemeRepository.selectById(schemeId);
551
        if ((!(scheme.getActiveTimestamp() == null)) && scheme.getExpireTimestamp() == null) {
552
            scheme.setEndDateTime(extendDatetime);
553
            schemeRepository.persist(scheme);
554
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
555
            return "response";
556
        }
557
        model.addAttribute("response1", mvcResponseSender.createResponseString(false));
558
        return "response";
559
    }
29608 amit.gupta 560
 
31352 amit.gupta 561
    @RequestMapping(value = "/getSchemes", method = RequestMethod.GET)
562
    public String getSchemes(HttpServletRequest request, @RequestParam(name = "offset", defaultValue = "0") int offset,
563
                             @RequestParam(required = false) LocalDate date,
564
                             @RequestParam(name = "limit", required = false, defaultValue = "30") int limit,
565
                             @RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel,
566
                             @RequestParam(name = "searchScheme", required = false, defaultValue = "0") int searchScheme,
567
                             @RequestParam(name = "partnerType", required = false, defaultValue = "ALL") PartnerType partnerType,
568
                             @RequestParam(name = "searchImei", required = false, defaultValue = "") String searchImei, Model model)
569
            throws ProfitMandiBusinessException {
570
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
571
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
572
        if (date != null) {
573
            date = date.isAfter(LocalDate.now()) ? LocalDate.now() : date;
574
        } else if (!isAdmin) {
575
            date = LocalDate.now();
576
        }
29608 amit.gupta 577
 
31352 amit.gupta 578
        List<Scheme> schemes = null;
579
        List<SchemeInOut> schemeInOuts = null;
29608 amit.gupta 580
 
31352 amit.gupta 581
        boolean fullAccess = this.getAccess(loginDetails.getEmailId());
29608 amit.gupta 582
 
31352 amit.gupta 583
        model.addAttribute("fullAccess", fullAccess);
584
        model.addAttribute("searchImei", searchImei);
585
        model.addAttribute("isAdmin", isAdmin);
586
        model.addAttribute("searchModel", searchModel);
587
        model.addAttribute("searchScheme", searchScheme);
588
        model.addAttribute("partnerType", partnerType);
589
        model.addAttribute("date", date);
29608 amit.gupta 590
 
31352 amit.gupta 591
        final LocalDate date1 = date;
592
        if (searchScheme > 0) {
593
            schemes = Arrays.asList(schemeRepository.selectById(searchScheme));
594
            this.setSchemeAmountModel(schemes);
595
            if (schemes.size() > 0) {
596
                model.addAttribute("schemes", schemes);
597
                List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
598
                Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
599
                model.addAttribute("schemeRegionMap", schemeRegionMap);
600
                return "schemes";
601
            } else {
602
                throw new ProfitMandiBusinessException("SchemeId", searchScheme, "SchemeId Not Found");
603
            }
604
        } else if (searchModel > 0) {
605
            Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
606
            TagListing tagListing = tagListingRepository.selectByItemId(item.getId());
607
            if (tagListing != null) {
608
                model.addAttribute("dp", tagListing.getSellingPrice());
609
                model.addAttribute("mop", tagListing.getMop());
610
            }
611
            model.addAttribute("modelName", item.getItemDescriptionNoColor());
612
            if (isAdmin) {
613
                schemes = schemeService
614
                        .selectSchemeByPartnerType(partnerType, date, searchModel, isAdmin, offset, limit).stream()
615
                        .filter(x -> x.getId() != 411 && x.getId() != 612).collect(Collectors.toList());
616
                this.setSchemeAmountModel(schemes);
617
                model.addAttribute("schemes", schemes);
618
                List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
619
                Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
620
                model.addAttribute("schemeRegionMap", schemeRegionMap);
621
                return "schemes";
622
            } else {
623
                partnerType = partnerTypeChangeService.getTypeOnDate(loginDetails.getFofoId(), date);
624
                schemes = schemeService
625
                        .selectSchemeByPartnerTypeFofoId(partnerType, date, searchModel, loginDetails.getFofoId(), offset, limit).stream()
626
                        .filter(x -> {
627
                            return (x.getId() != 411 && x.getId() != 612) || date1.isBefore(LocalDate.of(2021, 12, 1));
628
                        }).collect(Collectors.toList());
629
                // Remove 411 and 612
630
                // this.setSchemeAmountModel(schemes);
631
                int nlc = this.getNlc(item, loginDetails.getFofoId(), schemes, tagListing);
632
                // For 7720(HR) remove investment
633
                model.addAttribute("schemes", schemes);
634
                model.addAttribute("nlc", Math.round(nlc));
29608 amit.gupta 635
 
31352 amit.gupta 636
                Map<Integer, Map<Integer, Long>> offerSlabPayoutMap = new HashMap<>();
637
                List<CreateOfferRequest> offers = offerService.getPublishedOffers(date, loginDetails.getFofoId(),
638
                        searchModel);
639
                if (offers.size() > 0) {
640
                    for (CreateOfferRequest createOfferRequest : offers) {
641
                        Map<Integer, Map<Integer, Long>> catalogSlabPayoutMap = offerService
642
                                .getSlabPayoutMap(createOfferRequest);
643
                        Map<Integer, Long> slabPayoutMap = catalogSlabPayoutMap.get(searchModel);
644
                        offerSlabPayoutMap.put(createOfferRequest.getId(), slabPayoutMap);
645
                    }
646
                    model.addAttribute("offers", offers);
647
                    model.addAttribute("offerSlabPayoutMap", offerSlabPayoutMap);
29608 amit.gupta 648
 
31352 amit.gupta 649
                    LOGGER.info("offer");
650
                }
651
                FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
652
                model.addAttribute("partnerCode", fs.getCode());
653
                model.addAttribute("fofoId", fs.getId());
29585 manish 654
 
31352 amit.gupta 655
                return "schemes-partner";
29608 amit.gupta 656
 
31352 amit.gupta 657
            }
29608 amit.gupta 658
 
31352 amit.gupta 659
        } else if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
29608 amit.gupta 660
 
31352 amit.gupta 661
            LOGGER.info("searchImei" + searchImei);
29608 amit.gupta 662
 
31352 amit.gupta 663
            InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
664
                    loginDetails.getFofoId());
665
            Item item = itemRepository.selectById(inventoryItem.getItemId());
666
            Map<Integer, Scheme> schemeMap = new HashMap<>();
667
            double netEarnings = 0;
668
            if (inventoryItem != null) {
669
                // Offer payout
670
                List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(loginDetails.getFofoId(),
671
                        searchImei);
672
                Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream()
673
                        .map(x -> offerService.getOffer(loginDetails.getFofoId(), (int) x.getOfferId()))
674
                        .collect(Collectors.toMap(x -> x.getId(), x -> x));
29608 amit.gupta 675
 
31352 amit.gupta 676
                schemeInOuts = schemeInOutRepository
677
                        .selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
25256 amit.gupta 678
 
31352 amit.gupta 679
                if (!schemeInOuts.isEmpty()) {
680
                    netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED))
681
                            .collect(Collectors.summingDouble(x -> x.getAmount()));
682
                    List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId())
683
                            .collect(Collectors.toList());
23914 govind 684
 
31352 amit.gupta 685
                    schemes = schemeRepository.selectBySchemeIds(schemeIds);
686
                    for (Scheme scheme : schemes) {
687
                        if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
688
                            scheme.setAmountModel(scheme.getAmount() + "%");
689
                        } else {
690
                            scheme.setAmountModel(scheme.getAmount() + "");
691
                        }
692
                    }
23914 govind 693
 
31352 amit.gupta 694
                    schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
695
                }
696
                List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
697
                        .selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
698
                if (priceDropImeis.size() > 0) {
23914 govind 699
 
31352 amit.gupta 700
                    for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
701
                        int priceDropId = priceDropIMEI.getPriceDropId();
702
                        PriceDrop pd = priceDropRepository.selectById(priceDropId);
703
                        priceDropIMEI.setPriceDrop(pd);
704
                    }
705
                    model.addAttribute("priceDropImeis", priceDropImeis);
706
                }
707
                netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
708
                model.addAttribute("offerPayouts", offerPayouts);
709
                model.addAttribute("offerRequestMap", offerRequestMap);
710
                model.addAttribute("inventoryItem", inventoryItem);
711
                model.addAttribute("inventoryItem", inventoryItem);
23914 govind 712
 
31352 amit.gupta 713
            }
714
            model.addAttribute("netEarnings", netEarnings);
715
            model.addAttribute("fofoId", loginDetails.getFofoId());
716
            model.addAttribute("schemeMap", schemeMap);
717
            model.addAttribute("item", item);
718
            model.addAttribute("schemeInOut", schemeInOuts);
719
            return "schemes-partner";
720
        }
31170 amit.gupta 721
 
31352 amit.gupta 722
        if (isAdmin) {
723
            schemes = schemeRepository.selectAll(0, 100);
724
            this.setSchemeAmountModel(schemes);
725
            List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
726
            Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
727
            model.addAttribute("schemes", schemes);
728
            model.addAttribute("schemeRegionMap", schemeRegionMap);
31170 amit.gupta 729
 
31352 amit.gupta 730
            return "schemes";
731
        } else {
732
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
733
                InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
734
                        loginDetails.getFofoId());
735
                List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
736
                        .selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
737
                if (priceDropImeis.size() > 0) {
31170 amit.gupta 738
 
31352 amit.gupta 739
                    for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
740
                        int priceDropId = priceDropIMEI.getPriceDropId();
741
                        PriceDrop pd = priceDropRepository.selectById(priceDropId);
742
                        priceDropIMEI.setPriceDrop(pd);
743
                    }
744
                    model.addAttribute("priceDropImeis", priceDropImeis);
745
                }
746
            }
747
            FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
748
            model.addAttribute("partnerCode", fs.getCode());
749
            model.addAttribute("fofoId", fs.getId());
750
            return "schemes-partner";
751
        }
23914 govind 752
 
31352 amit.gupta 753
    }
23786 amit.gupta 754
 
31352 amit.gupta 755
    private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing) {
756
        if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
757
                .filter(x -> x.getId() == fofoId).count() > 0) {
758
            schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
759
                    .collect(Collectors.toList());
760
        }
761
        float nlc = tagListing.getSellingPrice();
762
        for (Scheme scheme : schemes) {
763
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
764
                if (tagListing != null) {
765
                    float amount = tagListing.getSellingPrice() * scheme.getAmount() / 100;
766
                    scheme.setAmountModel(FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
767
                    nlc -= amount;
768
                } else {
769
                    scheme.setAmountModel(scheme.getAmount() + "%");
770
                }
771
            } else {
772
                scheme.setAmountModel(scheme.getAmount() + "");
773
                nlc -= scheme.getAmount();
774
            }
775
        }
23819 govind 776
 
31352 amit.gupta 777
        return Math.round(nlc);
23914 govind 778
 
31352 amit.gupta 779
    }
29899 tejbeer 780
 
31352 amit.gupta 781
    @RequestMapping(value = "/getLastMonthCreditIncome", method = RequestMethod.GET)
782
    public String getLastMonthCreditIncome(HttpServletRequest request, Model model) throws Exception {
30122 amit.gupta 783
 
31352 amit.gupta 784
        String status = "CREDITED";
785
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23786 amit.gupta 786
 
31352 amit.gupta 787
        LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
788
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
31170 amit.gupta 789
 
31352 amit.gupta 790
        YearMonth yearMonth = YearMonth.now();
791
        LOGGER.info("yearMonth" + yearMonth);
31170 amit.gupta 792
 
31352 amit.gupta 793
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), yearMonth);
31170 amit.gupta 794
 
31352 amit.gupta 795
        LOGGER.info("partnerType" + partnerType);
31170 amit.gupta 796
 
31352 amit.gupta 797
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
31170 amit.gupta 798
 
31352 amit.gupta 799
        if (partnerType) {
800
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
801
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), currentStartMonth,
802
                            currentDate)
803
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
804
        }
805
        List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
806
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
31170 amit.gupta 807
 
31352 amit.gupta 808
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
809
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
31170 amit.gupta 810
 
31352 amit.gupta 811
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
812
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), currentStartMonth, currentDate);
26802 tejbeer 813
 
31352 amit.gupta 814
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = schemeInOutRepository
815
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate).stream()
816
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
28796 tejbeer 817
 
31352 amit.gupta 818
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
29608 amit.gupta 819
 
31352 amit.gupta 820
        lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
821
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
29608 amit.gupta 822
 
31352 amit.gupta 823
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
824
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30274 amit.gupta 825
 
31352 amit.gupta 826
        lastMonthFrontEndIncomes.stream().forEach(x -> {
827
            if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
828
                x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
829
                lastMonthSaleMarginMap.put(x.getBrand(), x);
830
            } else {
831
                lastMonthSaleMarginMap.put(x.getBrand(), x);
832
            }
30274 amit.gupta 833
 
31352 amit.gupta 834
        });
835
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
836
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
30274 amit.gupta 837
 
31352 amit.gupta 838
        Set<String> keySet = new HashSet<>();
839
        keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
840
        keySet.addAll(lastMonthSaleMarginMap.keySet());
841
        keySet.addAll(lastMonthPendingIncomeMap.keySet());
28795 tejbeer 842
 
31352 amit.gupta 843
        lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
844
            String brand = x.getKey();
845
            float amount = x.getValue().getAmount();
846
            if (!totalAmountMap.containsKey(brand)) {
847
                totalAmountMap.put(brand, 0f);
848
            }
849
            totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
30253 amit.gupta 850
 
31352 amit.gupta 851
        });
30122 amit.gupta 852
 
31352 amit.gupta 853
        lastMonthPendingIncomeMap.entrySet().stream().forEach(x -> {
854
            String brand = x.getKey();
855
            float amount = x.getValue().getAmount();
856
            if (!totalAmountMap.containsKey(brand)) {
857
                totalAmountMap.put(brand, 0f);
858
            }
859
            totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
28795 tejbeer 860
 
31352 amit.gupta 861
        });
28795 tejbeer 862
 
863
 
31352 amit.gupta 864
        Map<Integer, String> monthValueMap = new HashMap<>();
865
        for (int i = 0; i <= 5; i++) {
866
            LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
867
            monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
868
        }
869
        model.addAttribute("month", 0);
870
        model.addAttribute("monthValueMap", monthValueMap);
871
        model.addAttribute("keySet", keySet);
872
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
28795 tejbeer 873
 
31352 amit.gupta 874
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
875
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
876
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
877
        model.addAttribute("status", status);
878
        model.addAttribute("totalAmountMap", totalAmountMap);
28795 tejbeer 879
 
31352 amit.gupta 880
        return "last-month-credited-income";
881
    }
30651 amit.gupta 882
 
31352 amit.gupta 883
    @RequestMapping(value = "/getLastMonthPendingIncome", method = RequestMethod.GET)
884
    public String getLastMonthPendingIncome(HttpServletRequest request, Model model) throws Exception {
30651 amit.gupta 885
 
31352 amit.gupta 886
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
28795 tejbeer 887
 
31352 amit.gupta 888
        LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
889
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
890
        String status = "PENDING";
31170 amit.gupta 891
 
31352 amit.gupta 892
        LOGGER.info("currentStartMonth" + currentStartMonth);
893
        LOGGER.info("currentDate" + currentDate);
28795 tejbeer 894
 
31352 amit.gupta 895
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
896
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
29899 tejbeer 897
 
31352 amit.gupta 898
        Map<String, LastMonthCreditedIncomeModel> lastMonthMarginMap = new HashMap<>();
23786 amit.gupta 899
 
31352 amit.gupta 900
        for (LastMonthCreditedIncomeModel lastMonthPendingIncomeModel : lastMonthPendingIncomeModels) {
28795 tejbeer 901
 
31352 amit.gupta 902
            lastMonthMarginMap.put(lastMonthPendingIncomeModel.getBrand(), lastMonthPendingIncomeModel);
903
        }
904
        LOGGER.info("lastMonthPendingIncomeModel" + lastMonthPendingIncomeModels);
905
        LOGGER.info("lastMonthMarginMap" + lastMonthMarginMap);
906
        model.addAttribute("lastMonthCreditedIncomeModels", lastMonthPendingIncomeModels);
907
        model.addAttribute("lastMonthMarginMap", lastMonthMarginMap);
908
        model.addAttribute("status", status);
28795 tejbeer 909
 
31352 amit.gupta 910
        return "last-month-credited-income";
911
    }
28795 tejbeer 912
 
31352 amit.gupta 913
    @RequestMapping(value = "/getLastMonthImeiWiseIncome", method = RequestMethod.GET)
914
    public String getLastMonthImeiWiseIncome(HttpServletRequest request,
915
                                             @RequestParam(name = "catalogItemId", required = false, defaultValue = "") int catalogItemId,
916
                                             @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
917
            throws Exception {
30053 manish 918
 
31352 amit.gupta 919
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 920
 
31352 amit.gupta 921
        LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
922
        LocalDateTime lastMonthEnd = lastMonthStart.plusMonths(1);
30053 manish 923
 
31352 amit.gupta 924
        HashSet<String> allImeiSet = new LinkedHashSet<>();
925
        HashSet<String> purchaseSet = new LinkedHashSet<>();
926
        HashSet<String> saleSet = new LinkedHashSet<>();
30053 manish 927
 
31352 amit.gupta 928
        List<LastMonthFrontEndImeiModel> lmfi = schemeInOutRepository
929
                .selectLastMonthFrontEndImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart, lastMonthEnd);
930
        List<LastMonthImeiModel> lmpi = schemeInOutRepository.selectLastMonthPurchaseInImei(loginDetails.getFofoId(),
931
                catalogItemId, lastMonthStart, lastMonthEnd);
932
        List<LastMonthImeiModel> lmci = schemeInOutRepository.selectLastMonthCreditedImei(loginDetails.getFofoId(),
933
                catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 934
 
31352 amit.gupta 935
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(YearMonth.of(lastMonthStart.getYear(),
936
                lastMonthStart.getMonth()), loginDetails.getFofoId(), null, catalogItemId);
30053 manish 937
 
31352 amit.gupta 938
        LOGGER.info("lmci {}", lmci);
30053 manish 939
 
31352 amit.gupta 940
        Map<String, Double> lastmonthCategoryUpgradeMargin = schemeInOutRepository
941
                .selectLastMonthCategoryUpgradeMarginByImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart,
942
                        lastMonthEnd)
943
                .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
30053 manish 944
 
31352 amit.gupta 945
        allImeiSet.addAll(lmpi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
946
        allImeiSet.addAll(lmci.stream().map(x -> x.getImei()).collect(Collectors.toList()));
947
        allImeiSet.addAll(lmfi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
948
        allImeiSet.addAll(offerPayoutImeiIncomeModels.stream().map(x -> x.getImei()).collect(Collectors.toList()));
30053 manish 949
 
31352 amit.gupta 950
        List<String> allImeiList = new ArrayList<>(allImeiSet);
30053 manish 951
 
31352 amit.gupta 952
        LOGGER.info("allImeiList" + allImeiList);
953
        LOGGER.info("lmcm" + lastmonthCategoryUpgradeMargin);
30253 amit.gupta 954
 
31352 amit.gupta 955
        List<LastMonthFrontEndImeiModel> lastMonthFrontEndImeis = schemeInOutRepository
956
                .selectLastMonthFrontEndByImei(loginDetails.getFofoId(), allImeiList);
30053 manish 957
 
31352 amit.gupta 958
        List<LastMonthImeiModel> lastMonthPurchaseInImeis = schemeInOutRepository
959
                .selectLastMonthPurchaseInByImei(loginDetails.getFofoId(), allImeiList);
30053 manish 960
 
31352 amit.gupta 961
        List<LastMonthImeiModel> lastMonthCreditedImeis = schemeInOutRepository
962
                .selectLastMonthCreditedByImei(loginDetails.getFofoId(), allImeiList);
963
        List<OfferPayoutImeiIncomeModel> allOfferPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByImei(allImeiList);
30053 manish 964
 
31352 amit.gupta 965
        //Map<String, OfferPayoutImeiIncomeModel> imeisOfferPayoutMap = allOfferPayoutImeiIncomeModels.stream().collect(Collectors.toMap(x->x.getImei(), x->x));
966
        Map<String, Double> imeiWisePendingSaleAmount = lastMonthCreditedImeis.stream()
967
                .filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).collect(Collectors
968
                        .groupingBy(x -> x.getImei(), Collectors.summingDouble(x -> x.getPendingSaleAmount())));
30053 manish 969
 
31352 amit.gupta 970
        allOfferPayoutImeiIncomeModels.stream().forEach(x -> {
971
            if (x.getSaleDate() != null) {
972
                LastMonthImeiModel lastMonthImeiModel = new LastMonthImeiModel(x.getImei(), (float) x.getSalePayout(),
973
                        0, "Addnl Margin", x.getSaleDate(), SchemePayoutStatus.CREDITED);
974
                lastMonthCreditedImeis.add(lastMonthImeiModel);
975
            }
976
            if (x.getGrnDate() != null) {
977
                LastMonthImeiModel lastMonthImeiModel = new LastMonthImeiModel(x.getImei(), (float) x.getPurchasePayout(),
978
                        0, "Booster Payout", x.getGrnDate(), SchemePayoutStatus.CREDITED);
979
                lastMonthPurchaseInImeis.add(lastMonthImeiModel);
980
            }
981
        });
30053 manish 982
 
31352 amit.gupta 983
        Map<String, Map<String, Double>> lastMonthPurchaseInMapPairMap = lastMonthPurchaseInImeis.stream()
984
                .collect(Collectors.groupingBy(x -> x.getImei(),
985
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
986
        Map<String, LocalDate> imeiPurchaseDateMap = lastMonthPurchaseInImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x.getCreateTimeStamp().toLocalDate(), (x, y) -> x));
987
        Map<String, LocalDate> imeiSaleDateMap = lastMonthCreditedImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x.getCreateTimeStamp().toLocalDate(), (x, y) -> x));
988
        Map<String, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
989
                .collect(Collectors.groupingBy(x -> x.getImei(),
990
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
30053 manish 991
 
31352 amit.gupta 992
        // descriptionSet.add("")
993
        purchaseSet.addAll(lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
994
        saleSet.addAll(lastMonthCreditedImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
30053 manish 995
 
31352 amit.gupta 996
        List<String> purchaseList = new ArrayList<>(purchaseSet);
997
        List<String> saleList = new ArrayList<>(saleSet);
30253 amit.gupta 998
 
31352 amit.gupta 999
        Map<String, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
30053 manish 1000
 
31352 amit.gupta 1001
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
30235 tejbeer 1002
 
31352 amit.gupta 1003
            String imei = entry.getKey();
1004
            ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imei,
1005
                    imeiPurchaseDateMap.get(imei), null);
1006
            imeiWiseIncomeMapOfMap.put(imei, modelImeiMap);
1007
            double totalAmount = entry.getValue().entrySet().stream()
1008
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1009
            imeiWiseIncomeMapOfMap.get(imei).setTotalIncome(totalAmount);
1010
        }
31283 amit.gupta 1011
 
31352 amit.gupta 1012
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
1013
            Map<String, Double> descriptionAmountMap = entry.getValue();
1014
            if (!imeiWiseIncomeMapOfMap.containsKey(entry.getKey())) {
1015
                ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(entry.getKey(), null,
1016
                        imeiSaleDateMap.get(entry.getKey()));
1017
                imeiWiseIncomeMapOfMap.put(entry.getKey(), modelImeiMap);
1018
            } else {
1019
                ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(entry.getKey());
1020
                modelImeiMap.setSaleDate(imeiSaleDateMap.get(entry.getKey()));
1021
            }
30053 manish 1022
 
31352 amit.gupta 1023
            double totalAmount = descriptionAmountMap.entrySet().stream()
1024
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1025
            imeiWiseIncomeMapOfMap.get(entry.getKey())
1026
                    .setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(entry.getKey()).getTotalIncome());
1027
        }
30053 manish 1028
 
31352 amit.gupta 1029
        lastMonthFrontEndImeis.stream().forEach(x -> {
1030
            if (imeiWiseIncomeMapOfMap.containsKey(x.getImei())) {
1031
                ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1032
                        .get(x.getImei());
1033
                imeiWiseIncomePairAndMapModel.setTotalIncome(imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getAmount());
1034
                imeiWiseIncomePairAndMapModel.setFrontMargin(x.getAmount());
1035
            }
1036
        });
30053 manish 1037
 
31352 amit.gupta 1038
        //Imeis for pending activation
1039
        lastMonthCreditedImeis.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).forEach(x -> {
1040
            if (!imeiWiseIncomeMapOfMap.containsKey(x.getImei())) {
1041
                ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = new ImeiWiseIncomePairAndMapModel();
1042
                imeiWiseIncomePairAndMapModel.setSerialNumber(x.getImei());
1043
            }
1044
            ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1045
                    .get(x.getImei());
1046
            imeiWiseIncomePairAndMapModel.setSaleDate(x.getCreateTimeStamp().toLocalDate());
1047
            imeiWiseIncomePairAndMapModel.setTotalIncome(x.getPendingSaleAmount() + imeiWiseIncomePairAndMapModel.getTotalIncome());
1048
        });
30053 manish 1049
 
31352 amit.gupta 1050
        model.addAttribute("imeiWisePendingSaleAmount", imeiWisePendingSaleAmount);
1051
        model.addAttribute("month", month);
1052
        model.addAttribute("purchaseList", purchaseList);
1053
        model.addAttribute("saleList", saleList);
1054
        model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1055
        model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1056
        model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1057
        model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
1058
        model.addAttribute("allOfferPayoutImeiIncomeModels", allOfferPayoutImeiIncomeModels);
1059
        //model.addAttribute("iimeiSaleDateMap", imeiSaleDateMap);
1060
        //model.addAttribute("imeiPurchaseDateMap", imeiPurchaseDateMap);
30053 manish 1061
 
31352 amit.gupta 1062
        return "last-month-imei-wise-income";
1063
    }
30053 manish 1064
 
31352 amit.gupta 1065
    @RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1066
    public String getBrandWiseIncome(HttpServletRequest request,
1067
                                     @RequestParam(name = "brand", required = false, defaultValue = "") String brand,
1068
                                     @RequestParam(name = "status", required = false, defaultValue = "") String status,
1069
                                     @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
1070
            throws ProfitMandiBusinessException {
1071
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1072
        LOGGER.info("loginDetails {}", loginDetails);
1073
        LOGGER.info("brand" + brand);
1074
        LOGGER.info("month {}", month);
30053 manish 1075
 
31352 amit.gupta 1076
        LocalDateTime monthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1077
        LocalDateTime monthEnd = monthStart.plusMonths(1);
30053 manish 1078
 
31352 amit.gupta 1079
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1080
                YearMonth.of(monthStart.getYear(), monthStart.getMonth()), loginDetails.getFofoId(), brand, null);
1081
        Map<Integer, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getPurchasePayout())));
1082
        Map<Integer, Double> additionalSalePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getSalePayout())));
30053 manish 1083
 
31352 amit.gupta 1084
        boolean partnerTypeUpgraded = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(),
1085
                YearMonth.now());
30053 manish 1086
 
31352 amit.gupta 1087
        LOGGER.info("partnerType" + partnerTypeUpgraded);
30053 manish 1088
 
31352 amit.gupta 1089
        Map<String, Double> categoryUpgradeBrandModelMap = null;
1090
        if (partnerTypeUpgraded) {
1091
            categoryUpgradeBrandModelMap = schemeInOutRepository
1092
                    .selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, monthStart,
1093
                            monthEnd)
1094
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1095
        }
30053 manish 1096
 
31352 amit.gupta 1097
        List<LastMonthFrontEndBrandWiseIncome> modelWiseSalesMargins = schemeInOutRepository
1098
                .selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand, monthStart, monthEnd);
30053 manish 1099
 
31352 amit.gupta 1100
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMargins = schemeInOutRepository
1101
                .selectLastMonthBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1102
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMarginsMap = modelWiseSchemeOutMargins.stream()
1103
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1104
 
31352 amit.gupta 1105
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeInMargins = schemeInOutRepository
1106
                .selectLastMonthPurchaseBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1107
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeInMarginsMap = modelWiseSchemeInMargins.stream()
1108
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1109
 
31352 amit.gupta 1110
        Map<Integer, Double> modelTotalIncomeMap = new HashMap<>();
1111
        Map<Integer, String> modelNameMap = new HashMap<>();
30053 manish 1112
 
31352 amit.gupta 1113
        offerPayoutImeiIncomeModels.stream().forEach(x -> {
1114
            if (!modelTotalIncomeMap.containsKey(x.getCatalogId())) {
1115
                modelNameMap.put(x.getCatalogId(), (x.getModelNumber() + " " + x.getModelName()).trim());
1116
                modelTotalIncomeMap.put(x.getCatalogId(), 0d);
1117
            }
1118
            modelTotalIncomeMap.put(x.getCatalogId(), modelTotalIncomeMap.get(x.getCatalogId()) + x.getPurchasePayout() + x.getSalePayout());
30253 amit.gupta 1119
 
31352 amit.gupta 1120
        });
30053 manish 1121
 
31352 amit.gupta 1122
        modelWiseSchemeOutMargins.stream().forEach(x -> {
1123
            if (!modelNameMap.containsKey(x.getCatalogItemId())) {
1124
                modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
1125
                modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + " " + x.getModelName()).trim());
1126
            }
1127
            modelTotalIncomeMap.put(x.getCatalogItemId(), modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount() + x.getPendingSaleAmount());
30053 manish 1128
 
31352 amit.gupta 1129
        });
30053 manish 1130
 
31352 amit.gupta 1131
        LastMonthBrandWiseIncomeModel totalModel = new LastMonthBrandWiseIncomeModel();
1132
        modelWiseSalesMargins.stream().forEach(x -> {
1133
            if (!modelWiseSchemeOutMarginsMap.containsKey(x.getCatalogItemId())) {
1134
                LastMonthBrandWiseIncomeModel lmbwIncomeModel = new LastMonthBrandWiseIncomeModel();
1135
                lmbwIncomeModel.setModelName(x.getModelName());
1136
                lmbwIncomeModel.setModelNumber(x.getModelNumber());
1137
                lmbwIncomeModel.setBrand(x.getBrand());
1138
                lmbwIncomeModel.setCatalogItemId(x.getCatalogItemId());
1139
                modelWiseSchemeOutMarginsMap.put(x.getCatalogItemId(), lmbwIncomeModel);
1140
                totalModel.setQty(totalModel.getQty() + x.getQty());
1141
            }
1142
            modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
1143
            LOGGER.info("Modelname {}, Model {}", modelNameMap.get(x.getCatalogItemId()), x.getQty());
1144
            LastMonthBrandWiseIncomeModel lmbwIncomeModel = modelWiseSchemeOutMarginsMap.get(x.getCatalogItemId());
30053 manish 1145
 
31352 amit.gupta 1146
            lmbwIncomeModel.setAmount(lmbwIncomeModel.getAmount() + x.getAmount());
1147
            lmbwIncomeModel.setQty(x.getQty());
1148
            if (!modelTotalIncomeMap.containsKey(x.getCatalogItemId())) {
1149
                modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
1150
            }
1151
            modelTotalIncomeMap.put(x.getCatalogItemId(), x.getAmount() + modelTotalIncomeMap.get(x.getCatalogItemId()));
1152
            totalModel.setAmount(totalModel.getAmount() + x.getAmount());
1153
            totalModel.setPendingSaleAmount(totalModel.getPendingSaleAmount());
30253 amit.gupta 1154
 
31352 amit.gupta 1155
        });
1156
        modelWiseSchemeInMargins.stream().forEach(x -> {
1157
            if (!modelTotalIncomeMap.containsKey(x.getCatalogItemId())) {
1158
                modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
1159
            }
1160
            modelTotalIncomeMap.put(x.getCatalogItemId(),
1161
                    modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount());
1162
            modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
1163
            totalModel.setQty(totalModel.getQty() + x.getQty());
1164
            totalModel.setAmount(totalModel.getAmount() + x.getAmount());
30253 amit.gupta 1165
 
31352 amit.gupta 1166
        });
30253 amit.gupta 1167
 
31352 amit.gupta 1168
        model.addAttribute("month", month);
1169
        model.addAttribute("modelWiseSchemeOutMarginsMap", modelWiseSchemeOutMarginsMap);
1170
        model.addAttribute("modelWiseSchemeInMarginsMap", modelWiseSchemeInMarginsMap);
1171
        model.addAttribute("modelNameMap", modelNameMap);
1172
        model.addAttribute("modelTotalIncomeMap", modelTotalIncomeMap);
1173
        model.addAttribute("categoryUpgradeBrandModelMap", categoryUpgradeBrandModelMap);
1174
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
1175
        model.addAttribute("additionalSalePayoutMap", additionalSalePayout);
1176
        model.addAttribute("totalModel", totalModel);
30253 amit.gupta 1177
 
31352 amit.gupta 1178
        return "monthly-brand-wise-income";
30053 manish 1179
 
31352 amit.gupta 1180
    }
30053 manish 1181
 
31352 amit.gupta 1182
    @RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
1183
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
1184
            throws ProfitMandiBusinessException {
1185
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30253 amit.gupta 1186
 
31352 amit.gupta 1187
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1188
        LocalDateTime lastMonthEnd = startOfMonth.plusMonths(1);
30253 amit.gupta 1189
 
31352 amit.gupta 1190
        YearMonth monthYear = YearMonth.now();
30053 manish 1191
 
31352 amit.gupta 1192
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
30053 manish 1193
 
31352 amit.gupta 1194
        LOGGER.info("partnerType" + partnerType);
30053 manish 1195
 
31352 amit.gupta 1196
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
30053 manish 1197
 
31352 amit.gupta 1198
        if (partnerType) {
1199
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1200
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), startOfMonth,
1201
                            lastMonthEnd)
1202
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1203
        }
30053 manish 1204
 
31352 amit.gupta 1205
        String status = "CREDITED";
30053 manish 1206
 
31352 amit.gupta 1207
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1208
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30053 manish 1209
 
31352 amit.gupta 1210
        List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
1211
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1212
 
31352 amit.gupta 1213
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1214
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1215
 
31352 amit.gupta 1216
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1217
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1218
 
31352 amit.gupta 1219
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1220
                YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()), loginDetails.getFofoId(), null, null);
30235 tejbeer 1221
 
31352 amit.gupta 1222
        Map<String, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getPurchasePayout)));
1223
        Map<String, Double> additionSalePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getSalePayout)));
30235 tejbeer 1224
 
1225
 
31352 amit.gupta 1226
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
1227
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1228
 
31352 amit.gupta 1229
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
1230
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1231
 
1232
 
31352 amit.gupta 1233
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = lastMonthPendingIncomeModels.stream()
1234
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1235
 
31352 amit.gupta 1236
        lastMonthFrontEndIncomes.stream().forEach(x -> {
1237
            if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
1238
                x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
30053 manish 1239
 
31352 amit.gupta 1240
                lastMonthSaleMarginMap.put(x.getBrand(), x);
1241
            } else {
1242
                lastMonthSaleMarginMap.put(x.getBrand(), x);
1243
            }
30053 manish 1244
 
31352 amit.gupta 1245
        });
1246
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1247
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1248
        Set<String> brandSet = new HashSet<>();
1249
        brandSet.addAll(lastMonthPurchaseInMarginMap.keySet());
1250
        brandSet.addAll(lastMonthSaleMarginMap.keySet());
1251
        brandSet.addAll(lastMonthPendingIncomeMap.keySet());
1252
        brandSet.addAll(additionalPurchasePayout.keySet());
1253
        brandSet.addAll(additionSalePayout.keySet());
1254
        brandSet.stream().forEach(brand -> {
1255
            totalAmountMap.put(brand,
1256
                    (lastMonthSaleMarginMap.get(brand) == null ? 0 : lastMonthSaleMarginMap.get(brand).getAmount()) +
1257
                            (lastMonthPurchaseInMarginMap.get(brand) == null ? 0 : lastMonthPurchaseInMarginMap.get(brand).getAmount()) +
1258
                            (lastMonthPendingIncomeMap.get(brand) == null ? 0 : lastMonthPendingIncomeMap.get(brand).getAmount()) +
1259
                            (additionalPurchasePayout.get(brand) == null ? 0 : additionalPurchasePayout.get(brand).longValue()) +
1260
                            (additionSalePayout.get(brand) == null ? 0 : additionSalePayout.get(brand).longValue())
1261
            );
1262
        });
30053 manish 1263
 
31352 amit.gupta 1264
        Map<Integer, String> monthValueMap = new HashMap<>();
1265
        for (int i = 0; i <= 5; i++) {
1266
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1267
            monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
1268
        }
1269
        model.addAttribute("monthValueMap", monthValueMap);
30053 manish 1270
 
31352 amit.gupta 1271
        model.addAttribute("keySet", brandSet);
1272
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1273
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1274
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
1275
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
1276
        model.addAttribute("additionalSalePayoutMap", additionSalePayout);
30053 manish 1277
 
31352 amit.gupta 1278
        model.addAttribute("totalAmountMap", totalAmountMap);
1279
        model.addAttribute("status", status);
1280
        model.addAttribute("month", yearMonth);
1281
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1282
        LOGGER.info("totalAmountMap {}", totalAmountMap);
1283
        LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
30253 amit.gupta 1284
 
31352 amit.gupta 1285
        return "last-month-credited-income";
1286
    }
30253 amit.gupta 1287
 
31352 amit.gupta 1288
    @RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
1289
    public String downloadPage(HttpServletRequest request, Model model) {
1290
        return "schemes-download";
1291
    }
30253 amit.gupta 1292
 
31352 amit.gupta 1293
    @RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
1294
    public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
1295
                                                                  @RequestParam LocalDateTime startDateTime, @RequestParam LocalDateTime endDateTime)
1296
            throws ProfitMandiBusinessException {
30253 amit.gupta 1297
 
31352 amit.gupta 1298
        List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
31334 amit.gupta 1299
 
31352 amit.gupta 1300
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1301
        ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
30253 amit.gupta 1302
 
31352 amit.gupta 1303
        final HttpHeaders headers = new HttpHeaders();
1304
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
1305
        headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
1306
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1307
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1308
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1309
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1310
    }
30053 manish 1311
 
31352 amit.gupta 1312
    @RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
1313
    public String getSchemeById(HttpServletRequest request,
1314
                                @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
1315
            throws ProfitMandiBusinessException {
1316
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 1317
 
31352 amit.gupta 1318
        boolean fullAccess = this.getAccess(loginDetails.getEmailId());
1319
        Scheme scheme = schemeService.getSchemeById(schemeId);
1320
        model.addAttribute("fullAccess", fullAccess);
1321
        model.addAttribute("scheme", scheme);
1322
        model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
1323
        return "scheme-details";
1324
    }
30053 manish 1325
 
31352 amit.gupta 1326
    @RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
1327
    public String activeSchemeById(@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1328
                                   @RequestParam(name = "offset", defaultValue = "0") int offset,
1329
                                   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1330
            throws ProfitMandiBusinessException {
1331
        schemeService.activeSchemeById(schemeId);
1332
        List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
1333
        for (Scheme scheme : schemes) {
1334
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1335
                scheme.setAmountModel(scheme.getAmount() + "%");
1336
            } else {
1337
                scheme.setAmountModel(scheme.getAmount() + "");
1338
            }
1339
        }
1340
        return "schemes";
1341
    }
30053 manish 1342
 
31352 amit.gupta 1343
    @RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
1344
    public String expireSchemeById(HttpServletRequest request,
1345
                                   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1346
                                   @RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp, Model model)
1347
            throws ProfitMandiBusinessException {
1348
        schemeService.expireSchemeById(schemeId, expiryTimestamp);
1349
        return getDefaultSchemes(request, model);
1350
    }
30053 manish 1351
 
31352 amit.gupta 1352
    @RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
1353
    public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
1354
                                            @RequestParam(name = "offset", defaultValue = "0") int offset,
1355
                                            @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1356
            throws ProfitMandiBusinessException {
1357
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1358
        return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1359
    }
30053 manish 1360
 
31352 amit.gupta 1361
    @RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1362
    public String getCustomerOffer(HttpServletRequest request,
1363
                                   @RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel, Model model)
1364
            throws ProfitMandiBusinessException {
1365
        List<CustomerOffer> customerOffers = null;
1366
        if (searchModel > 0) {
30053 manish 1367
 
31352 amit.gupta 1368
            Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
1369
            customerOffers = customerOfferRepository.selectActiveOfferByModel(searchModel, LocalDate.now());
1370
            model.addAttribute("modelName", item.getItemDescriptionNoColor());
1371
        } else {
1372
            customerOffers = customerOfferRepository.selectAll();
1373
        }
30053 manish 1374
 
31352 amit.gupta 1375
        LOGGER.info("customerOffers" + customerOffers);
30053 manish 1376
 
31352 amit.gupta 1377
        for (CustomerOffer customerOffer : customerOffers) {
30053 manish 1378
 
31352 amit.gupta 1379
            LOGGER.info("ss" + searchModel);
30053 manish 1380
 
31352 amit.gupta 1381
            if (!StringUtils.isEmpty(customerOffer.getPartnerCriteria())) {
1382
                String partnerCriteria = retailerService.getPartnerCriteriaString(
1383
                        gson.fromJson(customerOffer.getPartnerCriteria(), PartnerCriteria.class));
1384
                customerOffer.setPartnerCriteriaString(partnerCriteria);
1385
            }
30053 manish 1386
 
31352 amit.gupta 1387
        }
30053 manish 1388
 
31352 amit.gupta 1389
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1390
                .collect(Collectors.toList());
31281 amit.gupta 1391
 
31352 amit.gupta 1392
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30053 manish 1393
 
31352 amit.gupta 1394
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1395
                .filter(x -> x != null).collect(Collectors.toList()).stream()
1396
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30053 manish 1397
 
31352 amit.gupta 1398
        model.addAttribute("customRetailersMap", customRetailersMap);
1399
        model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
1400
        model.addAttribute("searchModel", searchModel);
30053 manish 1401
 
31352 amit.gupta 1402
        model.addAttribute("customerOffers", customerOffers);
1403
        return "customer-offer";
30053 manish 1404
 
31352 amit.gupta 1405
    }
30053 manish 1406
 
31352 amit.gupta 1407
    @RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1408
    public String createCustomerOffer(HttpServletRequest request, @RequestBody CustomerOfferModel customerOfferModel,
1409
                                      Model model) throws Exception {
30053 manish 1410
 
31352 amit.gupta 1411
        CustomerOffer co = new CustomerOffer();
1412
        co.setOfferName(customerOfferModel.getOfferName());
1413
        co.setStartDate(customerOfferModel.getStartDate());
1414
        co.setEndDate(customerOfferModel.getEndDate());
1415
        co.setPartnerCriteria(gson.toJson(customerOfferModel.getPartnerCriteria()));
1416
        co.setCreatedTimestamp(LocalDateTime.now());
1417
        co.setUpdatedTimestamp(LocalDateTime.now());
1418
        customerOfferRepository.persist(co);
31281 amit.gupta 1419
 
31352 amit.gupta 1420
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31281 amit.gupta 1421
 
31352 amit.gupta 1422
        return "response";
30053 manish 1423
 
31352 amit.gupta 1424
    }
30053 manish 1425
 
31352 amit.gupta 1426
    @RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1427
    public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1428
        List<List<?>> rows = new ArrayList<>();
30053 manish 1429
 
31352 amit.gupta 1430
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("id",
1431
                        "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date (dd-mm-yyyy)", "End Date (dd-mm-yyyy)"),
1432
                rows);
30053 manish 1433
 
31352 amit.gupta 1434
        final HttpHeaders headers = new HttpHeaders();
1435
        headers.set("Content-Type", "text/csv");
1436
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1437
        headers.setContentLength(baos.toByteArray().length);
30053 manish 1438
 
31352 amit.gupta 1439
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1440
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1441
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
30053 manish 1442
 
31352 amit.gupta 1443
    }
30053 manish 1444
 
31352 amit.gupta 1445
    @RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1446
    public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
1447
                                          HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
23786 amit.gupta 1448
 
31352 amit.gupta 1449
        List<CSVRecord> records = FileUtil.readFile(file);
1450
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
23914 govind 1451
 
31352 amit.gupta 1452
        CustomerOffer customerOffer = customerOfferRepository.selectById(offerId);
1453
        List<Integer> catalogIds = new ArrayList<>();
1454
        for (CSVRecord record : records) {
23786 amit.gupta 1455
 
31352 amit.gupta 1456
            CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
23786 amit.gupta 1457
 
31352 amit.gupta 1458
            if (coi == null) {
1459
                coi = new CustomerOfferItem();
1460
                coi.setCatalogId(Integer.parseInt(record.get(1)));
1461
                coi.setSchemePayout(Integer.parseInt(record.get(2)));
1462
                coi.setDealerPayout(Integer.parseInt(record.get(3)));
1463
                coi.setCustomerOfferId(offerId);
1464
                coi.setCreatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1465
 
31352 amit.gupta 1466
                customerOfferItemRepository.persist(coi);
29899 tejbeer 1467
 
31352 amit.gupta 1468
            }
1469
            coi.setSchemePayout(Integer.parseInt(record.get(2)));
1470
            coi.setDealerPayout(Integer.parseInt(record.get(3)));
1471
            coi.setCustomerOfferId(offerId);
1472
            coi.setUpdatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1473
 
31352 amit.gupta 1474
            LOGGER.info(record.get(4));
23786 amit.gupta 1475
 
31352 amit.gupta 1476
            LocalDate startDate = LocalDate.parse(record.get(4), formatter);
1477
            LocalDate endDate = LocalDate.parse(record.get(5), formatter);
23786 amit.gupta 1478
 
31352 amit.gupta 1479
            if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1480
                    || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1481
                    && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1482
                    || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1483
                coi.setStartDate(startDate);
26802 tejbeer 1484
 
31352 amit.gupta 1485
            } else {
29707 tejbeer 1486
 
31352 amit.gupta 1487
                catalogIds.add(coi.getCatalogId());
1488
            }
29707 tejbeer 1489
 
31352 amit.gupta 1490
            if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1491
                    || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1492
                    && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1493
                    || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1494
 
31352 amit.gupta 1495
                coi.setEndDate(endDate);
31147 tejbeer 1496
 
31352 amit.gupta 1497
            } else {
1498
                catalogIds.add(coi.getCatalogId());
1499
            }
31147 tejbeer 1500
 
31352 amit.gupta 1501
        }
31147 tejbeer 1502
 
31352 amit.gupta 1503
        if (!catalogIds.isEmpty()) {
1504
            throw new ProfitMandiBusinessException("Please set accurate start and end date", catalogIds,
1505
                    "Please set accurate start and end date");
1506
        }
1507
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1508
 
31352 amit.gupta 1509
        return "response";
31147 tejbeer 1510
 
31352 amit.gupta 1511
    }
31147 tejbeer 1512
 
31352 amit.gupta 1513
    @RequestMapping(value = "/addCustomerOfferItem", method = RequestMethod.POST)
1514
    public String addCustomerOfferItem(HttpServletRequest request,
1515
                                       @RequestBody CustomerOfferItemModel customerOfferItemModel, Model model) throws Throwable {
31147 tejbeer 1516
 
31352 amit.gupta 1517
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItemModel.getOfferId());
31147 tejbeer 1518
 
31352 amit.gupta 1519
        if (!(customerOffer.getEndDate().toLocalDate().equals(LocalDate.now()))
1520
                && customerOffer.getEndDate().isBefore(LocalDateTime.now())) {
1521
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(), "Offer is Expired");
29707 tejbeer 1522
 
31352 amit.gupta 1523
        }
29707 tejbeer 1524
 
31352 amit.gupta 1525
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
1526
                .selectByOfferAndCatalogId(customerOfferItemModel.getOfferId(), customerOfferItemModel.getCatalogId());
29707 tejbeer 1527
 
31352 amit.gupta 1528
        if (!customerOfferItems.isEmpty()) {
29707 tejbeer 1529
 
31352 amit.gupta 1530
            for (CustomerOfferItem coi : customerOfferItems) {
1531
                if (!(coi.getEndDate().equals(LocalDate.now())) && coi.getEndDate().isAfter(LocalDate.now())) {
1532
                    throw new ProfitMandiBusinessException("Catalog Id", coi.getCatalogId(), "Item is already exist.");
1533
                }
1534
            }
29707 tejbeer 1535
 
31352 amit.gupta 1536
        }
29707 tejbeer 1537
 
31352 amit.gupta 1538
        LocalDate startDate = customerOfferItemModel.getStartDate().toLocalDate();
1539
        LocalDate endDate = customerOfferItemModel.getEndDate().toLocalDate();
1540
        CustomerOfferItem coi = new CustomerOfferItem();
1541
        coi.setCatalogId(customerOfferItemModel.getCatalogId());
1542
        coi.setSchemePayout(customerOfferItemModel.getSchemePayout());
1543
        coi.setDealerPayout(customerOfferItemModel.getDealerPayout());
1544
        coi.setCustomerOfferId(customerOfferItemModel.getOfferId());
1545
        coi.setUpdatedTimestamp(LocalDateTime.now());
1546
        coi.setCreatedTimestamp(LocalDateTime.now());
29707 tejbeer 1547
 
31352 amit.gupta 1548
        if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1549
                || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1550
                && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1551
                || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 1552
 
31352 amit.gupta 1553
            coi.setStartDate(startDate);
29707 tejbeer 1554
 
31352 amit.gupta 1555
        } else {
29707 tejbeer 1556
 
31352 amit.gupta 1557
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1558
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1559
                            + customerOffer.getEndDate());
29707 tejbeer 1560
 
31352 amit.gupta 1561
        }
29707 tejbeer 1562
 
31352 amit.gupta 1563
        if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1564
                || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1565
                && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1566
                || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 1567
 
31352 amit.gupta 1568
            coi.setEndDate(endDate);
29707 tejbeer 1569
 
31352 amit.gupta 1570
        } else {
1571
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1572
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1573
                            + customerOffer.getEndDate());
1574
        }
31147 tejbeer 1575
 
31352 amit.gupta 1576
        customerOfferItemRepository.persist(coi);
31147 tejbeer 1577
 
31352 amit.gupta 1578
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1579
 
31352 amit.gupta 1580
        return "response";
29707 tejbeer 1581
 
31352 amit.gupta 1582
    }
31147 tejbeer 1583
 
31352 amit.gupta 1584
    @RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1585
    public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
31147 tejbeer 1586
 
31352 amit.gupta 1587
        List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1588
        List<List<?>> rows = new ArrayList<>();
1589
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
31147 tejbeer 1590
 
31352 amit.gupta 1591
        for (CustomerOfferItem coi : cois) {
1592
            rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout(),
1593
                    coi.getStartDate().format(formatter), coi.getEndDate().format(formatter)));
31147 tejbeer 1594
 
31352 amit.gupta 1595
        }
31147 tejbeer 1596
 
31352 amit.gupta 1597
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1598
                Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date", "End Date"), rows);
29707 tejbeer 1599
 
31352 amit.gupta 1600
        final HttpHeaders headers = new HttpHeaders();
1601
        headers.set("Content-Type", "text/csv");
1602
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1603
        headers.setContentLength(baos.toByteArray().length);
31147 tejbeer 1604
 
31352 amit.gupta 1605
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1606
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1607
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
31147 tejbeer 1608
 
31352 amit.gupta 1609
    }
31147 tejbeer 1610
 
31352 amit.gupta 1611
    @RequestMapping(value = "/getCustomerOfferItem", method = RequestMethod.GET)
1612
    public String getCustomerOfferItem(HttpServletRequest request, @RequestParam int offerId, Model model)
1613
            throws Exception {
29707 tejbeer 1614
 
31352 amit.gupta 1615
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository.selectByOfferId(offerId);
1616
        List<Integer> catalogIds = customerOfferItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
29707 tejbeer 1617
 
31352 amit.gupta 1618
        Map<Integer, List<Item>> catalogItemMap = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds))
1619
                .stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
29707 tejbeer 1620
 
31352 amit.gupta 1621
        model.addAttribute("catalogItemMap", catalogItemMap);
29707 tejbeer 1622
 
31352 amit.gupta 1623
        model.addAttribute("offerId", offerId);
31147 tejbeer 1624
 
31352 amit.gupta 1625
        model.addAttribute("customerOfferItems", customerOfferItems);
1626
        return "customer-offer-item";
31147 tejbeer 1627
 
31352 amit.gupta 1628
    }
31147 tejbeer 1629
 
31352 amit.gupta 1630
    @RequestMapping(value = "/expiredCustomerOfferItem", method = RequestMethod.POST)
1631
    public String expiredCustomerOfferItem(HttpServletRequest request, @RequestParam int id,
1632
                                           @RequestParam LocalDateTime endDate, Model model) throws Exception {
31147 tejbeer 1633
 
31352 amit.gupta 1634
        CustomerOfferItem customerOfferItem = customerOfferItemRepository.selectById(id);
31147 tejbeer 1635
 
31352 amit.gupta 1636
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItem.getCustomerOfferId());
31147 tejbeer 1637
 
31352 amit.gupta 1638
        if ((endDate.toLocalDate().equals(customerOffer.getStartDate().toLocalDate())
1639
                || endDate.toLocalDate().isAfter(customerOffer.getStartDate().toLocalDate()))
1640
                && (endDate.toLocalDate().isEqual(customerOffer.getEndDate().toLocalDate())
1641
                || endDate.toLocalDate().isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1642
 
31352 amit.gupta 1643
            customerOfferItem.setEndDate(endDate.toLocalDate());
31147 tejbeer 1644
 
31352 amit.gupta 1645
        } else {
1646
            throw new ProfitMandiBusinessException("Date", customerOffer.getOfferName(),
1647
                    "customer offer expired on " + customerOffer.getEndDate());
1648
        }
1649
        Map<Integer, List<Item>> catalogItemMap = itemRepository
1650
                .selectAllByCatalogItemId(customerOfferItem.getCatalogId()).stream()
1651
                .collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
1652
        model.addAttribute("catalogItemMap", catalogItemMap);
31147 tejbeer 1653
 
31352 amit.gupta 1654
        model.addAttribute("coi", customerOfferItem);
31147 tejbeer 1655
 
31352 amit.gupta 1656
        return "customer-offer-item-index";
31147 tejbeer 1657
 
31352 amit.gupta 1658
    }
31147 tejbeer 1659
 
31352 amit.gupta 1660
    @RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1661
    public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
1662
                                      @RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 1663
 
31352 amit.gupta 1664
        CustomerOffer co = customerOfferRepository.selectById(id);
1665
        co.setEndDate(endDate);
1666
        co.setUpdatedTimestamp(LocalDateTime.now());
31147 tejbeer 1667
 
31352 amit.gupta 1668
        model.addAttribute("co", co);
31147 tejbeer 1669
 
31352 amit.gupta 1670
        return "customer-index-offer";
31147 tejbeer 1671
 
31352 amit.gupta 1672
    }
31147 tejbeer 1673
 
31352 amit.gupta 1674
    @RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1675
    public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 1676
 
31352 amit.gupta 1677
        List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1678
        List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1679
                uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
31147 tejbeer 1680
 
31352 amit.gupta 1681
        model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1682
        return "samsung-upgrade-offer";
31147 tejbeer 1683
 
31352 amit.gupta 1684
    }
31147 tejbeer 1685
 
31352 amit.gupta 1686
    @RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1687
    public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1688
            throws ProfitMandiBusinessException {
29707 tejbeer 1689
 
31352 amit.gupta 1690
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1691
        suo.setStatus(UpgradeOfferStatus.approved);
1692
        suo.setApprovedTimestamp(LocalDateTime.now());
1693
        model.addAttribute("suo", suo);
1694
        return "samsung-upgrade-offer-index";
29707 tejbeer 1695
 
31352 amit.gupta 1696
    }
29707 tejbeer 1697
 
31352 amit.gupta 1698
    @RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1699
    public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1700
            throws ProfitMandiBusinessException {
29707 tejbeer 1701
 
31352 amit.gupta 1702
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1703
        suo.setStatus(UpgradeOfferStatus.rejected);
29707 tejbeer 1704
 
31352 amit.gupta 1705
        model.addAttribute("suo", suo);
1706
        return "samsung-upgrade-offer-index";
29707 tejbeer 1707
 
31352 amit.gupta 1708
    }
29707 tejbeer 1709
 
22860 ashik.ali 1710
}