Subversion Repositories SmartDukaan

Rev

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