Subversion Repositories SmartDukaan

Rev

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

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