Subversion Repositories SmartDukaan

Rev

Rev 31335 | Rev 31379 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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