Subversion Repositories SmartDukaan

Rev

Rev 31383 | Rev 31482 | 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()));
627
                Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
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()
634
                        .filter(x -> {
635
                            return (x.getId() != 411 && x.getId() != 612) || date1.isBefore(LocalDate.of(2021, 12, 1));
636
                        }).collect(Collectors.toList());
637
                // Remove 411 and 612
638
                // this.setSchemeAmountModel(schemes);
639
                int nlc = this.getNlc(item, loginDetails.getFofoId(), schemes, tagListing);
640
                // For 7720(HR) remove investment
641
                model.addAttribute("schemes", schemes);
642
                model.addAttribute("nlc", Math.round(nlc));
29608 amit.gupta 643
 
31352 amit.gupta 644
                Map<Integer, Map<Integer, Long>> offerSlabPayoutMap = new HashMap<>();
645
                List<CreateOfferRequest> offers = offerService.getPublishedOffers(date, loginDetails.getFofoId(),
646
                        searchModel);
647
                if (offers.size() > 0) {
648
                    for (CreateOfferRequest createOfferRequest : offers) {
649
                        Map<Integer, Map<Integer, Long>> catalogSlabPayoutMap = offerService
650
                                .getSlabPayoutMap(createOfferRequest);
651
                        Map<Integer, Long> slabPayoutMap = catalogSlabPayoutMap.get(searchModel);
652
                        offerSlabPayoutMap.put(createOfferRequest.getId(), slabPayoutMap);
653
                    }
654
                    model.addAttribute("offers", offers);
655
                    model.addAttribute("offerSlabPayoutMap", offerSlabPayoutMap);
29608 amit.gupta 656
 
31352 amit.gupta 657
                    LOGGER.info("offer");
658
                }
659
                FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
660
                model.addAttribute("partnerCode", fs.getCode());
661
                model.addAttribute("fofoId", fs.getId());
29585 manish 662
 
31352 amit.gupta 663
                return "schemes-partner";
29608 amit.gupta 664
 
31352 amit.gupta 665
            }
29608 amit.gupta 666
 
31352 amit.gupta 667
        } else if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
29608 amit.gupta 668
 
31352 amit.gupta 669
            LOGGER.info("searchImei" + searchImei);
29608 amit.gupta 670
 
31352 amit.gupta 671
            InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
672
                    loginDetails.getFofoId());
673
            Item item = itemRepository.selectById(inventoryItem.getItemId());
674
            Map<Integer, Scheme> schemeMap = new HashMap<>();
675
            double netEarnings = 0;
676
            if (inventoryItem != null) {
677
                // Offer payout
678
                List<OfferPayout> offerPayouts = offerPayoutRepository.selectAllBySerialNumber(loginDetails.getFofoId(),
679
                        searchImei);
680
                Map<Integer, CreateOfferRequest> offerRequestMap = offerPayouts.stream()
681
                        .map(x -> offerService.getOffer(loginDetails.getFofoId(), (int) x.getOfferId()))
682
                        .collect(Collectors.toMap(x -> x.getId(), x -> x));
29608 amit.gupta 683
 
31352 amit.gupta 684
                schemeInOuts = schemeInOutRepository
685
                        .selectByInventoryItemIds(new HashSet<>(Arrays.asList(inventoryItem.getId())));
25256 amit.gupta 686
 
31352 amit.gupta 687
                if (!schemeInOuts.isEmpty()) {
688
                    netEarnings += schemeInOuts.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.CREDITED))
689
                            .collect(Collectors.summingDouble(x -> x.getAmount()));
690
                    List<Integer> schemeIds = schemeInOuts.stream().map(x -> x.getSchemeId())
691
                            .collect(Collectors.toList());
23914 govind 692
 
31352 amit.gupta 693
                    schemes = schemeRepository.selectBySchemeIds(schemeIds);
694
                    for (Scheme scheme : schemes) {
695
                        if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
696
                            scheme.setAmountModel(scheme.getAmount() + "%");
697
                        } else {
698
                            scheme.setAmountModel(scheme.getAmount() + "");
699
                        }
700
                    }
23914 govind 701
 
31352 amit.gupta 702
                    schemeMap = schemes.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
703
                }
704
                List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
705
                        .selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
706
                if (priceDropImeis.size() > 0) {
23914 govind 707
 
31352 amit.gupta 708
                    for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
709
                        int priceDropId = priceDropIMEI.getPriceDropId();
710
                        PriceDrop pd = priceDropRepository.selectById(priceDropId);
711
                        priceDropIMEI.setPriceDrop(pd);
712
                    }
713
                    model.addAttribute("priceDropImeis", priceDropImeis);
714
                }
715
                netEarnings += offerPayouts.stream().collect(Collectors.summingDouble(x -> x.getAmount()));
716
                model.addAttribute("offerPayouts", offerPayouts);
717
                model.addAttribute("offerRequestMap", offerRequestMap);
718
                model.addAttribute("inventoryItem", inventoryItem);
719
                model.addAttribute("inventoryItem", inventoryItem);
23914 govind 720
 
31352 amit.gupta 721
            }
722
            model.addAttribute("netEarnings", netEarnings);
723
            model.addAttribute("fofoId", loginDetails.getFofoId());
724
            model.addAttribute("schemeMap", schemeMap);
725
            model.addAttribute("item", item);
726
            model.addAttribute("schemeInOut", schemeInOuts);
727
            return "schemes-partner";
728
        }
31170 amit.gupta 729
 
31352 amit.gupta 730
        if (isAdmin) {
731
            schemes = schemeRepository.selectAll(0, 100);
732
            this.setSchemeAmountModel(schemes);
733
            List<SchemeRegion> schemeRegionList = schemeRegionRepository.selectAllBySchemeIds(schemes.stream().map(x -> x.getId()).collect(Collectors.toList()));
734
            Map<Integer, String> schemeRegionMap = schemeRegionList.stream().collect(Collectors.groupingBy(x -> x.getSchemeId(), Collectors.mapping(y -> regionRepository.selectById(y.getRegionId()).getName(), Collectors.joining(","))));
735
            model.addAttribute("schemes", schemes);
736
            model.addAttribute("schemeRegionMap", schemeRegionMap);
31170 amit.gupta 737
 
31352 amit.gupta 738
            return "schemes";
739
        } else {
740
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(searchImei)) {
741
                InventoryItem inventoryItem = inventoryItemRepository.selectBySerialNumberFofoId(searchImei,
742
                        loginDetails.getFofoId());
743
                List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository
744
                        .selectByFofoIdImei(loginDetails.getFofoId(), searchImei);
745
                if (priceDropImeis.size() > 0) {
31170 amit.gupta 746
 
31352 amit.gupta 747
                    for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
748
                        int priceDropId = priceDropIMEI.getPriceDropId();
749
                        PriceDrop pd = priceDropRepository.selectById(priceDropId);
750
                        priceDropIMEI.setPriceDrop(pd);
751
                    }
752
                    model.addAttribute("priceDropImeis", priceDropImeis);
753
                }
754
            }
755
            FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
756
            model.addAttribute("partnerCode", fs.getCode());
757
            model.addAttribute("fofoId", fs.getId());
758
            return "schemes-partner";
759
        }
23914 govind 760
 
31352 amit.gupta 761
    }
23786 amit.gupta 762
 
31352 amit.gupta 763
    private int getNlc(Item item, int fofoId, List<Scheme> schemes, TagListing tagListing) {
764
        if (item.getBrand().equals("Vivo") && fofoStoreRepository.getWarehousePartnerMap().get(7720).stream()
765
                .filter(x -> x.getId() == fofoId).count() > 0) {
766
            schemes = schemes.stream().filter(x -> !x.getType().equals(SchemeType.INVESTMENT))
767
                    .collect(Collectors.toList());
768
        }
769
        float nlc = tagListing.getSellingPrice();
770
        for (Scheme scheme : schemes) {
771
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
772
                if (tagListing != null) {
773
                    float amount = tagListing.getSellingPrice() * scheme.getAmount() / 100;
774
                    scheme.setAmountModel(FormattingUtils.formatDecimal(amount) + " (" + scheme.getAmount() + "%)");
775
                    nlc -= amount;
776
                } else {
777
                    scheme.setAmountModel(scheme.getAmount() + "%");
778
                }
779
            } else {
780
                scheme.setAmountModel(scheme.getAmount() + "");
781
                nlc -= scheme.getAmount();
782
            }
783
        }
23819 govind 784
 
31352 amit.gupta 785
        return Math.round(nlc);
23914 govind 786
 
31352 amit.gupta 787
    }
29899 tejbeer 788
 
31352 amit.gupta 789
    @RequestMapping(value = "/getLastMonthCreditIncome", method = RequestMethod.GET)
790
    public String getLastMonthCreditIncome(HttpServletRequest request, Model model) throws Exception {
30122 amit.gupta 791
 
31352 amit.gupta 792
        String status = "CREDITED";
793
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
23786 amit.gupta 794
 
31352 amit.gupta 795
        LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
796
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
31170 amit.gupta 797
 
31352 amit.gupta 798
        YearMonth yearMonth = YearMonth.now();
799
        LOGGER.info("yearMonth" + yearMonth);
31170 amit.gupta 800
 
31352 amit.gupta 801
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), yearMonth);
31170 amit.gupta 802
 
31352 amit.gupta 803
        LOGGER.info("partnerType" + partnerType);
31170 amit.gupta 804
 
31352 amit.gupta 805
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
31170 amit.gupta 806
 
31352 amit.gupta 807
        if (partnerType) {
808
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
809
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), currentStartMonth,
810
                            currentDate)
811
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
812
        }
813
        List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
814
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
31170 amit.gupta 815
 
31352 amit.gupta 816
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
817
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
31170 amit.gupta 818
 
31352 amit.gupta 819
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
820
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), currentStartMonth, currentDate);
26802 tejbeer 821
 
31352 amit.gupta 822
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = schemeInOutRepository
823
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate).stream()
824
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
28796 tejbeer 825
 
31352 amit.gupta 826
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = new HashMap<>();
29608 amit.gupta 827
 
31352 amit.gupta 828
        lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
829
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
29608 amit.gupta 830
 
31352 amit.gupta 831
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
832
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30274 amit.gupta 833
 
31352 amit.gupta 834
        lastMonthFrontEndIncomes.stream().forEach(x -> {
835
            if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
836
                x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
837
                lastMonthSaleMarginMap.put(x.getBrand(), x);
838
            } else {
839
                lastMonthSaleMarginMap.put(x.getBrand(), x);
840
            }
30274 amit.gupta 841
 
31352 amit.gupta 842
        });
843
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
844
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
30274 amit.gupta 845
 
31352 amit.gupta 846
        Set<String> keySet = new HashSet<>();
847
        keySet.addAll(lastMonthPurchaseInMarginMap.keySet());
848
        keySet.addAll(lastMonthSaleMarginMap.keySet());
849
        keySet.addAll(lastMonthPendingIncomeMap.keySet());
28795 tejbeer 850
 
31352 amit.gupta 851
        lastMonthPurchaseInMarginMap.entrySet().stream().forEach(x -> {
852
            String brand = x.getKey();
853
            float amount = x.getValue().getAmount();
854
            if (!totalAmountMap.containsKey(brand)) {
855
                totalAmountMap.put(brand, 0f);
856
            }
857
            totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
30253 amit.gupta 858
 
31352 amit.gupta 859
        });
30122 amit.gupta 860
 
31352 amit.gupta 861
        lastMonthPendingIncomeMap.entrySet().stream().forEach(x -> {
862
            String brand = x.getKey();
863
            float amount = x.getValue().getAmount();
864
            if (!totalAmountMap.containsKey(brand)) {
865
                totalAmountMap.put(brand, 0f);
866
            }
867
            totalAmountMap.put(brand, totalAmountMap.get(brand) + amount);
28795 tejbeer 868
 
31352 amit.gupta 869
        });
28795 tejbeer 870
 
871
 
31352 amit.gupta 872
        Map<Integer, String> monthValueMap = new HashMap<>();
873
        for (int i = 0; i <= 5; i++) {
874
            LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
875
            monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
876
        }
877
        model.addAttribute("month", 0);
878
        model.addAttribute("monthValueMap", monthValueMap);
879
        model.addAttribute("keySet", keySet);
880
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
28795 tejbeer 881
 
31352 amit.gupta 882
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
883
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
884
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
885
        model.addAttribute("status", status);
886
        model.addAttribute("totalAmountMap", totalAmountMap);
28795 tejbeer 887
 
31352 amit.gupta 888
        return "last-month-credited-income";
889
    }
30651 amit.gupta 890
 
31352 amit.gupta 891
    @RequestMapping(value = "/getLastMonthPendingIncome", method = RequestMethod.GET)
892
    public String getLastMonthPendingIncome(HttpServletRequest request, Model model) throws Exception {
30651 amit.gupta 893
 
31352 amit.gupta 894
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
28795 tejbeer 895
 
31352 amit.gupta 896
        LocalDateTime currentStartMonth = LocalDate.now().atStartOfDay().withDayOfMonth(1);
897
        LocalDateTime currentDate = LocalDate.now().atStartOfDay();
898
        String status = "PENDING";
31170 amit.gupta 899
 
31352 amit.gupta 900
        LOGGER.info("currentStartMonth" + currentStartMonth);
901
        LOGGER.info("currentDate" + currentDate);
28795 tejbeer 902
 
31352 amit.gupta 903
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
904
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), currentStartMonth, currentDate);
29899 tejbeer 905
 
31352 amit.gupta 906
        Map<String, LastMonthCreditedIncomeModel> lastMonthMarginMap = new HashMap<>();
23786 amit.gupta 907
 
31352 amit.gupta 908
        for (LastMonthCreditedIncomeModel lastMonthPendingIncomeModel : lastMonthPendingIncomeModels) {
28795 tejbeer 909
 
31352 amit.gupta 910
            lastMonthMarginMap.put(lastMonthPendingIncomeModel.getBrand(), lastMonthPendingIncomeModel);
911
        }
912
        LOGGER.info("lastMonthPendingIncomeModel" + lastMonthPendingIncomeModels);
913
        LOGGER.info("lastMonthMarginMap" + lastMonthMarginMap);
914
        model.addAttribute("lastMonthCreditedIncomeModels", lastMonthPendingIncomeModels);
915
        model.addAttribute("lastMonthMarginMap", lastMonthMarginMap);
916
        model.addAttribute("status", status);
28795 tejbeer 917
 
31352 amit.gupta 918
        return "last-month-credited-income";
919
    }
28795 tejbeer 920
 
31352 amit.gupta 921
    @RequestMapping(value = "/getLastMonthImeiWiseIncome", method = RequestMethod.GET)
922
    public String getLastMonthImeiWiseIncome(HttpServletRequest request,
923
                                             @RequestParam(name = "catalogItemId", required = false, defaultValue = "") int catalogItemId,
924
                                             @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
925
            throws Exception {
30053 manish 926
 
31352 amit.gupta 927
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 928
 
31352 amit.gupta 929
        LocalDateTime lastMonthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
930
        LocalDateTime lastMonthEnd = lastMonthStart.plusMonths(1);
30053 manish 931
 
31352 amit.gupta 932
        HashSet<String> allImeiSet = new LinkedHashSet<>();
933
        HashSet<String> purchaseSet = new LinkedHashSet<>();
934
        HashSet<String> saleSet = new LinkedHashSet<>();
30053 manish 935
 
31352 amit.gupta 936
        List<LastMonthFrontEndImeiModel> lmfi = schemeInOutRepository
937
                .selectLastMonthFrontEndImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart, lastMonthEnd);
938
        List<LastMonthImeiModel> lmpi = schemeInOutRepository.selectLastMonthPurchaseInImei(loginDetails.getFofoId(),
939
                catalogItemId, lastMonthStart, lastMonthEnd);
940
        List<LastMonthImeiModel> lmci = schemeInOutRepository.selectLastMonthCreditedImei(loginDetails.getFofoId(),
941
                catalogItemId, lastMonthStart, lastMonthEnd);
30053 manish 942
 
31352 amit.gupta 943
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(YearMonth.of(lastMonthStart.getYear(),
944
                lastMonthStart.getMonth()), loginDetails.getFofoId(), null, catalogItemId);
30053 manish 945
 
31352 amit.gupta 946
        LOGGER.info("lmci {}", lmci);
30053 manish 947
 
31352 amit.gupta 948
        Map<String, Double> lastmonthCategoryUpgradeMargin = schemeInOutRepository
949
                .selectLastMonthCategoryUpgradeMarginByImei(loginDetails.getFofoId(), catalogItemId, lastMonthStart,
950
                        lastMonthEnd)
951
                .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
30053 manish 952
 
31352 amit.gupta 953
        allImeiSet.addAll(lmpi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
954
        allImeiSet.addAll(lmci.stream().map(x -> x.getImei()).collect(Collectors.toList()));
955
        allImeiSet.addAll(lmfi.stream().map(x -> x.getImei()).collect(Collectors.toList()));
956
        allImeiSet.addAll(offerPayoutImeiIncomeModels.stream().map(x -> x.getImei()).collect(Collectors.toList()));
30053 manish 957
 
31352 amit.gupta 958
        List<String> allImeiList = new ArrayList<>(allImeiSet);
30053 manish 959
 
31352 amit.gupta 960
        LOGGER.info("allImeiList" + allImeiList);
961
        LOGGER.info("lmcm" + lastmonthCategoryUpgradeMargin);
30253 amit.gupta 962
 
31352 amit.gupta 963
        List<LastMonthFrontEndImeiModel> lastMonthFrontEndImeis = schemeInOutRepository
964
                .selectLastMonthFrontEndByImei(loginDetails.getFofoId(), allImeiList);
31379 amit.gupta 965
        Map<String, LastMonthFrontEndImeiModel> soldMap = lastMonthFrontEndImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x));
30053 manish 966
 
31379 amit.gupta 967
 
31352 amit.gupta 968
        List<LastMonthImeiModel> lastMonthPurchaseInImeis = schemeInOutRepository
969
                .selectLastMonthPurchaseInByImei(loginDetails.getFofoId(), allImeiList);
30053 manish 970
 
31352 amit.gupta 971
        List<LastMonthImeiModel> lastMonthCreditedImeis = schemeInOutRepository
972
                .selectLastMonthCreditedByImei(loginDetails.getFofoId(), allImeiList);
973
        List<OfferPayoutImeiIncomeModel> allOfferPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByImei(allImeiList);
30053 manish 974
 
31352 amit.gupta 975
        //Map<String, OfferPayoutImeiIncomeModel> imeisOfferPayoutMap = allOfferPayoutImeiIncomeModels.stream().collect(Collectors.toMap(x->x.getImei(), x->x));
976
        Map<String, Double> imeiWisePendingSaleAmount = lastMonthCreditedImeis.stream()
977
                .filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).collect(Collectors
978
                        .groupingBy(x -> x.getImei(), Collectors.summingDouble(x -> x.getPendingSaleAmount())));
30053 manish 979
 
31352 amit.gupta 980
        allOfferPayoutImeiIncomeModels.stream().forEach(x -> {
981
            if (x.getSaleDate() != null) {
982
                LastMonthImeiModel lastMonthImeiModel = new LastMonthImeiModel(x.getImei(), (float) x.getSalePayout(),
983
                        0, "Addnl Margin", x.getSaleDate(), SchemePayoutStatus.CREDITED);
984
                lastMonthCreditedImeis.add(lastMonthImeiModel);
985
            }
986
            if (x.getGrnDate() != null) {
987
                LastMonthImeiModel lastMonthImeiModel = new LastMonthImeiModel(x.getImei(), (float) x.getPurchasePayout(),
988
                        0, "Booster Payout", x.getGrnDate(), SchemePayoutStatus.CREDITED);
989
                lastMonthPurchaseInImeis.add(lastMonthImeiModel);
990
            }
991
        });
30053 manish 992
 
31352 amit.gupta 993
        Map<String, Map<String, Double>> lastMonthPurchaseInMapPairMap = lastMonthPurchaseInImeis.stream()
994
                .collect(Collectors.groupingBy(x -> x.getImei(),
995
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
996
        Map<String, LocalDate> imeiPurchaseDateMap = lastMonthPurchaseInImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x.getCreateTimeStamp().toLocalDate(), (x, y) -> x));
997
        Map<String, LocalDate> imeiSaleDateMap = lastMonthCreditedImeis.stream().collect(Collectors.toMap(x -> x.getImei(), x -> x.getCreateTimeStamp().toLocalDate(), (x, y) -> x));
998
        Map<String, Map<String, Double>> lastMonthCreditedMapPairMap = lastMonthCreditedImeis.stream()
999
                .collect(Collectors.groupingBy(x -> x.getImei(),
1000
                        Collectors.groupingBy(x -> x.getDescription(), Collectors.summingDouble(x -> x.getAmount()))));
30053 manish 1001
 
31352 amit.gupta 1002
        // descriptionSet.add("")
1003
        purchaseSet.addAll(lastMonthPurchaseInImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
1004
        saleSet.addAll(lastMonthCreditedImeis.stream().map(x -> x.getDescription()).collect(Collectors.toList()));
30053 manish 1005
 
31352 amit.gupta 1006
        List<String> purchaseList = new ArrayList<>(purchaseSet);
1007
        List<String> saleList = new ArrayList<>(saleSet);
30253 amit.gupta 1008
 
31352 amit.gupta 1009
        Map<String, ImeiWiseIncomePairAndMapModel> imeiWiseIncomeMapOfMap = new HashMap<>();
30053 manish 1010
 
31352 amit.gupta 1011
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthPurchaseInMapPairMap.entrySet()) {
30235 tejbeer 1012
 
31352 amit.gupta 1013
            String imei = entry.getKey();
1014
            ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(imei,
1015
                    imeiPurchaseDateMap.get(imei), null);
1016
            imeiWiseIncomeMapOfMap.put(imei, modelImeiMap);
1017
            double totalAmount = entry.getValue().entrySet().stream()
1018
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1019
            imeiWiseIncomeMapOfMap.get(imei).setTotalIncome(totalAmount);
1020
        }
31283 amit.gupta 1021
 
31352 amit.gupta 1022
        for (Map.Entry<String, Map<String, Double>> entry : lastMonthCreditedMapPairMap.entrySet()) {
1023
            Map<String, Double> descriptionAmountMap = entry.getValue();
1024
            if (!imeiWiseIncomeMapOfMap.containsKey(entry.getKey())) {
1025
                ImeiWiseIncomePairAndMapModel modelImeiMap = new ImeiWiseIncomePairAndMapModel(entry.getKey(), null,
1026
                        imeiSaleDateMap.get(entry.getKey()));
1027
                imeiWiseIncomeMapOfMap.put(entry.getKey(), modelImeiMap);
1028
            } else {
1029
                ImeiWiseIncomePairAndMapModel modelImeiMap = imeiWiseIncomeMapOfMap.get(entry.getKey());
1030
                modelImeiMap.setSaleDate(imeiSaleDateMap.get(entry.getKey()));
1031
            }
30053 manish 1032
 
31352 amit.gupta 1033
            double totalAmount = descriptionAmountMap.entrySet().stream()
1034
                    .collect(Collectors.summingDouble(x -> x.getValue()));
1035
            imeiWiseIncomeMapOfMap.get(entry.getKey())
1036
                    .setTotalIncome(totalAmount + imeiWiseIncomeMapOfMap.get(entry.getKey()).getTotalIncome());
1037
        }
30053 manish 1038
 
31379 amit.gupta 1039
        /*lastMonthFrontEndImeis.stream().forEach(x -> {
31352 amit.gupta 1040
            if (imeiWiseIncomeMapOfMap.containsKey(x.getImei())) {
1041
                ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1042
                        .get(x.getImei());
1043
                imeiWiseIncomePairAndMapModel.setTotalIncome(imeiWiseIncomePairAndMapModel.getTotalIncome() + x.getAmount());
1044
                imeiWiseIncomePairAndMapModel.setFrontMargin(x.getAmount());
1045
            }
31379 amit.gupta 1046
        });*/
30053 manish 1047
 
31352 amit.gupta 1048
        //Imeis for pending activation
1049
        lastMonthCreditedImeis.stream().filter(x -> x.getStatus().equals(SchemePayoutStatus.PENDING)).forEach(x -> {
1050
            if (!imeiWiseIncomeMapOfMap.containsKey(x.getImei())) {
31379 amit.gupta 1051
                ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = new ImeiWiseIncomePairAndMapModel(x.getImei(), null, null);
31352 amit.gupta 1052
            }
1053
            ImeiWiseIncomePairAndMapModel imeiWiseIncomePairAndMapModel = imeiWiseIncomeMapOfMap
1054
                    .get(x.getImei());
1055
            imeiWiseIncomePairAndMapModel.setSaleDate(x.getCreateTimeStamp().toLocalDate());
1056
            imeiWiseIncomePairAndMapModel.setTotalIncome(x.getPendingSaleAmount() + imeiWiseIncomePairAndMapModel.getTotalIncome());
1057
        });
30053 manish 1058
 
31379 amit.gupta 1059
        lastMonthFrontEndImeis.stream().forEach(lastMonthFrontEndImeiModel -> {
1060
            if (imeiWiseIncomeMapOfMap.containsKey(lastMonthFrontEndImeiModel.getImei())) {
1061
                lastMonthFrontEndImeiModel.setNlc(lastMonthFrontEndImeiModel.getDp()
1062
                        - (float) imeiWiseIncomeMapOfMap.get(lastMonthFrontEndImeiModel.getImei()).getTotalIncome());
1063
                lastMonthFrontEndImeiModel.setNetIncome(lastMonthFrontEndImeiModel.getSellingPrice() - lastMonthFrontEndImeiModel.getNlc());
1064
            }
1065
        });
1066
 
31352 amit.gupta 1067
        model.addAttribute("imeiWisePendingSaleAmount", imeiWisePendingSaleAmount);
1068
        model.addAttribute("month", month);
1069
        model.addAttribute("purchaseList", purchaseList);
1070
        model.addAttribute("saleList", saleList);
1071
        model.addAttribute("lastMonthPurchaseInMapPairMap", lastMonthPurchaseInMapPairMap);
1072
        model.addAttribute("lastMonthCreditedMapPairMap", lastMonthCreditedMapPairMap);
1073
        model.addAttribute("imeiWiseIncomeMapOfMap", imeiWiseIncomeMapOfMap);
1074
        model.addAttribute("lastmonthCategoryUpgradeMargin", lastmonthCategoryUpgradeMargin);
31379 amit.gupta 1075
        model.addAttribute("soldMap", soldMap);
31352 amit.gupta 1076
        model.addAttribute("allOfferPayoutImeiIncomeModels", allOfferPayoutImeiIncomeModels);
1077
        //model.addAttribute("iimeiSaleDateMap", imeiSaleDateMap);
1078
        //model.addAttribute("imeiPurchaseDateMap", imeiPurchaseDateMap);
30053 manish 1079
 
31352 amit.gupta 1080
        return "last-month-imei-wise-income";
1081
    }
30053 manish 1082
 
31352 amit.gupta 1083
    @RequestMapping(value = "/brandWiseIncome", method = RequestMethod.GET)
1084
    public String getBrandWiseIncome(HttpServletRequest request,
1085
                                     @RequestParam(name = "brand", required = false, defaultValue = "") String brand,
1086
                                     @RequestParam(name = "status", required = false, defaultValue = "") String status,
1087
                                     @RequestParam(name = "month", required = false, defaultValue = "") int month, Model model)
1088
            throws ProfitMandiBusinessException {
1089
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1090
        LOGGER.info("loginDetails {}", loginDetails);
1091
        LOGGER.info("brand" + brand);
1092
        LOGGER.info("month {}", month);
30053 manish 1093
 
31352 amit.gupta 1094
        LocalDateTime monthStart = LocalDate.now().minusMonths(month).withDayOfMonth(1).atStartOfDay();
1095
        LocalDateTime monthEnd = monthStart.plusMonths(1);
30053 manish 1096
 
31352 amit.gupta 1097
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1098
                YearMonth.of(monthStart.getYear(), monthStart.getMonth()), loginDetails.getFofoId(), brand, null);
1099
        Map<Integer, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getPurchasePayout())));
1100
        Map<Integer, Double> additionalSalePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(x -> x.getCatalogId(), Collectors.summingDouble(x -> x.getSalePayout())));
30053 manish 1101
 
31352 amit.gupta 1102
        boolean partnerTypeUpgraded = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(),
1103
                YearMonth.now());
30053 manish 1104
 
31352 amit.gupta 1105
        LOGGER.info("partnerType" + partnerTypeUpgraded);
30053 manish 1106
 
31352 amit.gupta 1107
        Map<String, Double> categoryUpgradeBrandModelMap = null;
1108
        if (partnerTypeUpgraded) {
1109
            categoryUpgradeBrandModelMap = schemeInOutRepository
1110
                    .selectLastMonthCategoryUpgradeMarginByBrandModel(loginDetails.getFofoId(), brand, monthStart,
1111
                            monthEnd)
1112
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1113
        }
30053 manish 1114
 
31352 amit.gupta 1115
        List<LastMonthFrontEndBrandWiseIncome> modelWiseSalesMargins = schemeInOutRepository
1116
                .selectFrontIncomeBrandWise(loginDetails.getFofoId(), brand, monthStart, monthEnd);
30053 manish 1117
 
31352 amit.gupta 1118
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMargins = schemeInOutRepository
1119
                .selectLastMonthBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1120
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeOutMarginsMap = modelWiseSchemeOutMargins.stream()
1121
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1122
 
31352 amit.gupta 1123
        List<LastMonthBrandWiseIncomeModel> modelWiseSchemeInMargins = schemeInOutRepository
1124
                .selectLastMonthPurchaseBrandWiseIncome(loginDetails.getFofoId(), brand, monthStart, monthEnd);
1125
        Map<Integer, LastMonthBrandWiseIncomeModel> modelWiseSchemeInMarginsMap = modelWiseSchemeInMargins.stream()
1126
                .collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x));
30053 manish 1127
 
31352 amit.gupta 1128
        Map<Integer, Double> modelTotalIncomeMap = new HashMap<>();
1129
        Map<Integer, String> modelNameMap = new HashMap<>();
30053 manish 1130
 
31352 amit.gupta 1131
        offerPayoutImeiIncomeModels.stream().forEach(x -> {
1132
            if (!modelTotalIncomeMap.containsKey(x.getCatalogId())) {
1133
                modelNameMap.put(x.getCatalogId(), (x.getModelNumber() + " " + x.getModelName()).trim());
1134
                modelTotalIncomeMap.put(x.getCatalogId(), 0d);
1135
            }
1136
            modelTotalIncomeMap.put(x.getCatalogId(), modelTotalIncomeMap.get(x.getCatalogId()) + x.getPurchasePayout() + x.getSalePayout());
30253 amit.gupta 1137
 
31352 amit.gupta 1138
        });
30053 manish 1139
 
31352 amit.gupta 1140
        modelWiseSchemeOutMargins.stream().forEach(x -> {
1141
            if (!modelNameMap.containsKey(x.getCatalogItemId())) {
1142
                modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
1143
                modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + " " + x.getModelName()).trim());
1144
            }
1145
            modelTotalIncomeMap.put(x.getCatalogItemId(), modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount() + x.getPendingSaleAmount());
30053 manish 1146
 
31352 amit.gupta 1147
        });
30053 manish 1148
 
31352 amit.gupta 1149
        LastMonthBrandWiseIncomeModel totalModel = new LastMonthBrandWiseIncomeModel();
1150
        modelWiseSalesMargins.stream().forEach(x -> {
1151
            if (!modelWiseSchemeOutMarginsMap.containsKey(x.getCatalogItemId())) {
1152
                LastMonthBrandWiseIncomeModel lmbwIncomeModel = new LastMonthBrandWiseIncomeModel();
1153
                lmbwIncomeModel.setModelName(x.getModelName());
1154
                lmbwIncomeModel.setModelNumber(x.getModelNumber());
1155
                lmbwIncomeModel.setBrand(x.getBrand());
1156
                lmbwIncomeModel.setCatalogItemId(x.getCatalogItemId());
1157
                modelWiseSchemeOutMarginsMap.put(x.getCatalogItemId(), lmbwIncomeModel);
1158
                totalModel.setQty(totalModel.getQty() + x.getQty());
1159
            }
1160
            modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
1161
            LOGGER.info("Modelname {}, Model {}", modelNameMap.get(x.getCatalogItemId()), x.getQty());
1162
            LastMonthBrandWiseIncomeModel lmbwIncomeModel = modelWiseSchemeOutMarginsMap.get(x.getCatalogItemId());
30053 manish 1163
 
31352 amit.gupta 1164
            lmbwIncomeModel.setAmount(lmbwIncomeModel.getAmount() + x.getAmount());
1165
            lmbwIncomeModel.setQty(x.getQty());
1166
            if (!modelTotalIncomeMap.containsKey(x.getCatalogItemId())) {
1167
                modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
1168
            }
1169
            modelTotalIncomeMap.put(x.getCatalogItemId(), x.getAmount() + modelTotalIncomeMap.get(x.getCatalogItemId()));
1170
            totalModel.setAmount(totalModel.getAmount() + x.getAmount());
1171
            totalModel.setPendingSaleAmount(totalModel.getPendingSaleAmount());
30253 amit.gupta 1172
 
31352 amit.gupta 1173
        });
1174
        modelWiseSchemeInMargins.stream().forEach(x -> {
1175
            if (!modelTotalIncomeMap.containsKey(x.getCatalogItemId())) {
1176
                modelTotalIncomeMap.put(x.getCatalogItemId(), 0d);
1177
            }
1178
            modelTotalIncomeMap.put(x.getCatalogItemId(),
1179
                    modelTotalIncomeMap.get(x.getCatalogItemId()) + x.getAmount());
1180
            modelNameMap.put(x.getCatalogItemId(), (x.getModelNumber() + x.getModelName()).trim());
1181
            totalModel.setQty(totalModel.getQty() + x.getQty());
1182
            totalModel.setAmount(totalModel.getAmount() + x.getAmount());
30253 amit.gupta 1183
 
31352 amit.gupta 1184
        });
30253 amit.gupta 1185
 
31352 amit.gupta 1186
        model.addAttribute("month", month);
1187
        model.addAttribute("modelWiseSchemeOutMarginsMap", modelWiseSchemeOutMarginsMap);
1188
        model.addAttribute("modelWiseSchemeInMarginsMap", modelWiseSchemeInMarginsMap);
1189
        model.addAttribute("modelNameMap", modelNameMap);
1190
        model.addAttribute("modelTotalIncomeMap", modelTotalIncomeMap);
1191
        model.addAttribute("categoryUpgradeBrandModelMap", categoryUpgradeBrandModelMap);
1192
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
1193
        model.addAttribute("additionalSalePayoutMap", additionalSalePayout);
1194
        model.addAttribute("totalModel", totalModel);
30253 amit.gupta 1195
 
31352 amit.gupta 1196
        return "monthly-brand-wise-income";
30053 manish 1197
 
31352 amit.gupta 1198
    }
30053 manish 1199
 
31352 amit.gupta 1200
    @RequestMapping(value = "/monthWisePartnerIncome/{yearMonth}", method = RequestMethod.GET)
1201
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
1202
            throws ProfitMandiBusinessException {
1203
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30253 amit.gupta 1204
 
31352 amit.gupta 1205
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
1206
        LocalDateTime lastMonthEnd = startOfMonth.plusMonths(1);
30253 amit.gupta 1207
 
31352 amit.gupta 1208
        YearMonth monthYear = YearMonth.now();
30053 manish 1209
 
31352 amit.gupta 1210
        boolean partnerType = partnerTypeChangeService.isPartnerTypeUpgraded(loginDetails.getFofoId(), monthYear);
30053 manish 1211
 
31352 amit.gupta 1212
        LOGGER.info("partnerType" + partnerType);
30053 manish 1213
 
31352 amit.gupta 1214
        Map<String, Double> lastMonthCategoryUpgradeMarginMap = new HashMap<>();
30053 manish 1215
 
31352 amit.gupta 1216
        if (partnerType) {
1217
            lastMonthCategoryUpgradeMarginMap = schemeInOutRepository
1218
                    .selectLastMonthCategoryUpgradeMarginByBrand(loginDetails.getFofoId(), startOfMonth,
1219
                            lastMonthEnd)
1220
                    .stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x.getAmount()));
1221
        }
30053 manish 1222
 
31352 amit.gupta 1223
        String status = "CREDITED";
30053 manish 1224
 
31352 amit.gupta 1225
        List<LastMonthCreditedIncomeModel> lastMonthPendingIncomeModels = schemeInOutRepository
1226
                .selectLastMonthPendingIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30053 manish 1227
 
31352 amit.gupta 1228
        List<LastMonthCreditedIncomeModel> lastMonthCreditedIncomeModels = schemeInOutRepository
1229
                .selectLastMonthCreditedIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1230
 
31352 amit.gupta 1231
        List<LastMonthCreditedIncomeModel> lastMonthPurchaseInMargins = schemeInOutRepository
1232
                .selectLastMonthPurchaseInMarginByFofoId(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1233
 
31352 amit.gupta 1234
        List<LastMonthCreditedIncomeModel> lastMonthFrontEndIncomes = schemeInOutRepository
1235
                .selectFrontIncomeByBrand(loginDetails.getFofoId(), startOfMonth, lastMonthEnd);
30235 tejbeer 1236
 
31352 amit.gupta 1237
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(
1238
                YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()), loginDetails.getFofoId(), null, null);
30235 tejbeer 1239
 
31352 amit.gupta 1240
        Map<String, Double> additionalPurchasePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getPurchasePayout)));
1241
        Map<String, Double> additionSalePayout = offerPayoutImeiIncomeModels.stream().collect(Collectors.groupingBy(OfferPayoutImeiIncomeModel::getBrand, Collectors.summingDouble(OfferPayoutImeiIncomeModel::getSalePayout)));
30235 tejbeer 1242
 
1243
 
31352 amit.gupta 1244
        Map<String, LastMonthCreditedIncomeModel> lastMonthPurchaseInMarginMap = lastMonthPurchaseInMargins.stream()
1245
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1246
 
31352 amit.gupta 1247
        Map<String, LastMonthCreditedIncomeModel> lastMonthSaleMarginMap = lastMonthCreditedIncomeModels.stream()
1248
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1249
 
1250
 
31352 amit.gupta 1251
        Map<String, LastMonthCreditedIncomeModel> lastMonthPendingIncomeMap = lastMonthPendingIncomeModels.stream()
1252
                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30053 manish 1253
 
31352 amit.gupta 1254
        lastMonthFrontEndIncomes.stream().forEach(x -> {
1255
            if (lastMonthSaleMarginMap.containsKey(x.getBrand())) {
1256
                x.setAmount(lastMonthSaleMarginMap.get(x.getBrand()).getAmount() + x.getAmount());
30053 manish 1257
 
31352 amit.gupta 1258
                lastMonthSaleMarginMap.put(x.getBrand(), x);
1259
            } else {
1260
                lastMonthSaleMarginMap.put(x.getBrand(), x);
1261
            }
30053 manish 1262
 
31352 amit.gupta 1263
        });
1264
        Map<String, Float> totalAmountMap = lastMonthSaleMarginMap.entrySet().stream()
1265
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue().getAmount()));
1266
        Set<String> brandSet = new HashSet<>();
1267
        brandSet.addAll(lastMonthPurchaseInMarginMap.keySet());
1268
        brandSet.addAll(lastMonthSaleMarginMap.keySet());
1269
        brandSet.addAll(lastMonthPendingIncomeMap.keySet());
1270
        brandSet.addAll(additionalPurchasePayout.keySet());
1271
        brandSet.addAll(additionSalePayout.keySet());
1272
        brandSet.stream().forEach(brand -> {
1273
            totalAmountMap.put(brand,
1274
                    (lastMonthSaleMarginMap.get(brand) == null ? 0 : lastMonthSaleMarginMap.get(brand).getAmount()) +
1275
                            (lastMonthPurchaseInMarginMap.get(brand) == null ? 0 : lastMonthPurchaseInMarginMap.get(brand).getAmount()) +
1276
                            (lastMonthPendingIncomeMap.get(brand) == null ? 0 : lastMonthPendingIncomeMap.get(brand).getAmount()) +
1277
                            (additionalPurchasePayout.get(brand) == null ? 0 : additionalPurchasePayout.get(brand).longValue()) +
1278
                            (additionSalePayout.get(brand) == null ? 0 : additionSalePayout.get(brand).longValue())
1279
            );
1280
        });
30053 manish 1281
 
31352 amit.gupta 1282
        Map<Integer, String> monthValueMap = new HashMap<>();
1283
        for (int i = 0; i <= 5; i++) {
1284
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
1285
            monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
1286
        }
1287
        model.addAttribute("monthValueMap", monthValueMap);
30053 manish 1288
 
31352 amit.gupta 1289
        model.addAttribute("keySet", brandSet);
1290
        model.addAttribute("lastMonthPurchaseInMarginMap", lastMonthPurchaseInMarginMap);
1291
        model.addAttribute("lastMonthSaleMarginMap", lastMonthSaleMarginMap);
1292
        model.addAttribute("lastMonthPendingIncomeMap", lastMonthPendingIncomeMap);
1293
        model.addAttribute("additionalPurchasePayoutMap", additionalPurchasePayout);
1294
        model.addAttribute("additionalSalePayoutMap", additionSalePayout);
30053 manish 1295
 
31352 amit.gupta 1296
        model.addAttribute("totalAmountMap", totalAmountMap);
1297
        model.addAttribute("status", status);
1298
        model.addAttribute("month", yearMonth);
1299
        model.addAttribute("lastMonthCategoryUpgradeMarginMap", lastMonthCategoryUpgradeMarginMap);
1300
        LOGGER.info("totalAmountMap {}", totalAmountMap);
1301
        LOGGER.info("lastMonthSaleMarginMap {}", lastMonthSaleMarginMap);
30253 amit.gupta 1302
 
31352 amit.gupta 1303
        return "last-month-credited-income";
1304
    }
30253 amit.gupta 1305
 
31352 amit.gupta 1306
    @RequestMapping(value = "/schemes/downloadPage", method = RequestMethod.GET)
1307
    public String downloadPage(HttpServletRequest request, Model model) {
1308
        return "schemes-download";
1309
    }
30253 amit.gupta 1310
 
31352 amit.gupta 1311
    @RequestMapping(value = "/schemes/download", method = RequestMethod.GET)
1312
    public ResponseEntity<?> downloadInventoryItemAgingByInterval(HttpServletRequest request,
1313
                                                                  @RequestParam LocalDateTime startDateTime, @RequestParam LocalDateTime endDateTime)
1314
            throws ProfitMandiBusinessException {
30253 amit.gupta 1315
 
31352 amit.gupta 1316
        List<SchemeModel> schemeModels = schemeService.getAllSchemeModels(startDateTime, endDateTime);
31334 amit.gupta 1317
 
31352 amit.gupta 1318
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1319
        ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
30253 amit.gupta 1320
 
31352 amit.gupta 1321
        final HttpHeaders headers = new HttpHeaders();
1322
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
1323
        headers.set("Content-disposition", "inline; filename=SchemesReport.xlsx");
1324
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1325
        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1326
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1327
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1328
    }
30053 manish 1329
 
31352 amit.gupta 1330
    @RequestMapping(value = "/getSchemeById", method = RequestMethod.GET)
1331
    public String getSchemeById(HttpServletRequest request,
1332
                                @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId, Model model)
1333
            throws ProfitMandiBusinessException {
1334
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
30053 manish 1335
 
31352 amit.gupta 1336
        boolean fullAccess = this.getAccess(loginDetails.getEmailId());
1337
        Scheme scheme = schemeService.getSchemeById(schemeId);
1338
        model.addAttribute("fullAccess", fullAccess);
1339
        model.addAttribute("scheme", scheme);
1340
        model.addAttribute("isAdmin", roleManager.isAdmin(loginDetails.getRoleIds()));
1341
        return "scheme-details";
1342
    }
30053 manish 1343
 
31352 amit.gupta 1344
    @RequestMapping(value = "/activeSchemeById", method = RequestMethod.PUT)
1345
    public String activeSchemeById(@RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1346
                                   @RequestParam(name = "offset", defaultValue = "0") int offset,
1347
                                   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1348
            throws ProfitMandiBusinessException {
1349
        schemeService.activeSchemeById(schemeId);
1350
        List<Scheme> schemes = schemeRepository.selectAll(offset, limit);
1351
        for (Scheme scheme : schemes) {
1352
            if (scheme.getAmountType().equals(AmountType.PERCENTAGE)) {
1353
                scheme.setAmountModel(scheme.getAmount() + "%");
1354
            } else {
1355
                scheme.setAmountModel(scheme.getAmount() + "");
1356
            }
1357
        }
1358
        return "schemes";
1359
    }
30053 manish 1360
 
31352 amit.gupta 1361
    @RequestMapping(value = "/expireSchemeById", method = RequestMethod.PUT)
1362
    public String expireSchemeById(HttpServletRequest request,
1363
                                   @RequestParam(name = ProfitMandiConstants.SCHEME_ID) int schemeId,
1364
                                   @RequestParam(name = ProfitMandiConstants.EXPIRE_TIMESTAMP) LocalDateTime expiryTimestamp, Model model)
1365
            throws ProfitMandiBusinessException {
1366
        schemeService.expireSchemeById(schemeId, expiryTimestamp);
1367
        return getDefaultSchemes(request, model);
1368
    }
30053 manish 1369
 
31352 amit.gupta 1370
    @RequestMapping(value = "/getSchemesJson", method = RequestMethod.GET)
1371
    public ResponseEntity<?> getSchemesJson(HttpServletRequest request,
1372
                                            @RequestParam(name = "offset", defaultValue = "0") int offset,
1373
                                            @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1374
            throws ProfitMandiBusinessException {
1375
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1376
        return responseSender.ok(schemeService.getSchemes(loginDetails.getRoleIds(), offset, limit));
1377
    }
30053 manish 1378
 
31352 amit.gupta 1379
    @RequestMapping(value = "/getCustomerOffer", method = RequestMethod.GET)
1380
    public String getCustomerOffer(HttpServletRequest request,
1381
                                   @RequestParam(name = "searchModel", required = false, defaultValue = "0") int searchModel, Model model)
1382
            throws ProfitMandiBusinessException {
1383
        List<CustomerOffer> customerOffers = null;
1384
        if (searchModel > 0) {
30053 manish 1385
 
31352 amit.gupta 1386
            Item item = itemRepository.selectAllByCatalogItemId(searchModel).get(0);
1387
            customerOffers = customerOfferRepository.selectActiveOfferByModel(searchModel, LocalDate.now());
1388
            model.addAttribute("modelName", item.getItemDescriptionNoColor());
1389
        } else {
1390
            customerOffers = customerOfferRepository.selectAll();
1391
        }
30053 manish 1392
 
31352 amit.gupta 1393
        LOGGER.info("customerOffers" + customerOffers);
30053 manish 1394
 
31352 amit.gupta 1395
        for (CustomerOffer customerOffer : customerOffers) {
30053 manish 1396
 
31352 amit.gupta 1397
            LOGGER.info("ss" + searchModel);
30053 manish 1398
 
31352 amit.gupta 1399
            if (!StringUtils.isEmpty(customerOffer.getPartnerCriteria())) {
1400
                String partnerCriteria = retailerService.getPartnerCriteriaString(
1401
                        gson.fromJson(customerOffer.getPartnerCriteria(), PartnerCriteria.class));
1402
                customerOffer.setPartnerCriteriaString(partnerCriteria);
1403
            }
30053 manish 1404
 
31352 amit.gupta 1405
        }
30053 manish 1406
 
31352 amit.gupta 1407
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
1408
                .collect(Collectors.toList());
31281 amit.gupta 1409
 
31352 amit.gupta 1410
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30053 manish 1411
 
31352 amit.gupta 1412
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
1413
                .filter(x -> x != null).collect(Collectors.toList()).stream()
1414
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30053 manish 1415
 
31352 amit.gupta 1416
        model.addAttribute("customRetailersMap", customRetailersMap);
1417
        model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
1418
        model.addAttribute("searchModel", searchModel);
30053 manish 1419
 
31352 amit.gupta 1420
        model.addAttribute("customerOffers", customerOffers);
1421
        return "customer-offer";
30053 manish 1422
 
31352 amit.gupta 1423
    }
30053 manish 1424
 
31352 amit.gupta 1425
    @RequestMapping(value = "/createCustomerOffer", method = RequestMethod.POST)
1426
    public String createCustomerOffer(HttpServletRequest request, @RequestBody CustomerOfferModel customerOfferModel,
1427
                                      Model model) throws Exception {
30053 manish 1428
 
31352 amit.gupta 1429
        CustomerOffer co = new CustomerOffer();
1430
        co.setOfferName(customerOfferModel.getOfferName());
1431
        co.setStartDate(customerOfferModel.getStartDate());
1432
        co.setEndDate(customerOfferModel.getEndDate());
1433
        co.setPartnerCriteria(gson.toJson(customerOfferModel.getPartnerCriteria()));
1434
        co.setCreatedTimestamp(LocalDateTime.now());
1435
        co.setUpdatedTimestamp(LocalDateTime.now());
1436
        customerOfferRepository.persist(co);
31281 amit.gupta 1437
 
31352 amit.gupta 1438
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31281 amit.gupta 1439
 
31352 amit.gupta 1440
        return "response";
30053 manish 1441
 
31352 amit.gupta 1442
    }
30053 manish 1443
 
31352 amit.gupta 1444
    @RequestMapping(value = "/customerOffer/downloadTemplate", method = RequestMethod.GET)
1445
    public ResponseEntity<?> downloadCustomerOfferTemplate(HttpServletRequest request) throws Exception {
1446
        List<List<?>> rows = new ArrayList<>();
30053 manish 1447
 
31352 amit.gupta 1448
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(Arrays.asList("id",
1449
                        "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date (dd-mm-yyyy)", "End Date (dd-mm-yyyy)"),
1450
                rows);
30053 manish 1451
 
31352 amit.gupta 1452
        final HttpHeaders headers = new HttpHeaders();
1453
        headers.set("Content-Type", "text/csv");
1454
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1455
        headers.setContentLength(baos.toByteArray().length);
30053 manish 1456
 
31352 amit.gupta 1457
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1458
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1459
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
30053 manish 1460
 
31352 amit.gupta 1461
    }
30053 manish 1462
 
31352 amit.gupta 1463
    @RequestMapping(value = "/customerOfferItem/upload", method = RequestMethod.POST)
1464
    public String uploadCustomerOfferItem(HttpServletRequest request, Model model, @RequestParam int offerId,
1465
                                          HttpServletResponse response, @RequestPart MultipartFile file) throws Throwable {
23786 amit.gupta 1466
 
31352 amit.gupta 1467
        List<CSVRecord> records = FileUtil.readFile(file);
1468
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
23914 govind 1469
 
31352 amit.gupta 1470
        CustomerOffer customerOffer = customerOfferRepository.selectById(offerId);
1471
        List<Integer> catalogIds = new ArrayList<>();
1472
        for (CSVRecord record : records) {
23786 amit.gupta 1473
 
31352 amit.gupta 1474
            CustomerOfferItem coi = customerOfferItemRepository.selectById(Integer.parseInt(record.get(0)));
23786 amit.gupta 1475
 
31352 amit.gupta 1476
            if (coi == null) {
1477
                coi = new CustomerOfferItem();
1478
                coi.setCatalogId(Integer.parseInt(record.get(1)));
1479
                coi.setSchemePayout(Integer.parseInt(record.get(2)));
1480
                coi.setDealerPayout(Integer.parseInt(record.get(3)));
1481
                coi.setCustomerOfferId(offerId);
1482
                coi.setCreatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1483
 
31352 amit.gupta 1484
                customerOfferItemRepository.persist(coi);
29899 tejbeer 1485
 
31352 amit.gupta 1486
            }
1487
            coi.setSchemePayout(Integer.parseInt(record.get(2)));
1488
            coi.setDealerPayout(Integer.parseInt(record.get(3)));
1489
            coi.setCustomerOfferId(offerId);
1490
            coi.setUpdatedTimestamp(LocalDateTime.now());
23786 amit.gupta 1491
 
31352 amit.gupta 1492
            LOGGER.info(record.get(4));
23786 amit.gupta 1493
 
31352 amit.gupta 1494
            LocalDate startDate = LocalDate.parse(record.get(4), formatter);
1495
            LocalDate endDate = LocalDate.parse(record.get(5), formatter);
23786 amit.gupta 1496
 
31352 amit.gupta 1497
            if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1498
                    || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1499
                    && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1500
                    || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
1501
                coi.setStartDate(startDate);
26802 tejbeer 1502
 
31352 amit.gupta 1503
            } else {
29707 tejbeer 1504
 
31352 amit.gupta 1505
                catalogIds.add(coi.getCatalogId());
1506
            }
29707 tejbeer 1507
 
31352 amit.gupta 1508
            if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1509
                    || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1510
                    && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1511
                    || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1512
 
31352 amit.gupta 1513
                coi.setEndDate(endDate);
31147 tejbeer 1514
 
31352 amit.gupta 1515
            } else {
1516
                catalogIds.add(coi.getCatalogId());
1517
            }
31147 tejbeer 1518
 
31352 amit.gupta 1519
        }
31147 tejbeer 1520
 
31352 amit.gupta 1521
        if (!catalogIds.isEmpty()) {
1522
            throw new ProfitMandiBusinessException("Please set accurate start and end date", catalogIds,
1523
                    "Please set accurate start and end date");
1524
        }
1525
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1526
 
31352 amit.gupta 1527
        return "response";
31147 tejbeer 1528
 
31352 amit.gupta 1529
    }
31147 tejbeer 1530
 
31352 amit.gupta 1531
    @RequestMapping(value = "/addCustomerOfferItem", method = RequestMethod.POST)
1532
    public String addCustomerOfferItem(HttpServletRequest request,
1533
                                       @RequestBody CustomerOfferItemModel customerOfferItemModel, Model model) throws Throwable {
31147 tejbeer 1534
 
31352 amit.gupta 1535
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItemModel.getOfferId());
31147 tejbeer 1536
 
31352 amit.gupta 1537
        if (!(customerOffer.getEndDate().toLocalDate().equals(LocalDate.now()))
1538
                && customerOffer.getEndDate().isBefore(LocalDateTime.now())) {
1539
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(), "Offer is Expired");
29707 tejbeer 1540
 
31352 amit.gupta 1541
        }
29707 tejbeer 1542
 
31352 amit.gupta 1543
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository
1544
                .selectByOfferAndCatalogId(customerOfferItemModel.getOfferId(), customerOfferItemModel.getCatalogId());
29707 tejbeer 1545
 
31352 amit.gupta 1546
        if (!customerOfferItems.isEmpty()) {
29707 tejbeer 1547
 
31352 amit.gupta 1548
            for (CustomerOfferItem coi : customerOfferItems) {
1549
                if (!(coi.getEndDate().equals(LocalDate.now())) && coi.getEndDate().isAfter(LocalDate.now())) {
1550
                    throw new ProfitMandiBusinessException("Catalog Id", coi.getCatalogId(), "Item is already exist.");
1551
                }
1552
            }
29707 tejbeer 1553
 
31352 amit.gupta 1554
        }
29707 tejbeer 1555
 
31352 amit.gupta 1556
        LocalDate startDate = customerOfferItemModel.getStartDate().toLocalDate();
1557
        LocalDate endDate = customerOfferItemModel.getEndDate().toLocalDate();
1558
        CustomerOfferItem coi = new CustomerOfferItem();
1559
        coi.setCatalogId(customerOfferItemModel.getCatalogId());
1560
        coi.setSchemePayout(customerOfferItemModel.getSchemePayout());
1561
        coi.setDealerPayout(customerOfferItemModel.getDealerPayout());
1562
        coi.setCustomerOfferId(customerOfferItemModel.getOfferId());
1563
        coi.setUpdatedTimestamp(LocalDateTime.now());
1564
        coi.setCreatedTimestamp(LocalDateTime.now());
29707 tejbeer 1565
 
31352 amit.gupta 1566
        if ((startDate.equals(customerOffer.getStartDate().toLocalDate())
1567
                || startDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1568
                && (startDate.isEqual(customerOffer.getEndDate().toLocalDate())
1569
                || startDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 1570
 
31352 amit.gupta 1571
            coi.setStartDate(startDate);
29707 tejbeer 1572
 
31352 amit.gupta 1573
        } else {
29707 tejbeer 1574
 
31352 amit.gupta 1575
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1576
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1577
                            + customerOffer.getEndDate());
29707 tejbeer 1578
 
31352 amit.gupta 1579
        }
29707 tejbeer 1580
 
31352 amit.gupta 1581
        if ((endDate.equals(customerOffer.getStartDate().toLocalDate())
1582
                || endDate.isAfter(customerOffer.getStartDate().toLocalDate()))
1583
                && (endDate.isEqual(customerOffer.getEndDate().toLocalDate())
1584
                || endDate.isBefore(customerOffer.getEndDate().toLocalDate()))) {
29707 tejbeer 1585
 
31352 amit.gupta 1586
            coi.setEndDate(endDate);
29707 tejbeer 1587
 
31352 amit.gupta 1588
        } else {
1589
            throw new ProfitMandiBusinessException("Catalog Id", customerOffer.getOfferName(),
1590
                    "Please select accurate duration between " + customerOffer.getStartDate().toLocalDate() + " - "
1591
                            + customerOffer.getEndDate());
1592
        }
31147 tejbeer 1593
 
31352 amit.gupta 1594
        customerOfferItemRepository.persist(coi);
31147 tejbeer 1595
 
31352 amit.gupta 1596
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
31147 tejbeer 1597
 
31352 amit.gupta 1598
        return "response";
29707 tejbeer 1599
 
31352 amit.gupta 1600
    }
31147 tejbeer 1601
 
31352 amit.gupta 1602
    @RequestMapping(value = "/customerOfferItem/download", method = RequestMethod.GET)
1603
    public ResponseEntity<?> downloadOfferItem(HttpServletRequest request, @RequestParam int offerId) throws Exception {
31147 tejbeer 1604
 
31352 amit.gupta 1605
        List<CustomerOfferItem> cois = customerOfferItemRepository.selectByOfferId(offerId);
1606
        List<List<?>> rows = new ArrayList<>();
1607
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
31147 tejbeer 1608
 
31352 amit.gupta 1609
        for (CustomerOfferItem coi : cois) {
1610
            rows.add(Arrays.asList(coi.getId(), coi.getCatalogId(), coi.getSchemePayout(), coi.getDealerPayout(),
1611
                    coi.getStartDate().format(formatter), coi.getEndDate().format(formatter)));
31147 tejbeer 1612
 
31352 amit.gupta 1613
        }
31147 tejbeer 1614
 
31352 amit.gupta 1615
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
1616
                Arrays.asList("id", "Catalog Id", "Scheme Payout", "Dealer Payout", "Start Date", "End Date"), rows);
29707 tejbeer 1617
 
31352 amit.gupta 1618
        final HttpHeaders headers = new HttpHeaders();
1619
        headers.set("Content-Type", "text/csv");
1620
        headers.set("Content-disposition", "inline; filename=customer-offer-template.csv");
1621
        headers.setContentLength(baos.toByteArray().length);
31147 tejbeer 1622
 
31352 amit.gupta 1623
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
1624
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
1625
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
31147 tejbeer 1626
 
31352 amit.gupta 1627
    }
31147 tejbeer 1628
 
31352 amit.gupta 1629
    @RequestMapping(value = "/getCustomerOfferItem", method = RequestMethod.GET)
1630
    public String getCustomerOfferItem(HttpServletRequest request, @RequestParam int offerId, Model model)
1631
            throws Exception {
29707 tejbeer 1632
 
31352 amit.gupta 1633
        List<CustomerOfferItem> customerOfferItems = customerOfferItemRepository.selectByOfferId(offerId);
1634
        List<Integer> catalogIds = customerOfferItems.stream().map(x -> x.getCatalogId()).collect(Collectors.toList());
29707 tejbeer 1635
 
31352 amit.gupta 1636
        Map<Integer, List<Item>> catalogItemMap = itemRepository.selectAllByCatalogIds(new HashSet<>(catalogIds))
1637
                .stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
29707 tejbeer 1638
 
31352 amit.gupta 1639
        model.addAttribute("catalogItemMap", catalogItemMap);
29707 tejbeer 1640
 
31352 amit.gupta 1641
        model.addAttribute("offerId", offerId);
31147 tejbeer 1642
 
31352 amit.gupta 1643
        model.addAttribute("customerOfferItems", customerOfferItems);
1644
        return "customer-offer-item";
31147 tejbeer 1645
 
31352 amit.gupta 1646
    }
31147 tejbeer 1647
 
31352 amit.gupta 1648
    @RequestMapping(value = "/expiredCustomerOfferItem", method = RequestMethod.POST)
1649
    public String expiredCustomerOfferItem(HttpServletRequest request, @RequestParam int id,
1650
                                           @RequestParam LocalDateTime endDate, Model model) throws Exception {
31147 tejbeer 1651
 
31352 amit.gupta 1652
        CustomerOfferItem customerOfferItem = customerOfferItemRepository.selectById(id);
31147 tejbeer 1653
 
31352 amit.gupta 1654
        CustomerOffer customerOffer = customerOfferRepository.selectById(customerOfferItem.getCustomerOfferId());
31147 tejbeer 1655
 
31352 amit.gupta 1656
        if ((endDate.toLocalDate().equals(customerOffer.getStartDate().toLocalDate())
1657
                || endDate.toLocalDate().isAfter(customerOffer.getStartDate().toLocalDate()))
1658
                && (endDate.toLocalDate().isEqual(customerOffer.getEndDate().toLocalDate())
1659
                || endDate.toLocalDate().isBefore(customerOffer.getEndDate().toLocalDate()))) {
31147 tejbeer 1660
 
31352 amit.gupta 1661
            customerOfferItem.setEndDate(endDate.toLocalDate());
31147 tejbeer 1662
 
31352 amit.gupta 1663
        } else {
1664
            throw new ProfitMandiBusinessException("Date", customerOffer.getOfferName(),
1665
                    "customer offer expired on " + customerOffer.getEndDate());
1666
        }
1667
        Map<Integer, List<Item>> catalogItemMap = itemRepository
1668
                .selectAllByCatalogItemId(customerOfferItem.getCatalogId()).stream()
1669
                .collect(Collectors.groupingBy(x -> x.getCatalogItemId()));
1670
        model.addAttribute("catalogItemMap", catalogItemMap);
31147 tejbeer 1671
 
31352 amit.gupta 1672
        model.addAttribute("coi", customerOfferItem);
31147 tejbeer 1673
 
31352 amit.gupta 1674
        return "customer-offer-item-index";
31147 tejbeer 1675
 
31352 amit.gupta 1676
    }
31147 tejbeer 1677
 
31352 amit.gupta 1678
    @RequestMapping(value = "/extendCustomerOffer", method = RequestMethod.POST)
1679
    public String extendCustomerOffer(HttpServletRequest request, @RequestParam int id,
1680
                                      @RequestParam LocalDateTime endDate, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 1681
 
31352 amit.gupta 1682
        CustomerOffer co = customerOfferRepository.selectById(id);
1683
        co.setEndDate(endDate);
1684
        co.setUpdatedTimestamp(LocalDateTime.now());
31147 tejbeer 1685
 
31352 amit.gupta 1686
        model.addAttribute("co", co);
31147 tejbeer 1687
 
31352 amit.gupta 1688
        return "customer-index-offer";
31147 tejbeer 1689
 
31352 amit.gupta 1690
    }
31147 tejbeer 1691
 
31352 amit.gupta 1692
    @RequestMapping(value = "/getSamsungUpgradeOffer", method = RequestMethod.GET)
1693
    public String getSamsungUpgradeOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
31147 tejbeer 1694
 
31352 amit.gupta 1695
        List<UpgradeOfferStatus> uos = UpgradeOfferStatus.offerStatus;
1696
        List<SamsungUpgradeOffer> samsungUpgradeOffers = samsungUpgradeOfferRepository.selectByStatus(
1697
                uos.stream().filter(x -> !x.equals(UpgradeOfferStatus.rejected)).collect(Collectors.toList()));
31147 tejbeer 1698
 
31352 amit.gupta 1699
        model.addAttribute("samsungUpgradeOffers", samsungUpgradeOffers);
1700
        return "samsung-upgrade-offer";
31147 tejbeer 1701
 
31352 amit.gupta 1702
    }
31147 tejbeer 1703
 
31352 amit.gupta 1704
    @RequestMapping(value = "/approveSamsungUpgradeOffer", method = RequestMethod.POST)
1705
    public String approveSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1706
            throws ProfitMandiBusinessException {
29707 tejbeer 1707
 
31352 amit.gupta 1708
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1709
        suo.setStatus(UpgradeOfferStatus.approved);
1710
        suo.setApprovedTimestamp(LocalDateTime.now());
1711
        model.addAttribute("suo", suo);
1712
        return "samsung-upgrade-offer-index";
29707 tejbeer 1713
 
31352 amit.gupta 1714
    }
29707 tejbeer 1715
 
31352 amit.gupta 1716
    @RequestMapping(value = "/rejectSamsungUpgradeOffer", method = RequestMethod.POST)
1717
    public String rejectSamsungUpgradeOffer(HttpServletRequest request, @RequestParam int id, Model model)
1718
            throws ProfitMandiBusinessException {
29707 tejbeer 1719
 
31352 amit.gupta 1720
        SamsungUpgradeOffer suo = samsungUpgradeOfferRepository.selectById(id);
1721
        suo.setStatus(UpgradeOfferStatus.rejected);
29707 tejbeer 1722
 
31352 amit.gupta 1723
        model.addAttribute("suo", suo);
1724
        return "samsung-upgrade-offer-index";
29707 tejbeer 1725
 
31352 amit.gupta 1726
    }
29707 tejbeer 1727
 
22860 ashik.ali 1728
}