Subversion Repositories SmartDukaan

Rev

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

Rev 31662 Rev 31751
Line 81... Line 81...
81
 
81
 
82
@Controller
82
@Controller
83
@Transactional(rollbackOn = Throwable.class)
83
@Transactional(rollbackOn = Throwable.class)
84
public class DashboardController {
84
public class DashboardController {
85
 
85
 
86
	List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
86
    List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com", "amit.gupta@smartdukaan.com", "tejbeer.kaur@smartdukaan.com", "kanan.choudhary@smartdukaan.com");
87
			"amit.gupta@smartdukaan.com", "tejbeer.kaur@smartdukaan.com", "kanan.choudhary@smartdukaan.com");
-
 
88
 
87
 
89
	@Value("${web.api.host}")
88
    @Value("${web.api.host}")
90
	private String webApiHost;
89
    private String webApiHost;
91
 
90
 
92
	@Value("${web.api.scheme}")
91
    @Value("${web.api.scheme}")
93
	private String webApiScheme;
92
    private String webApiScheme;
94
 
93
 
95
	@Autowired
94
    @Autowired
96
	private CsService1 csService1;
95
    private CsService1 csService1;
97
 
96
 
98
	@Value("${web.api.root}")
97
    @Value("${web.api.root}")
99
	private String webApiRoot;
98
    private String webApiRoot;
100
 
99
 
101
	@Value("${web.api.port}")
100
    @Value("${web.api.port}")
102
	private int webApiPort;
101
    private int webApiPort;
103
 
102
 
104
	@Autowired
103
    @Autowired
105
	private PriceDropRepository priceDropRepository;
104
    private PriceDropRepository priceDropRepository;
106
 
105
 
107
	@Autowired
106
    @Autowired
108
	private CookiesProcessor cookiesProcessor;
107
    private CookiesProcessor cookiesProcessor;
109
 
108
 
110
	@Autowired
109
    @Autowired
111
	private PendingOrderRepository pendingOrderRepository;
110
    private PendingOrderRepository pendingOrderRepository;
112
 
111
 
113
	@Autowired
112
    @Autowired
114
	private PartnerStatsService partnerStatsService;
113
    private PartnerStatsService partnerStatsService;
115
 
114
 
116
	@Autowired
115
    @Autowired
117
	private CsService csService;
116
    private CsService csService;
118
 
117
 
119
	@Autowired
118
    @Autowired
120
	private ResponseSender<?> responseSender;
119
    private ResponseSender<?> responseSender;
121
 
120
 
122
	@Autowired
121
    @Autowired
123
	RetailerService retailerService;
122
    RetailerService retailerService;
124
 
123
 
125
	@Autowired
124
    @Autowired
126
	private AdminUser adminUser;
125
    private AdminUser adminUser;
127
 
126
 
128
	@Autowired
127
    @Autowired
129
	private RoleManager roleManager;
128
    private RoleManager roleManager;
130
 
129
 
131
	@Autowired
130
    @Autowired
132
	private FofoStoreRepository fofoStoreRepository;
131
    private FofoStoreRepository fofoStoreRepository;
133
 
132
 
134
	@Autowired
133
    @Autowired
135
	private PartnerInvestmentService partnerInvestmentService;
134
    private PartnerInvestmentService partnerInvestmentService;
136
 
135
 
137
	@Autowired
136
    @Autowired
138
	DocumentRepository documentRepository;
137
    DocumentRepository documentRepository;
139
 
138
 
140
	@Autowired
139
    @Autowired
141
	InventoryItemRepository inventoryItemRepository;
140
    InventoryItemRepository inventoryItemRepository;
142
 
141
 
143
	@Autowired
142
    @Autowired
144
	InventoryService inventoryService;
143
    InventoryService inventoryService;
145
 
144
 
146
	@Autowired
145
    @Autowired
147
	private PendingOrderItemRepository pendingOrderItemRepository;
146
    private PendingOrderItemRepository pendingOrderItemRepository;
148
 
147
 
149
	@Autowired
148
    @Autowired
150
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
149
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
151
 
150
 
152
	@Autowired
151
    @Autowired
153
	private FofoOrderItemRepository fofoOrderItemRepository;
152
    private FofoOrderItemRepository fofoOrderItemRepository;
154
 
153
 
155
	@Autowired
154
    @Autowired
156
	private PartnerTypeChangeService partnerTypeChangeService;
155
    private PartnerTypeChangeService partnerTypeChangeService;
157
 
156
 
158
	@Autowired
157
    @Autowired
159
	private HygieneDataRepository hygieneDataRepository;
158
    private HygieneDataRepository hygieneDataRepository;
160
 
159
 
161
	@Autowired
160
    @Autowired
162
	private UserAccountRepository userAccountRepository;
161
    private UserAccountRepository userAccountRepository;
163
 
162
 
164
	@Autowired
163
    @Autowired
165
	private NotificationCampaignRepository notificationCampaignRepository;
164
    private NotificationCampaignRepository notificationCampaignRepository;
166
 
165
 
167
	@Autowired
166
    @Autowired
168
	private AuthRepository authRepository;
167
    private AuthRepository authRepository;
169
 
168
 
170
	@Autowired
169
    @Autowired
171
	private FofoOrderRepository fofoOrderRepository;
170
    private FofoOrderRepository fofoOrderRepository;
172
 
171
 
173
	@Autowired
172
    @Autowired
174
	private Gson gson;
173
    private Gson gson;
175
 
174
 
176
	@Autowired
175
    @Autowired
177
	TicketRepository ticketRepository;
176
    TicketRepository ticketRepository;
178
 
177
 
179
	@Autowired
178
    @Autowired
180
	private OfferService offerService;
179
    private OfferService offerService;
181
 
180
 
182
	@Autowired
181
    @Autowired
183
	private ItemRepository itemRepository;
182
    private ItemRepository itemRepository;
184
 
183
 
185
	@Autowired
184
    @Autowired
186
	private SaholicInventoryCISRepository saholicInventoryCISRepository;
185
    private SaholicInventoryCISRepository saholicInventoryCISRepository;
187
 
186
 
188
	@Autowired
187
    @Autowired
189
	private MVCResponseSender mvcResponseSender;
188
    private MVCResponseSender mvcResponseSender;
190
 
189
 
191
	@Autowired
190
    @Autowired
192
	private ReporticoCacheTableRepository reporticoCacheTableRepository;
191
    private ReporticoCacheTableRepository reporticoCacheTableRepository;
193
 
192
 
194
	@Autowired
193
    @Autowired
195
	private TransactionService transactionService;
194
    private TransactionService transactionService;
196
 
195
 
197
	@Autowired
196
    @Autowired
198
	private TagListingRepository tagListingRepository;
197
    private TagListingRepository tagListingRepository;
199
 
198
 
200
	@Autowired
199
    @Autowired
201
	private TicketAssignedRepository ticketAssignedRepository;
200
    private TicketAssignedRepository ticketAssignedRepository;
202
 
201
 
203
	@Autowired
202
    @Autowired
204
	private OrderRepository orderRepository;
203
    private OrderRepository orderRepository;
205
 
204
 
206
	@Autowired
205
    @Autowired
207
	private FofoUser fofoUser;
206
    private FofoUser fofoUser;
208
 
207
 
209
	@Autowired
208
    @Autowired
210
	private ActivatedImeiRepository activatedImeiRepository;
209
    private ActivatedImeiRepository activatedImeiRepository;
211
 
210
 
212
	@Autowired
211
    @Autowired
213
	private Mongo mongoClient;
212
    private Mongo mongoClient;
214
 
213
 
215
	@Autowired
214
    @Autowired
216
	private SchemeInOutRepository schemeInOutRepository;
215
    private SchemeInOutRepository schemeInOutRepository;
217
 
216
 
218
	@Autowired
217
    @Autowired
219
	private LineItemRepository lineItemRepository;
218
    private LineItemRepository lineItemRepository;
220
 
219
 
221
	@Autowired
220
    @Autowired
222
	private FofoLineItemRepository fofoLineItemRepository;
221
    private FofoLineItemRepository fofoLineItemRepository;
223
 
222
 
224
	@Autowired
223
    @Autowired
225
	private PositionRepository positionRepository;
224
    private PositionRepository positionRepository;
226
 
225
 
227
	@Autowired
226
    @Autowired
228
	private MonthlyTargetRepository monthlyTargetRepository;
227
    private MonthlyTargetRepository monthlyTargetRepository;
229
 
228
 
230
	@Autowired
229
    @Autowired
231
	private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
230
    private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
232
	private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);
231
    private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);
233
 
232
 
234
	@RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)
233
    @RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)
235
	public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {
234
    public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {
236
		boolean isAdmin = false;
235
        boolean isAdmin = false;
237
		model.addAttribute("isAdmin", isAdmin);
236
        model.addAttribute("isAdmin", isAdmin);
238
 
237
 
239
		model.addAttribute("webApiHost", webApiHost);
238
        model.addAttribute("webApiHost", webApiHost);
240
		model.addAttribute("webApiPort", webApiPort);
239
        model.addAttribute("webApiPort", webApiPort);
241
		model.addAttribute("webApiScheme", webApiScheme);
240
        model.addAttribute("webApiScheme", webApiScheme);
242
		model.addAttribute("webApiRoot", webApiRoot);
241
        model.addAttribute("webApiRoot", webApiRoot);
243
		if (isAdmin) {
242
        if (isAdmin) {
244
			return "dashboard1";
243
            return "dashboard1";
245
		}
244
        }
246
 
245
 
247
		FofoStore fofoStore = null;
246
        FofoStore fofoStore = null;
248
		try {
247
        try {
249
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
248
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
250
			fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
249
            fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
251
			if (!fofoStore.isActive()) {
250
            if (!fofoStore.isActive()) {
252
				return "redirect:/login";
251
                return "redirect:/login";
253
			}
252
            }
254
 
253
 
255
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
254
            PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
256
			model.addAttribute("partnerType", partnerType);
255
            model.addAttribute("partnerType", partnerType);
257
			model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
256
            model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
258
			model.addAttribute("fofoStore", customRetailer);
257
            model.addAttribute("fofoStore", customRetailer);
259
			model.addAttribute("partnerType", partnerType);
258
            model.addAttribute("partnerType", partnerType);
260
			model.addAttribute("hasGift", fofoUser.hasGift(fofoId));
259
            model.addAttribute("hasGift", fofoUser.hasGift(fofoId));
261
			model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
260
            model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
262
 
261
 
263
			model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(fofoId));
262
            model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(fofoId));
264
			model.addAttribute("salesMap", fofoUser.getSales(fofoId));
263
            model.addAttribute("salesMap", fofoUser.getSales(fofoId));
265
			model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
264
            model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
266
			// this.setInvestments
265
            // this.setInvestments
267
			//
266
            //
268
			Map<Integer, String> monthValueMap = new HashMap<>();
267
            Map<Integer, String> monthValueMap = new HashMap<>();
269
			for (int i = 0; i <= 5; i++) {
268
            for (int i = 0; i <= 5; i++) {
270
				LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
269
                LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
271
				monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
270
                monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
272
			}
271
            }
273
			LOGGER.info("monthValueMap" + monthValueMap);
272
            LOGGER.info("monthValueMap" + monthValueMap);
274
			model.addAttribute("monthValueMap", monthValueMap);
273
            model.addAttribute("monthValueMap", monthValueMap);
275
			model.addAttribute("investments", fofoUser.getInvestments(fofoId));
274
            model.addAttribute("investments", fofoUser.getInvestments(fofoId));
276
			model.addAttribute("isInvestmentOk",
275
            model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(fofoId, ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT));
277
					partnerInvestmentService.isInvestmentOk(fofoId, ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT));
276
        } catch (ProfitMandiBusinessException e) {
278
		} catch (ProfitMandiBusinessException e) {
277
            LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);
279
			LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);
278
 
280
 
279
        }
281
		}
280
 
282
 
281
        return "12dashboard34";
283
		return "12dashboard34";
282
    }
284
	}
283
 
285
 
284
    @RequestMapping(value = "/getMonthSale", method = RequestMethod.GET)
286
	@RequestMapping(value = "/getMonthSale", method = RequestMethod.GET)
285
    public String getMonthsale(HttpServletRequest request, Model model) throws Exception {
287
	public String getMonthsale(HttpServletRequest request, Model model) throws Exception {
286
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
288
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
287
        int fofoId = loginDetails.getFofoId();
289
		int fofoId = loginDetails.getFofoId();
288
        Map<Integer, MonthSaleModel> monthSaleMap = new HashMap<>();
290
		Map<Integer, MonthSaleModel> monthSaleMap = new HashMap<>();
289
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
291
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
290
        int dayOfMonth = curDate.getDayOfMonth();
292
		int dayOfMonth = curDate.getDayOfMonth();
291
        for (int i = 1; i <= 6; i++) {
293
		for (int i = 1; i <= 6; i++) {
292
            LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
294
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
293
            int lengthOfMonth = YearMonth.from(startOfMonth).lengthOfMonth();
295
			int lengthOfMonth = YearMonth.from(startOfMonth).lengthOfMonth();
294
            LOGGER.info("Start of previous Month {}, start of next month Month {}", startOfMonth, startOfMonth.plusMonths(1));
296
			LOGGER.info("Start of previous Month {}, start of next month Month {}", startOfMonth,
295
            double monthSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth, startOfMonth.plusMonths(1), loginDetails.getFofoId(), false).get(fofoId);
297
					startOfMonth.plusMonths(1));
296
 
298
			double monthSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth,
297
            double mtdSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth, startOfMonth.plusDays(Math.min(dayOfMonth, lengthOfMonth)), loginDetails.getFofoId(), false).get(fofoId);
299
					startOfMonth.plusMonths(1), loginDetails.getFofoId(), false).get(fofoId);
298
 
300
 
299
            PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth.toLocalDate());
301
			double mtdSales = fofoOrderItemRepository
300
 
302
					.selectSumMopGroupByRetailer(startOfMonth,
301
            MonthSaleModel ms = new MonthSaleModel();
303
							startOfMonth.plusDays(Math.min(dayOfMonth, lengthOfMonth)), loginDetails.getFofoId(), false)
302
            ms.setMtdSales(fofoUser.format((long) mtdSales));
304
					.get(fofoId);
303
            ms.setMonthlySales(fofoUser.format(((long) monthSales)));
305
 
304
            ms.setPartnerType(partnerType);
306
			PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, startOfMonth.toLocalDate());
305
            ms.setMonth(startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
307
 
306
            monthSaleMap.put(i, ms);
308
			MonthSaleModel ms = new MonthSaleModel();
307
        }
309
			ms.setMtdSales(fofoUser.format((long) mtdSales));
308
 
310
			ms.setMonthlySales(fofoUser.format(((long) monthSales)));
309
        model.addAttribute("monthSales", monthSaleMap);
311
			ms.setPartnerType(partnerType);
310
        return "monthSales";
312
			ms.setMonth(startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
311
    }
313
			monthSaleMap.put(i, ms);
312
 
314
		}
313
    @RequestMapping(value = "/dashboard", method = RequestMethod.GET)
315
 
314
    public String dashboard(HttpServletRequest request, Model model) throws Exception {
316
		model.addAttribute("monthSales", monthSaleMap);
315
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
317
		return "monthSales";
316
        String email = loginDetails.getEmailId();
318
	}
317
        int fofoId = loginDetails.getFofoId();
319
 
318
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
320
	@RequestMapping(value = "/dashboard", method = RequestMethod.GET)
319
        model.addAttribute("isAdmin", isAdmin);
321
	public String dashboard(HttpServletRequest request, Model model) throws Exception {
320
 
322
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
321
        model.addAttribute("webApiHost", webApiHost);
323
		String email = loginDetails.getEmailId();
322
        model.addAttribute("webApiPort", webApiPort);
324
		int fofoId = loginDetails.getFofoId();
323
        model.addAttribute("webApiScheme", webApiScheme);
325
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
324
        model.addAttribute("webApiRoot", webApiRoot);
326
		model.addAttribute("isAdmin", isAdmin);
325
        if (isAdmin) {
327
 
326
            return adminUser.adminPanel(loginDetails.getFofoId(), email, model);
328
		model.addAttribute("webApiHost", webApiHost);
327
        } else {
329
		model.addAttribute("webApiPort", webApiPort);
328
            FofoStore fofoStore = null;
330
		model.addAttribute("webApiScheme", webApiScheme);
329
            try {
331
		model.addAttribute("webApiRoot", webApiRoot);
330
                fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
332
		if (isAdmin) {
331
                if (!fofoStore.isActive()) {
333
			return adminUser.adminPanel(loginDetails.getFofoId(), email, model);
332
                    return "redirect:/login";
334
		} else {
333
                }
335
			FofoStore fofoStore = null;
334
 
336
			try {
335
                LocalDateTime startDate = LocalDate.now().withDayOfYear(1).atStartOfDay();
337
				fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
336
                LocalDateTime endtDate = LocalDateTime.now();
338
				if (!fofoStore.isActive()) {
337
                OnlineDeliveredOrderSum onlineDeliveredOrderSum = pendingOrderItemRepository.selectSumSellingPriceOnlineOrder(fofoId, startDate, endtDate);
339
					return "redirect:/login";
338
                LOGGER.info("onlineDeliveredOrderSum" + onlineDeliveredOrderSum.getSellingPrice());
340
				}
339
 
341
 
340
                long countOrder = pendingOrderRepository.pendingOrderCount(fofoId, OrderStatus.PROCESSING);
342
				LocalDateTime startDate = LocalDate.now().withDayOfYear(1).atStartOfDay();
341
                LOGGER.info("countOrder" + countOrder);
343
				LocalDateTime endtDate = LocalDateTime.now();
342
 
344
				OnlineDeliveredOrderSum onlineDeliveredOrderSum = pendingOrderItemRepository
343
                ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
345
						.selectSumSellingPriceOnlineOrder(fofoId, startDate, endtDate);
344
 
346
				LOGGER.info("onlineDeliveredOrderSum" + onlineDeliveredOrderSum.getSellingPrice());
345
                orderStatus.add(SUBMITTED_FOR_PROCESSING);
347
 
346
                orderStatus.add(BILLED);
348
				long countOrder = pendingOrderRepository.pendingOrderCount(fofoId, OrderStatus.PROCESSING);
347
                orderStatus.add(SHIPPED_FROM_WH);
349
				LOGGER.info("countOrder" + countOrder);
348
                orderStatus.add(DELIVERY_SUCCESS);
350
 
349
 
351
				ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
350
                List<Order> openOrders = orderRepository.selectGrnTimestampNull(fofoId, orderStatus);
352
 
351
                List<LineItem> submittedLineItemIds = openOrders.stream().filter(x -> x.getStatus().equals(SUBMITTED_FOR_PROCESSING)).map(x -> x.getLineItem()).collect(Collectors.toList());
353
				orderStatus.add(SUBMITTED_FOR_PROCESSING);
352
                List<LineItem> billedOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(BILLED)).map(x -> x.getLineItem()).collect(Collectors.toList());
354
				orderStatus.add(BILLED);
353
                List<LineItem> shippedOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(SHIPPED_FROM_WH)).map(x -> x.getLineItem()).collect(Collectors.toList());
355
				orderStatus.add(SHIPPED_FROM_WH);
354
                List<LineItem> grnPendingLineItemIds = openOrders.stream().filter(x -> x.getStatus().equals(DELIVERY_SUCCESS)).map(x -> x.getLineItem()).collect(Collectors.toList());
356
				orderStatus.add(DELIVERY_SUCCESS);
355
 
357
 
356
                long imeiActivationPendingCount = 0;
358
				List<Order> openOrders = orderRepository.selectGrnTimestampNull(fofoId, orderStatus);
357
                long imeiActivationPendingValue = 0;
359
				List<LineItem> submittedLineItemIds = openOrders.stream()
358
                List<Integer> grnPendingOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(SHIPPED_FROM_WH) || x.getStatus().equals(DELIVERY_SUCCESS)).map(x -> x.getId()).collect(Collectors.toList());
360
						.filter(x -> x.getStatus().equals(SUBMITTED_FOR_PROCESSING)).map(x -> x.getLineItem())
359
                if (grnPendingOrderIds.size() > 0) {
361
						.collect(Collectors.toList());
360
                    List<ImeiActivationTimestampModel> imeiActivationTimestampModels = activatedImeiRepository.selectActivatedImeisByOrders(grnPendingOrderIds);
362
				List<LineItem> billedOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(BILLED))
361
                    imeiActivationPendingCount = imeiActivationTimestampModels.size();
363
						.map(x -> x.getLineItem()).collect(Collectors.toList());
362
                    imeiActivationPendingValue = imeiActivationTimestampModels.stream().collect(Collectors.summingDouble(x -> x.getSellingPrice())).longValue();
364
				List<LineItem> shippedOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(SHIPPED_FROM_WH))
363
                }
365
						.map(x -> x.getLineItem()).collect(Collectors.toList());
364
 
366
				List<LineItem> grnPendingLineItemIds = openOrders.stream()
365
                long grnPendingCount = grnPendingLineItemIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
367
						.filter(x -> x.getStatus().equals(DELIVERY_SUCCESS)).map(x -> x.getLineItem())
366
                long grnPendingValue = grnPendingLineItemIds.stream().collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
368
						.collect(Collectors.toList());
367
                model.addAttribute("grnPendingCount", grnPendingCount);
369
 
368
                model.addAttribute("grnPendingValue", grnPendingValue);
370
				long imeiActivationPendingCount = 0;
369
 
371
				long imeiActivationPendingValue = 0;
370
                long submittedCount = submittedLineItemIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
372
				List<Integer> grnPendingOrderIds = openOrders.stream()
371
                long submittedValue = submittedLineItemIds.stream().collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
373
						.filter(x -> x.getStatus().equals(SHIPPED_FROM_WH) || x.getStatus().equals(DELIVERY_SUCCESS))
372
                model.addAttribute("submittedCount", submittedCount);
374
						.map(x -> x.getId()).collect(Collectors.toList());
373
                model.addAttribute("submittedValue", submittedValue);
375
				if (grnPendingOrderIds.size() > 0) {
374
 
376
					List<ImeiActivationTimestampModel> imeiActivationTimestampModels = activatedImeiRepository
375
                long billedCount = billedOrderIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
377
							.selectActivatedImeisByOrders(grnPendingOrderIds);
376
                long billedValue = billedOrderIds.stream().collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
378
					imeiActivationPendingCount = imeiActivationTimestampModels.size();
377
                model.addAttribute("billedValue", billedValue);
379
					imeiActivationPendingValue = imeiActivationTimestampModels.stream()
378
                model.addAttribute("billedCount", billedCount);
380
							.collect(Collectors.summingDouble(x -> x.getSellingPrice())).longValue();
379
                LOGGER.info("billedCount {}", billedCount);
381
				}
380
 
382
 
381
                long shippedCount = shippedOrderIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
383
				long grnPendingCount = grnPendingLineItemIds.stream()
382
                model.addAttribute("shippedCount", shippedCount);
384
						.collect(Collectors.summingLong(LineItem::getQuantity));
383
                LOGGER.info("shippedCount {}", shippedCount);
385
				long grnPendingValue = grnPendingLineItemIds.stream()
384
                long shippedValue = shippedOrderIds.stream().collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
386
						.collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
385
                model.addAttribute("shippedValue", shippedValue);
387
				model.addAttribute("grnPendingCount", grnPendingCount);
386
 
388
				model.addAttribute("grnPendingValue", grnPendingValue);
387
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
389
 
388
 
390
				long submittedCount = submittedLineItemIds.stream()
389
                LocalDateTime currentMonthStart = curDate.withDayOfMonth(1);
391
						.collect(Collectors.summingLong(LineItem::getQuantity));
390
                LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
392
				long submittedValue = submittedLineItemIds.stream()
391
                LocalDateTime currentMonthEnd = currentMonthStart.withDayOfMonth(1);
393
						.collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
392
 
394
				model.addAttribute("submittedCount", submittedCount);
393
                LOGGER.info("lastMonthStart" + lastMonthStart);
395
				model.addAttribute("submittedValue", submittedValue);
394
                LOGGER.info("currentMonthEnd" + currentMonthEnd);
396
 
395
 
397
				long billedCount = billedOrderIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
396
                model.addAttribute("countOrder", countOrder);
398
				long billedValue = billedOrderIds.stream()
397
                model.addAttribute("onlineDeliveredOrderSum", onlineDeliveredOrderSum.getSellingPrice());
399
						.collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
398
 
400
				model.addAttribute("billedValue", billedValue);
399
                PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
401
				model.addAttribute("billedCount", billedCount);
400
                model.addAttribute("partnerType", partnerType);
402
				LOGGER.info("billedCount {}", billedCount);
401
                model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
403
 
402
                model.addAttribute("fofoStore", fofoStore);
404
				long shippedCount = shippedOrderIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
403
                model.addAttribute("partnerType", partnerType);
405
				model.addAttribute("shippedCount", shippedCount);
404
                model.addAttribute("hasGift", fofoUser.hasGift(loginDetails.getFofoId()));
406
				LOGGER.info("shippedCount {}", shippedCount);
405
                model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
407
				long shippedValue = shippedOrderIds.stream()
406
                model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode()).append("partnerId", fofoStore.getId()).toString());
408
						.collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
407
                model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
409
				model.addAttribute("shippedValue", shippedValue);
408
                model.addAttribute("imeiActivationPendingCount", imeiActivationPendingCount);
410
 
409
                model.addAttribute("imeiActivationPendingValue", imeiActivationPendingValue);
411
				LocalDateTime curDate = LocalDate.now().atStartOfDay();
410
 
412
 
411
                Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(), curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
413
				LocalDateTime currentMonthStart = curDate.withDayOfMonth(1);
412
 
414
				LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
413
                Double accesoriesStock = currentInventorySnapshotRepository.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(), Optional.of(false)).get(loginDetails.getFofoId());
415
				LocalDateTime currentMonthEnd = currentMonthStart.withDayOfMonth(1);
414
 
416
 
415
                model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
417
				LOGGER.info("lastMonthStart" + lastMonthStart);
416
                model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(loginDetails.getFofoId()));
418
				LOGGER.info("currentMonthEnd" + currentMonthEnd);
417
                model.addAttribute("salesMap", fofoUser.getSales(loginDetails.getFofoId()));
419
 
418
                ChartModel cm = fofoUser.getBrandChart(loginDetails.getFofoId());
420
				model.addAttribute("countOrder", countOrder);
419
 
421
				model.addAttribute("onlineDeliveredOrderSum", onlineDeliveredOrderSum.getSellingPrice());
420
                LOGGER.info("chartMap" + gson.toJson(cm));
422
 
421
                model.addAttribute("chartMap", gson.toJson(cm));
423
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
422
 
424
				model.addAttribute("partnerType", partnerType);
423
                List<CreateOfferRequest> publishedOffers = offerService.getPublishedOffers(loginDetails.getFofoId(), YearMonth.from(LocalDateTime.now()));
425
				model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
424
                model.addAttribute("publishedOffers", publishedOffers);
426
				model.addAttribute("fofoStore", fofoStore);
425
                model.addAttribute("investments", fofoUser.getInvestments(loginDetails.getFofoId()));
427
				model.addAttribute("partnerType", partnerType);
426
                model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(), ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT));
428
				model.addAttribute("hasGift", fofoUser.hasGift(loginDetails.getFofoId()));
427
 
429
				model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
428
                double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart, currentMonthEnd) / 2;
430
				model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode())
429
                double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart, currentMonthStart) / 2;
431
						.append("partnerId", fofoStore.getId()).toString());
430
                double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN, currentMonthEnd) / 2;
432
				model.addAttribute("activatedImeis",
431
                model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
433
						inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
432
                model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
434
				model.addAttribute("imeiActivationPendingCount", imeiActivationPendingCount);
433
                model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
435
				model.addAttribute("imeiActivationPendingValue", imeiActivationPendingValue);
434
 
436
 
435
                long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart, currentMonthEnd);
437
				Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository
436
 
438
						.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
437
                long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false, currentMonthStart, currentMonthEnd);
439
								curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
438
                if (hygieneCount == 0 && invalidHygieneCount == 0) {
440
 
439
                    invalidHygieneCount = 1;
441
				Double accesoriesStock = currentInventorySnapshotRepository
440
                }
442
						.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(),
441
                Map<Integer, String> monthValueMap = new HashMap<>();
443
								Optional.of(false))
442
                for (int i = 0; i <= 5; i++) {
444
						.get(loginDetails.getFofoId());
443
                    LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
445
 
444
                    monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
446
				model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
445
                }
447
				model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(loginDetails.getFofoId()));
446
 
448
				model.addAttribute("salesMap", fofoUser.getSales(loginDetails.getFofoId()));
447
                MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
449
				ChartModel cm = fofoUser.getBrandChart(loginDetails.getFofoId());
448
                model.addAttribute("monthlyTarget", monthlyTarget);
450
 
449
 
451
				LOGGER.info("chartMap" + gson.toJson(cm));
450
                model.addAttribute("monthValueMap", monthValueMap);
452
				model.addAttribute("chartMap", gson.toJson(cm));
451
                model.addAttribute("month", 0);
453
 
452
                model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
454
				List<CreateOfferRequest> publishedOffers = offerService.getPublishedOffers(loginDetails.getFofoId(),
453
                model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
455
						YearMonth.from(LocalDateTime.now()));
454
                model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
456
				model.addAttribute("publishedOffers", publishedOffers);
455
 
457
				model.addAttribute("investments", fofoUser.getInvestments(loginDetails.getFofoId()));
456
            } catch (ProfitMandiBusinessException e) {
458
				model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(),
457
                LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
459
						ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT));
458
 
460
 
459
            }
461
				double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(),
460
            return "dashboard1";
462
						currentMonthStart, currentMonthEnd) / 2;
461
        }
463
				double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
462
 
464
						currentMonthStart) / 2;
463
    }
465
				double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(),
464
 
466
						LocalDateTime.MIN, currentMonthEnd) / 2;
465
    @RequestMapping(value = "/getGrnPendingOrderStatus", method = RequestMethod.GET)
467
				model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
466
    public String getGrnPendingOrderStatus(HttpServletRequest request, Model model) throws Exception {
468
				model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
467
 
469
				model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
468
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
470
 
469
        int fofoId = loginDetails.getFofoId();
471
				long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true,
470
        List<Order> grnPendingOrders = orderRepository.selectGrnTimestampNull(fofoId, Arrays.asList(in.shop2020.model.v1.order.OrderStatus.DELIVERY_SUCCESS));
472
						currentMonthStart, currentMonthEnd);
471
 
473
 
472
        model.addAttribute("grnPendingOrders", grnPendingOrders);
474
				long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
473
        return "purchase-grn-order-status";
475
						currentMonthStart, currentMonthEnd);
474
    }
476
				if (hygieneCount == 0 && invalidHygieneCount == 0) {
475
 
477
					invalidHygieneCount = 1;
476
    @RequestMapping(value = "/getPendingOrderStatus", method = RequestMethod.GET)
478
				}
477
    public String getPendingOrderStatus(HttpServletRequest request, Model model) throws Exception {
479
				Map<Integer, String> monthValueMap = new HashMap<>();
478
 
480
				for (int i = 0; i <= 5; i++) {
479
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
481
					LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
480
        int fofoId = loginDetails.getFofoId();
482
					monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
481
        ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
483
				}
482
 
484
 
483
        orderStatus.add(in.shop2020.model.v1.order.OrderStatus.SUBMITTED_FOR_PROCESSING);
485
				MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
484
 
486
				model.addAttribute("monthlyTarget", monthlyTarget);
485
        List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
487
 
486
        List<Integer> submittedOrderIds = order.stream().filter(x -> x.getStatus() == in.shop2020.model.v1.order.OrderStatus.SUBMITTED_FOR_PROCESSING).map(x -> x.getId()).collect(Collectors.toList());
488
				model.addAttribute("monthValueMap", monthValueMap);
487
        model.addAttribute("submittedOrderIds", submittedOrderIds);
489
				model.addAttribute("month", 0);
488
        if (!submittedOrderIds.isEmpty()) {
490
				model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
489
 
491
				model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
490
            List<LineItem> submittedLineItem = lineItemRepository.selectLineItem(submittedOrderIds);
492
				model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
491
            Map<Integer, LineItem> submittedLineItemMap = submittedLineItem.stream().collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
493
 
492
            LOGGER.info("submittedLineItemMap {}", submittedLineItemMap);
494
			} catch (ProfitMandiBusinessException e) {
493
            model.addAttribute("submittedLineItemMap", submittedLineItemMap);
495
				LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
494
        }
496
 
495
 
497
			}
496
        return "purchase-pending-order-status";
498
			return "dashboard1";
497
    }
499
		}
498
 
500
 
499
    @RequestMapping(value = "/getBilledOrderStatus", method = RequestMethod.GET)
501
	}
500
    public String getBilledOrderStatus(HttpServletRequest request, Model model) throws Exception {
502
 
501
 
503
	@RequestMapping(value = "/getGrnPendingOrderStatus", method = RequestMethod.GET)
502
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
504
	public String getGrnPendingOrderStatus(HttpServletRequest request, Model model) throws Exception {
503
        int fofoId = loginDetails.getFofoId();
505
 
504
        ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
506
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
505
        orderStatus.add(in.shop2020.model.v1.order.OrderStatus.BILLED);
507
		int fofoId = loginDetails.getFofoId();
506
 
508
		List<Order> grnPendingOrders = orderRepository.selectGrnTimestampNull(fofoId,
507
        List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
509
				Arrays.asList(in.shop2020.model.v1.order.OrderStatus.DELIVERY_SUCCESS));
508
        List<Integer> billedOrderIds = order.stream().filter(x -> x.getStatus() == in.shop2020.model.v1.order.OrderStatus.BILLED).map(x -> x.getId()).collect(Collectors.toList());
510
 
509
        LOGGER.info("billedOrderIds {}", billedOrderIds);
511
		model.addAttribute("grnPendingOrders", grnPendingOrders);
510
        model.addAttribute("billedOrderIds", billedOrderIds);
512
		return "purchase-grn-order-status";
511
 
513
	}
512
        if (!billedOrderIds.isEmpty()) {
514
 
513
            List<LineItem> billedLineItem = lineItemRepository.selectLineItem(billedOrderIds);
515
	@RequestMapping(value = "/getPendingOrderStatus", method = RequestMethod.GET)
514
            Map<Integer, LineItem> billedLineItemMap = billedLineItem.stream().collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
516
	public String getPendingOrderStatus(HttpServletRequest request, Model model) throws Exception {
515
            LOGGER.info("billedLineItemMap {}", billedLineItemMap);
517
 
516
            model.addAttribute("billedLineItemMap", billedLineItemMap);
518
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
517
        }
519
		int fofoId = loginDetails.getFofoId();
518
 
520
		ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
519
        return "purchase-billed-order-status";
521
 
520
    }
522
		orderStatus.add(in.shop2020.model.v1.order.OrderStatus.SUBMITTED_FOR_PROCESSING);
521
 
523
 
522
    @RequestMapping(value = "/getShippedOrderStatus", method = RequestMethod.GET)
524
		List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
523
    public String getShippedOrderStatus(HttpServletRequest request, Model model) throws Exception {
525
		List<Integer> submittedOrderIds = order.stream()
524
 
526
				.filter(x -> x.getStatus() == in.shop2020.model.v1.order.OrderStatus.SUBMITTED_FOR_PROCESSING)
525
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
527
				.map(x -> x.getId()).collect(Collectors.toList());
526
        int fofoId = loginDetails.getFofoId();
528
		model.addAttribute("submittedOrderIds", submittedOrderIds);
527
        ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
529
		if (!submittedOrderIds.isEmpty()) {
528
 
530
 
529
        orderStatus.add(SHIPPED_FROM_WH);
531
			List<LineItem> submittedLineItem = lineItemRepository.selectLineItem(submittedOrderIds);
530
 
532
			Map<Integer, LineItem> submittedLineItemMap = submittedLineItem.stream()
531
        List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
533
					.collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
532
        List<Integer> shippedOrderIds = order.stream().filter(x -> x.getPartnerGrnTimestamp() == null).map(x -> x.getId()).collect(Collectors.toList());
534
			LOGGER.info("submittedLineItemMap {}", submittedLineItemMap);
533
        model.addAttribute("shippedOrderIds", shippedOrderIds);
535
			model.addAttribute("submittedLineItemMap", submittedLineItemMap);
534
        LOGGER.info("shippedOrderIds {}", shippedOrderIds);
536
		}
535
 
537
 
536
        if (!shippedOrderIds.isEmpty()) {
538
		return "purchase-pending-order-status";
537
            List<LineItem> shippedLineItem = lineItemRepository.selectLineItem(shippedOrderIds);
539
	}
538
            Map<Integer, LineItem> shippedLineItemMap = shippedLineItem.stream().collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
540
 
539
            LOGGER.info("shippedLineItemMap {}", shippedLineItemMap);
541
	@RequestMapping(value = "/getBilledOrderStatus", method = RequestMethod.GET)
540
 
542
	public String getBilledOrderStatus(HttpServletRequest request, Model model) throws Exception {
541
            model.addAttribute("shippedLineItemMap", shippedLineItemMap);
543
 
542
        }
544
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
543
        return "purchase-shipped-order-status";
545
		int fofoId = loginDetails.getFofoId();
544
    }
546
		ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
545
 
547
		orderStatus.add(in.shop2020.model.v1.order.OrderStatus.BILLED);
546
    @Autowired
548
 
547
    OfferRepository offerRepository;
549
		List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
548
 
550
		List<Integer> billedOrderIds = order.stream()
549
    @Autowired
551
				.filter(x -> x.getStatus() == in.shop2020.model.v1.order.OrderStatus.BILLED).map(x -> x.getId())
550
    OfferPayoutRepository offerPayoutRepository;
552
				.collect(Collectors.toList());
551
 
553
		LOGGER.info("billedOrderIds {}", billedOrderIds);
552
    @RequestMapping(value = "/partnerTotalIncomeByMonth/{yearMonth}", method = RequestMethod.GET)
554
		model.addAttribute("billedOrderIds", billedOrderIds);
553
    public String getPartnerTotalIncomeByMonth(HttpServletRequest request, @PathVariable int yearMonth, Model model) throws Exception {
555
 
554
 
556
		if (!billedOrderIds.isEmpty()) {
555
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
557
			List<LineItem> billedLineItem = lineItemRepository.selectLineItem(billedOrderIds);
556
        long pendingIncome = 0;
558
			Map<Integer, LineItem> billedLineItemMap = billedLineItem.stream()
557
        long partnerPurchaseIn = 0;
559
					.collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
558
        long partnerCreditedSale = 0;
560
			LOGGER.info("billedLineItemMap {}", billedLineItemMap);
559
        long partnerFrontIncome = 0;
561
			model.addAttribute("billedLineItemMap", billedLineItemMap);
560
 
562
		}
561
        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
563
 
562
        LocalDateTime endOfMonth = startOfMonth.plusMonths(1).toLocalDate().atStartOfDay();
564
		return "purchase-billed-order-status";
563
 
565
	}
564
        AllPurchaseInventoryModel partnerlPendingSaleAmount = schemeInOutRepository.selectAllPendingSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
566
 
565
        AllPurchaseInventoryModel partnerCreditedSaleAmount = schemeInOutRepository.selectAllCreditedSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
567
	@RequestMapping(value = "/getShippedOrderStatus", method = RequestMethod.GET)
566
        AllPurchaseInventoryModel partnerPurchaseInAmount = schemeInOutRepository.selectAllPurchaseInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
568
	public String getShippedOrderStatus(HttpServletRequest request, Model model) throws Exception {
567
 
569
 
568
        AllPurchaseInventoryModel partnerFrontIncomes = schemeInOutRepository.selectFrontIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
570
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
569
 
571
		int fofoId = loginDetails.getFofoId();
570
        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()), loginDetails.getFofoId(), null, null);
572
		ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
571
 
573
 
572
        long additionalIncome = offerPayoutImeiIncomeModels.stream().collect(Collectors.summingDouble(x -> x.getSalePayout() + x.getPurchasePayout())).longValue();
574
		orderStatus.add(SHIPPED_FROM_WH);
573
        // AllPurchaseInventoryModel partnerAdditionalIncome =
575
 
574
        // offerRepository.selectPurchaseIncome(loginDetails.getFofoId(), startOfMonth,
576
		List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
575
        // endOfMonth);
577
		List<Integer> shippedOrderIds = order.stream().filter(x -> x.getPartnerGrnTimestamp() == null)
576
 
578
				.map(x -> x.getId()).collect(Collectors.toList());
577
        LOGGER.info("partnerfrontIncomes" + partnerFrontIncomes);
579
		model.addAttribute("shippedOrderIds", shippedOrderIds);
578
 
580
		LOGGER.info("shippedOrderIds {}", shippedOrderIds);
579
        LOGGER.info("partnerCreditedSaleAmount" + partnerCreditedSaleAmount);
581
 
580
        LOGGER.info("partnerPurchaseInAmount" + partnerPurchaseInAmount);
582
		if (!shippedOrderIds.isEmpty()) {
581
        LOGGER.info("partnerlPendingSaleAmount" + partnerlPendingSaleAmount);
583
			List<LineItem> shippedLineItem = lineItemRepository.selectLineItem(shippedOrderIds);
582
 
584
			Map<Integer, LineItem> shippedLineItemMap = shippedLineItem.stream()
583
        if (partnerlPendingSaleAmount != null) {
585
					.collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
584
 
586
			LOGGER.info("shippedLineItemMap {}", shippedLineItemMap);
585
            pendingIncome = partnerlPendingSaleAmount.getAmount();
587
 
586
 
588
			model.addAttribute("shippedLineItemMap", shippedLineItemMap);
587
            LOGGER.info("pendingIncome" + pendingIncome);
589
		}
588
 
590
		return "purchase-shipped-order-status";
589
        }
591
	}
590
 
592
 
591
        if (partnerCreditedSaleAmount != null) {
593
	@Autowired
592
 
594
	OfferRepository offerRepository;
593
            partnerCreditedSale = partnerCreditedSaleAmount.getAmount();
595
 
594
 
596
	@Autowired
595
            LOGGER.info("partnerCreditedSale" + partnerCreditedSale);
597
	OfferPayoutRepository offerPayoutRepository;
596
 
598
 
597
        }
599
	@RequestMapping(value = "/partnerTotalIncomeByMonth/{yearMonth}", method = RequestMethod.GET)
598
        if (partnerFrontIncomes != null) {
600
	public String getPartnerTotalIncomeByMonth(HttpServletRequest request, @PathVariable int yearMonth, Model model)
599
 
601
			throws Exception {
600
            partnerFrontIncome = partnerFrontIncomes.getAmount();
602
 
601
            LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);
603
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
602
 
604
		long pendingIncome = 0;
603
        }
605
		long partnerPurchaseIn = 0;
604
        if (partnerPurchaseInAmount != null) {
606
		long partnerCreditedSale = 0;
605
 
607
		long partnerFrontIncome = 0;
606
            partnerPurchaseIn = partnerPurchaseInAmount.getAmount();
608
 
607
            LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);
609
		LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
608
 
610
		LocalDateTime endOfMonth = startOfMonth.plusMonths(1).toLocalDate().atStartOfDay();
609
        }
611
 
610
 
612
		AllPurchaseInventoryModel partnerlPendingSaleAmount = schemeInOutRepository
611
        LOGGER.info("partnerPurchaseInTT" + partnerPurchaseIn);
613
				.selectAllPendingSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
612
        LOGGER.info("partnerCreditedSaleTT" + partnerCreditedSale);
614
		AllPurchaseInventoryModel partnerCreditedSaleAmount = schemeInOutRepository
613
        LOGGER.info("pendingIncomeTT" + pendingIncome);
615
				.selectAllCreditedSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
614
 
616
		AllPurchaseInventoryModel partnerPurchaseInAmount = schemeInOutRepository
615
        long totalIncome = partnerCreditedSale + partnerPurchaseIn + pendingIncome + partnerFrontIncome + additionalIncome;
617
				.selectAllPurchaseInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
616
 
618
 
617
        long creditedIncome = partnerCreditedSale + partnerPurchaseIn + partnerFrontIncome + additionalIncome;
619
		AllPurchaseInventoryModel partnerFrontIncomes = schemeInOutRepository
618
 
620
				.selectFrontIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
619
        long pendingTotalIncome = pendingIncome;
621
 
620
        LOGGER.info("totalIncome" + totalIncome);
622
		List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository
621
        LOGGER.info("creditedIncome" + creditedIncome);
623
				.getTotalPayoutsByPartnerPeriod(YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()),
622
        LOGGER.info("pendingTotalIncome" + pendingTotalIncome);
624
						loginDetails.getFofoId(), null, null);
623
 
625
 
624
        model.addAttribute("totalIncome", totalIncome);
626
		long additionalIncome = offerPayoutImeiIncomeModels.stream()
625
        model.addAttribute("creditedIncome", creditedIncome);
627
				.collect(Collectors.summingDouble(x -> x.getSalePayout() + x.getPurchasePayout())).longValue();
626
        model.addAttribute("pendingTotalIncome", pendingTotalIncome);
628
		// AllPurchaseInventoryModel partnerAdditionalIncome =
627
 
629
		// offerRepository.selectPurchaseIncome(loginDetails.getFofoId(), startOfMonth,
628
        Map<Integer, String> monthValueMap = new HashMap<>();
630
		// endOfMonth);
629
        for (int i = 0; i <= 5; i++) {
631
 
630
            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
632
		LOGGER.info("partnerfrontIncomes" + partnerFrontIncomes);
631
            monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
633
 
632
        }
634
		LOGGER.info("partnerCreditedSaleAmount" + partnerCreditedSaleAmount);
633
 
635
		LOGGER.info("partnerPurchaseInAmount" + partnerPurchaseInAmount);
634
        model.addAttribute("month", yearMonth);
636
		LOGGER.info("partnerlPendingSaleAmount" + partnerlPendingSaleAmount);
635
        model.addAttribute("monthValueMap", monthValueMap);
637
 
636
 
638
		if (partnerlPendingSaleAmount != null) {
637
        return "partner-total-income";
639
 
638
    }
640
			pendingIncome = partnerlPendingSaleAmount.getAmount();
639
 
641
 
640
    @RequestMapping(value = "/getMonthsInvestment", method = RequestMethod.GET)
642
			LOGGER.info("pendingIncome" + pendingIncome);
641
    public String getMonthsInvestment(HttpServletRequest request, @RequestParam(name = "month", required = true, defaultValue = "0") int month, Model model) throws Exception {
643
 
642
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
644
		}
643
        int fofoId = loginDetails.getFofoId();
645
 
644
        Map<String, Object> investment = fofoUser.getInvestmentsMonths(fofoId, month);
646
		if (partnerCreditedSaleAmount != null) {
645
 
647
 
646
        LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
648
			partnerCreditedSale = partnerCreditedSaleAmount.getAmount();
647
        LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
649
 
648
        LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
650
			LOGGER.info("partnerCreditedSale" + partnerCreditedSale);
649
        double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart, currentMonthEnd) / 2;
651
 
650
        double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart, currentMonthStart) / 2;
652
		}
651
        double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN, currentMonthEnd) / 2;
653
		if (partnerFrontIncomes != null) {
652
        model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
654
 
653
        model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
655
			partnerFrontIncome = partnerFrontIncomes.getAmount();
654
        model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
656
			LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);
655
 
657
 
656
        long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
658
		}
657
 
659
		if (partnerPurchaseInAmount != null) {
658
        long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false, currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
660
 
659
        if (hygieneCount == 0 && invalidHygieneCount == 0) {
661
			partnerPurchaseIn = partnerPurchaseInAmount.getAmount();
660
            invalidHygieneCount = 1;
662
			LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);
661
        }
663
 
662
        Map<Integer, String> monthValueMap = new HashMap<>();
664
		}
663
        for (int i = 0; i <= 5; i++) {
665
 
664
            LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
666
		LOGGER.info("partnerPurchaseInTT" + partnerPurchaseIn);
665
            monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
667
		LOGGER.info("partnerCreditedSaleTT" + partnerCreditedSale);
666
        }
668
		LOGGER.info("pendingIncomeTT" + pendingIncome);
667
        model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
669
 
668
        model.addAttribute("monthValueMap", monthValueMap);
670
		long totalIncome = partnerCreditedSale + partnerPurchaseIn + pendingIncome + partnerFrontIncome
669
        model.addAttribute("investments", investment);
671
				+ additionalIncome;
670
        model.addAttribute("monthDays", LocalDate.now().minusMonths(month).lengthOfMonth());
672
 
671
        model.addAttribute("dayOfMonth", LocalDate.now().minusMonths(month).lengthOfMonth());
673
		long creditedIncome = partnerCreditedSale + partnerPurchaseIn + partnerFrontIncome + additionalIncome;
672
        model.addAttribute("month", month);
674
 
673
        return "performance";
675
		long pendingTotalIncome = pendingIncome;
674
    }
676
		LOGGER.info("totalIncome" + totalIncome);
675
 
677
		LOGGER.info("creditedIncome" + creditedIncome);
676
    @RequestMapping(value = "/investmentDetails", method = RequestMethod.GET)
678
		LOGGER.info("pendingTotalIncome" + pendingTotalIncome);
677
    public String getInvestmentDetails(HttpServletRequest request, Model model) throws Exception {
679
 
678
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
680
		model.addAttribute("totalIncome", totalIncome);
679
        int fofoId = loginDetails.getFofoId();
681
		model.addAttribute("creditedIncome", creditedIncome);
680
        ChartInvestmentModel cm = fofoUser.getInvestmentChart(fofoId);
682
		model.addAttribute("pendingTotalIncome", pendingTotalIncome);
681
        model.addAttribute("chartPieMap", gson.toJson(cm));
683
 
682
 
684
		Map<Integer, String> monthValueMap = new HashMap<>();
683
        LOGGER.info("InvestmentChart" + gson.toJson(cm));
685
		for (int i = 0; i <= 5; i++) {
684
        LOGGER.info("InvestmentChart" + cm);
686
			LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
685
        return "investmentdetails";
687
			monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
686
    }
688
		}
687
 
689
 
688
    @RequestMapping(value = "/getlmsLineChart", method = RequestMethod.GET)
690
		model.addAttribute("month", yearMonth);
689
    public String getlmsLineChart(HttpServletRequest request, Model model) throws Exception {
691
		model.addAttribute("monthValueMap", monthValueMap);
690
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
692
 
691
        int fofoId = loginDetails.getFofoId();
693
		return "partner-total-income";
692
        ChartModel cm = fofoUser.getLmsLineChart(loginDetails.getFofoId());
694
	}
693
 
695
 
694
        LOGGER.info("linechartMap" + gson.toJson(cm));
696
	@RequestMapping(value = "/getMonthsInvestment", method = RequestMethod.GET)
695
        model.addAttribute("linechartMap", gson.toJson(cm));
697
	public String getMonthsInvestment(HttpServletRequest request,
696
        return "lmsLineChart";
698
			@RequestParam(name = "month", required = true, defaultValue = "0") int month, Model model)
697
    }
699
			throws Exception {
698
 
700
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
699
    @RequestMapping(value = "/getMonthlyPurchaseLineChart", method = RequestMethod.GET)
701
		int fofoId = loginDetails.getFofoId();
700
    public String getMonthlyPurchaseLineChart(HttpServletRequest request, Model model) throws Exception {
702
		Map<String, Object> investment = fofoUser.getInvestmentsMonths(fofoId, month);
701
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
703
 
702
        int fofoId = loginDetails.getFofoId();
704
		LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
703
        ChartModel cm = fofoUser.getPurchaseOrderChart(fofoId);
705
		LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
704
 
706
		LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
705
        LOGGER.info("chartMap" + gson.toJson(cm));
707
		double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), currentMonthStart,
706
        model.addAttribute("chartMap", gson.toJson(cm));
708
				currentMonthEnd) / 2;
707
 
709
		double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), lastMonthStart,
708
        return "purchase_chart";
710
				currentMonthStart) / 2;
709
    }
711
		double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), LocalDateTime.MIN,
710
 
712
				currentMonthEnd) / 2;
711
    @RequestMapping(value = "/getBarChart", method = RequestMethod.GET)
713
		model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
712
    public String getBarChart(HttpServletRequest request, Model model) throws Exception {
714
		model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
713
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
715
		model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
714
        int fofoId = loginDetails.getFofoId();
716
 
715
        ChartModel cm = fofoUser.getBrandChart(fofoId);
717
		long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true,
716
 
718
				currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
717
        LOGGER.info("chartMap" + gson.toJson(cm));
719
 
718
        model.addAttribute("chartMap", gson.toJson(cm));
720
		long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false,
719
 
721
				currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
720
        return "bar_chart";
722
		if (hygieneCount == 0 && invalidHygieneCount == 0) {
721
    }
723
			invalidHygieneCount = 1;
722
 
724
		}
723
    @RequestMapping(value = "/getPriceDropDetails", method = RequestMethod.GET)
725
		Map<Integer, String> monthValueMap = new HashMap<>();
724
    public String getPriceDropDetails(HttpServletRequest request, @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId, @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, @RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model) throws Exception {
726
		for (int i = 0; i <= 5; i++) {
725
 
727
			LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
726
        LOGGER.info("params" + fofoId + brand + yearMonth);
728
			monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
727
 
729
		}
728
        List<PriceDropWithDetailsByYearMonthModel> priceDropdetailsList = priceDropRepository.selectBrandPendingPriceDropWithDetailsByYearMonth(fofoId, brand, yearMonth);
730
		model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
729
 
731
		model.addAttribute("monthValueMap", monthValueMap);
730
        LOGGER.info("priceDropdetailsList" + priceDropdetailsList);
732
		model.addAttribute("investments", investment);
731
 
733
		model.addAttribute("monthDays", LocalDate.now().minusMonths(month).lengthOfMonth());
732
        model.addAttribute("priceDropdetailsList", priceDropdetailsList);
734
		model.addAttribute("dayOfMonth", LocalDate.now().minusMonths(month).lengthOfMonth());
733
 
735
		model.addAttribute("month", month);
734
        return "price-drop-details";
736
		return "performance";
735
    }
737
	}
736
 
738
 
737
    @RequestMapping(value = "/getPriceDropDetailSixMonths", method = RequestMethod.GET)
739
	@RequestMapping(value = "/investmentDetails", method = RequestMethod.GET)
738
    public String getPriceDropDetailSixMonths(HttpServletRequest request, @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId, @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model) throws Exception {
740
	public String getInvestmentDetails(HttpServletRequest request, Model model) throws Exception {
739
 
741
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
740
        LOGGER.info("params" + fofoId + brand);
742
		int fofoId = loginDetails.getFofoId();
741
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
743
		ChartInvestmentModel cm = fofoUser.getInvestmentChart(fofoId);
742
        LocalDateTime startfMonthSixMonth = curDate.withDayOfMonth(1).minusMonths(12);
744
		model.addAttribute("chartPieMap", gson.toJson(cm));
743
        LocalDateTime endMonthTotal = curDate.withDayOfMonth(1).minusMonths(6);
745
 
744
 
746
		LOGGER.info("InvestmentChart" + gson.toJson(cm));
745
        List<PriceDropWithDetailsByYearMonthModel> priceDropdetailsList = priceDropRepository.selectBrandPendingPriceDropWithDetailsAndSixMonth(fofoId, brand, startfMonthSixMonth, endMonthTotal);
747
		LOGGER.info("InvestmentChart" + cm);
746
 
748
		return "investmentdetails";
747
        LOGGER.info("priceDropdetailsList" + priceDropdetailsList);
749
	}
748
 
750
 
749
        model.addAttribute("priceDropdetailsList", priceDropdetailsList);
751
	@RequestMapping(value = "/getlmsLineChart", method = RequestMethod.GET)
750
 
752
	public String getlmsLineChart(HttpServletRequest request, Model model) throws Exception {
751
        return "price-drop-details";
753
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
752
    }
754
		int fofoId = loginDetails.getFofoId();
753
 
755
		ChartModel cm = fofoUser.getLmsLineChart(loginDetails.getFofoId());
754
    @RequestMapping(value = "/getMonthlyPriceDrop", method = RequestMethod.GET)
756
 
755
    public String getMonthlyPriceDropTabular(HttpServletRequest request, Model model) throws Exception {
757
		LOGGER.info("linechartMap" + gson.toJson(cm));
756
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
758
		model.addAttribute("linechartMap", gson.toJson(cm));
757
        int fofoId = loginDetails.getFofoId();
759
		return "lmsLineChart";
758
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
760
	}
759
 
761
 
760
        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
762
	@RequestMapping(value = "/getMonthlyPurchaseLineChart", method = RequestMethod.GET)
761
        LocalDateTime startfMonthTotal = curDate.withDayOfMonth(1).minusMonths(12);
763
	public String getMonthlyPurchaseLineChart(HttpServletRequest request, Model model) throws Exception {
762
        LocalDateTime endMonthTotal = curDate.withDayOfMonth(1).minusMonths(5);
764
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
763
 
765
		int fofoId = loginDetails.getFofoId();
764
        LOGGER.info("startfMonthTotal" + startfMonthTotal);
766
		ChartModel cm = fofoUser.getPurchaseOrderChart(fofoId);
765
 
767
 
766
        LOGGER.info("endMonthTotal" + endMonthTotal);
768
		LOGGER.info("chartMap" + gson.toJson(cm));
767
        List<YearMonth> yms = new ArrayList<YearMonth>();
769
		model.addAttribute("chartMap", gson.toJson(cm));
768
 
770
 
769
        for (int i = 0; i <= 5; i++) {
771
		return "purchase_chart";
770
            yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
772
	}
771
        }
773
 
772
        Collections.reverse(yms);
774
	@RequestMapping(value = "/getBarChart", method = RequestMethod.GET)
773
        model.addAttribute("yms", yms);
775
	public String getBarChart(HttpServletRequest request, Model model) throws Exception {
774
        LOGGER.info("ym" + yms);
776
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
775
 
777
		int fofoId = loginDetails.getFofoId();
776
        List<PriceDropYearMonthModel> priceDropYearMonthModels = priceDropRepository.selectBrandPendingPriceDropByYearMonth(fofoId, startOfMonth);
778
		ChartModel cm = fofoUser.getBrandChart(fofoId);
777
 
779
 
778
        List<PriceDropBrandModel> priceDropBrandSixMonthTotals = priceDropRepository.selectSixMonthBrandPriceDropByYearMonth(fofoId, startfMonthTotal, endMonthTotal);
780
		LOGGER.info("chartMap" + gson.toJson(cm));
779
 
781
		model.addAttribute("chartMap", gson.toJson(cm));
780
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
782
 
781
 
783
		return "bar_chart";
782
        Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
784
	}
783
 
785
 
784
        LOGGER.info("priceDropBrandSixMonthTotals" + priceDropBrandSixMonthTotals);
786
	@RequestMapping(value = "/getPriceDropDetails", method = RequestMethod.GET)
785
 
787
	public String getPriceDropDetails(HttpServletRequest request,
786
        Map<String, Double> priceDropBrandSixMonthMap = priceDropBrandSixMonthTotals.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
788
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
787
 
789
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand,
788
        model.addAttribute("priceDropBrandSixMonthMap", priceDropBrandSixMonthMap);
790
			@RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model)
789
        LOGGER.info("priceDropYearMonthModels" + priceDropYearMonthModels);
791
			throws Exception {
790
 
792
 
791
        for (PriceDropYearMonthModel pdm : priceDropYearMonthModels) {
793
		LOGGER.info("params" + fofoId + brand + yearMonth);
792
            Map<YearMonth, Double> brandValue = new HashMap<>();
794
 
793
 
795
		List<PriceDropWithDetailsByYearMonthModel> priceDropdetailsList = priceDropRepository
794
            if (brandMonthValue.containsKey(pdm.getBrand())) {
796
				.selectBrandPendingPriceDropWithDetailsByYearMonth(fofoId, brand, yearMonth);
795
                brandValue = brandMonthValue.get(pdm.getBrand());
797
 
796
                brandValue.put(YearMonth.parse(pdm.getYearMonth(), dateTimeFormatter), (double) pdm.getAmount());
798
		LOGGER.info("priceDropdetailsList" + priceDropdetailsList);
797
            } else {
799
 
798
 
800
		model.addAttribute("priceDropdetailsList", priceDropdetailsList);
799
                brandValue.put(YearMonth.parse(pdm.getYearMonth(), dateTimeFormatter), (double) pdm.getAmount());
801
 
800
 
802
		return "price-drop-details";
801
            }
803
	}
802
            brandMonthValue.put(pdm.getBrand(), brandValue);
804
 
803
        }
805
	@RequestMapping(value = "/getPriceDropDetailSixMonths", method = RequestMethod.GET)
804
        List<String> brands = new ArrayList<>();
806
	public String getPriceDropDetailSixMonths(HttpServletRequest request,
805
        brands.add("Accessories");
807
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
806
        brands.add("Oppo");
808
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model)
807
        brands.add("Vivo");
809
			throws Exception {
808
        brands.add("Samsung");
810
 
809
        brands.add("Realme");
811
		LOGGER.info("params" + fofoId + brand);
810
        brands.add("MI");
812
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
811
        brands.add("Tecno");
813
		LocalDateTime startfMonthSixMonth = curDate.withDayOfMonth(1).minusMonths(12);
812
        brands.add("Itel");
814
		LocalDateTime endMonthTotal = curDate.withDayOfMonth(1).minusMonths(6);
813
        brands.add("Nokia");
815
 
814
 
816
		List<PriceDropWithDetailsByYearMonthModel> priceDropdetailsList = priceDropRepository
815
        Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
817
				.selectBrandPendingPriceDropWithDetailsAndSixMonth(fofoId, brand, startfMonthSixMonth, endMonthTotal);
816
 
818
 
817
        model.addAttribute("brands", brands);
819
		LOGGER.info("priceDropdetailsList" + priceDropdetailsList);
818
 
820
 
819
        for (String brand : brands) {
821
		model.addAttribute("priceDropdetailsList", priceDropdetailsList);
820
            Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
822
 
821
            for (int i = 5; i >= 0; i--) {
823
		return "price-drop-details";
822
 
824
	}
823
                LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
825
 
824
 
826
	@RequestMapping(value = "/getMonthlyPriceDrop", method = RequestMethod.GET)
825
                if (yearMonthValue != null) {
827
	public String getMonthlyPriceDropTabular(HttpServletRequest request, Model model) throws Exception {
826
                    if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
828
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
827
                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
829
		int fofoId = loginDetails.getFofoId();
828
                    }
830
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
829
 
831
 
830
                } else {
832
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
831
                    yearMonthValue = new HashMap<>();
833
		LocalDateTime startfMonthTotal = curDate.withDayOfMonth(1).minusMonths(12);
832
                    yearMonthValue.put(YearMonth.from(startMonth), 0.0);
834
		LocalDateTime endMonthTotal = curDate.withDayOfMonth(1).minusMonths(5);
833
                }
835
 
834
            }
836
		LOGGER.info("startfMonthTotal" + startfMonthTotal);
835
 
837
 
836
            Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
838
		LOGGER.info("endMonthTotal" + endMonthTotal);
837
 
839
		List<YearMonth> yms = new ArrayList<YearMonth>();
838
            brandMonthValue.put(brand, sortedMonthBrandValue);
840
 
839
 
841
		for (int i = 0; i <= 5; i++) {
840
            sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
842
			yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
841
 
843
		}
842
        }
844
		Collections.reverse(yms);
843
 
845
		model.addAttribute("yms", yms);
844
        LOGGER.info("sortedBrandValue" + sortedBrandValue);
846
		LOGGER.info("ym" + yms);
845
        model.addAttribute("fofoId", fofoId);
847
 
846
 
848
		List<PriceDropYearMonthModel> priceDropYearMonthModels = priceDropRepository
847
        model.addAttribute("sortedBrandValue", sortedBrandValue);
849
				.selectBrandPendingPriceDropByYearMonth(fofoId, startOfMonth);
848
 
850
 
849
        return "price-drop-tabular";
851
		List<PriceDropBrandModel> priceDropBrandSixMonthTotals = priceDropRepository
850
    }
852
				.selectSixMonthBrandPriceDropByYearMonth(fofoId, startfMonthTotal, endMonthTotal);
851
 
853
 
852
    @RequestMapping(value = "/getMonthlyActivation", method = RequestMethod.GET)
854
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
853
    public String getMonthlyActivation(HttpServletRequest request, Model model) throws Exception {
855
 
854
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
856
		Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
855
        int fofoId = loginDetails.getFofoId();
857
 
856
 
858
		LOGGER.info("priceDropBrandSixMonthTotals" + priceDropBrandSixMonthTotals);
857
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
859
 
858
        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
860
		Map<String, Double> priceDropBrandSixMonthMap = priceDropBrandSixMonthTotals.stream()
859
 
861
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
860
        List<YearMonth> yms = new ArrayList<YearMonth>();
862
 
861
 
863
		model.addAttribute("priceDropBrandSixMonthMap", priceDropBrandSixMonthMap);
862
        for (int i = 0; i <= 5; i++) {
864
		LOGGER.info("priceDropYearMonthModels" + priceDropYearMonthModels);
863
            yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
865
 
864
        }
866
		for (PriceDropYearMonthModel pdm : priceDropYearMonthModels) {
865
        Collections.reverse(yms);
867
			Map<YearMonth, Double> brandValue = new HashMap<>();
866
        model.addAttribute("yms", yms);
868
 
867
        LOGGER.info("ym" + yms);
869
			if (brandMonthValue.containsKey(pdm.getBrand())) {
868
 
870
				brandValue = brandMonthValue.get(pdm.getBrand());
869
        List<ActivationYearMonthModel> pendingActivationModels = schemeInOutRepository.selectPendingActivationGroupByBrandYearMonth(fofoId, startOfMonth);
871
				brandValue.put(YearMonth.parse(pdm.getYearMonth(), dateTimeFormatter), (double) pdm.getAmount());
870
 
872
			} else {
871
        List<ActivationBrandModel> pendingActivationBeforeSixMonth = schemeInOutRepository.selectByYearMonthActivationGroupByBrand(fofoId, startOfMonth);
873
 
872
 
874
				brandValue.put(YearMonth.parse(pdm.getYearMonth(), dateTimeFormatter), (double) pdm.getAmount());
873
        Map<String, Double> pendingActivationBeforeSixMonthMap = pendingActivationBeforeSixMonth.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
875
 
874
 
876
			}
875
        model.addAttribute("pendingActivationBeforeSixMonthMap", pendingActivationBeforeSixMonthMap);
877
			brandMonthValue.put(pdm.getBrand(), brandValue);
876
 
878
		}
877
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
879
		List<String> brands = new ArrayList<>();
878
 
880
		brands.add("Accessories");
879
        Map<String, Map<YearMonth, Double>> activationBrandMonthMap = new HashMap<>();
881
		brands.add("Oppo");
880
 
882
		brands.add("Vivo");
881
        for (ActivationYearMonthModel pam : pendingActivationModels) {
883
		brands.add("Samsung");
882
            Map<YearMonth, Double> brandValue = new HashMap<>();
884
		brands.add("Realme");
883
 
885
		brands.add("MI");
884
            if (activationBrandMonthMap.containsKey(pam.getBrand())) {
886
		brands.add("Tecno");
885
                brandValue = activationBrandMonthMap.get(pam.getBrand());
887
		brands.add("Itel");
886
                brandValue.put(YearMonth.parse(pam.getYearMonth(), dateTimeFormatter), (double) pam.getAmount());
888
		brands.add("Nokia");
887
            } else {
889
 
888
 
890
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
889
                brandValue.put(YearMonth.parse(pam.getYearMonth(), dateTimeFormatter), (double) pam.getAmount());
891
 
890
 
892
		model.addAttribute("brands", brands);
891
            }
893
 
892
            activationBrandMonthMap.put(pam.getBrand(), brandValue);
894
		for (String brand : brands) {
893
        }
895
			Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
894
 
896
			for (int i = 5; i >= 0; i--) {
895
        List<String> brands = new ArrayList<>();
897
 
896
        brands.add("Oppo");
898
				LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
897
        brands.add("Vivo");
899
 
898
        brands.add("Samsung");
900
				if (yearMonthValue != null) {
899
        brands.add("Realme");
901
					if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
900
        brands.add("MI");
902
						yearMonthValue.put(YearMonth.from(startMonth), 0.0);
901
        brands.add("Tecno");
903
					}
902
        brands.add("Itel");
904
 
903
        brands.add("Nokia");
905
				} else {
904
        brands.add("Lava");
906
					yearMonthValue = new HashMap<>();
905
        Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
907
					yearMonthValue.put(YearMonth.from(startMonth), 0.0);
906
 
908
				}
907
        model.addAttribute("brands", brands);
909
			}
908
 
910
 
909
        for (String brand : brands) {
911
			Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
910
            Map<YearMonth, Double> yearMonthValue = activationBrandMonthMap.get(brand);
912
 
911
            for (int i = 5; i >= 0; i--) {
913
			brandMonthValue.put(brand, sortedMonthBrandValue);
912
                LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
914
 
913
                if (yearMonthValue != null) {
915
			sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
914
                    if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
916
 
915
                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
917
		}
916
                    }
918
 
917
 
919
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
918
                } else {
920
		model.addAttribute("fofoId", fofoId);
919
                    yearMonthValue = new HashMap<>();
921
 
920
                    yearMonthValue.put(YearMonth.from(startMonth), 0.0);
922
		model.addAttribute("sortedBrandValue", sortedBrandValue);
921
                }
923
 
922
            }
924
		return "price-drop-tabular";
923
            Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
925
	}
924
            activationBrandMonthMap.put(brand, sortedMonthBrandValue);
926
 
925
            sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
927
	@RequestMapping(value = "/getMonthlyActivation", method = RequestMethod.GET)
926
        }
928
	public String getMonthlyActivation(HttpServletRequest request, Model model) throws Exception {
927
 
929
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
928
        LOGGER.info("sortedBrandValue" + sortedBrandValue);
930
		int fofoId = loginDetails.getFofoId();
929
        model.addAttribute("sortedBrandValue", sortedBrandValue);
931
 
930
        model.addAttribute("fofoId", fofoId);
932
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
931
        return "activation-tabular";
933
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
932
    }
934
 
933
 
935
		List<YearMonth> yms = new ArrayList<YearMonth>();
934
    @RequestMapping(value = "/getMonthlyActivationItemDetail", method = RequestMethod.GET)
936
 
935
    public String getMonthlyActivationItemDetail(HttpServletRequest request, @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId, @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, @RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model) throws Exception {
937
		for (int i = 0; i <= 5; i++) {
936
 
938
			yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
937
        LOGGER.info("params" + fofoId + brand + yearMonth);
939
		}
938
 
940
		Collections.reverse(yms);
939
        List<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository.selectBrandPendingActivationItemDetails(fofoId, brand, yearMonth);
941
		model.addAttribute("yms", yms);
940
 
942
		LOGGER.info("ym" + yms);
941
        for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {
943
 
942
 
944
		List<ActivationYearMonthModel> pendingActivationModels = schemeInOutRepository
943
            List<FofoLineItem> flis = fofoLineItemRepository.selectByInventoryItemId(activationItemDetail.getInventoryItemId());
945
				.selectPendingActivationGroupByBrandYearMonth(fofoId, startOfMonth);
944
 
946
 
945
            LOGGER.info("flis" + flis);
947
		List<ActivationBrandModel> pendingActivationBeforeSixMonth = schemeInOutRepository
946
 
948
				.selectByYearMonthActivationGroupByBrand(fofoId, startOfMonth);
947
            int maxFofoOrderItemId = flis.stream().mapToInt(x -> x.getFofoOrderItemId()).max().orElseThrow(NoSuchElementException::new);
949
 
948
            LOGGER.info("maxFofoOrderItemId" + maxFofoOrderItemId);
950
		Map<String, Double> pendingActivationBeforeSixMonthMap = pendingActivationBeforeSixMonth.stream()
949
 
951
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
950
            FofoOrderItem foi = fofoOrderItemRepository.selectById(maxFofoOrderItemId);
952
 
951
 
953
		model.addAttribute("pendingActivationBeforeSixMonthMap", pendingActivationBeforeSixMonthMap);
952
            FofoOrder fo = fofoOrderRepository.selectByOrderId(foi.getOrderId());
954
 
953
 
955
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
954
            activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());
956
 
955
 
957
		Map<String, Map<YearMonth, Double>> activationBrandMonthMap = new HashMap<>();
956
        }
958
 
957
        LOGGER.info("activationItemDetails" + activationItemDetails);
959
		for (ActivationYearMonthModel pam : pendingActivationModels) {
958
 
960
			Map<YearMonth, Double> brandValue = new HashMap<>();
959
        model.addAttribute("activationItemDetails", activationItemDetails);
961
 
960
 
962
			if (activationBrandMonthMap.containsKey(pam.getBrand())) {
961
        return "activation-pending-item-details";
963
				brandValue = activationBrandMonthMap.get(pam.getBrand());
962
    }
964
				brandValue.put(YearMonth.parse(pam.getYearMonth(), dateTimeFormatter), (double) pam.getAmount());
963
 
965
			} else {
964
    @RequestMapping(value = "/getMonthlyActivationBeforeSixMonthsItemDetail", method = RequestMethod.GET)
966
 
965
    public String getMonthlyActivationItemDetail(HttpServletRequest request, @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId, @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model) throws Exception {
967
				brandValue.put(YearMonth.parse(pam.getYearMonth(), dateTimeFormatter), (double) pam.getAmount());
966
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
968
 
967
 
969
			}
968
        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
970
			activationBrandMonthMap.put(pam.getBrand(), brandValue);
969
 
971
		}
970
        List<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository.selectBrandPendingActivationItemDetailByYearMonth(fofoId, brand, startOfMonth);
972
 
971
 
973
		List<String> brands = new ArrayList<>();
972
        for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {
974
		brands.add("Oppo");
973
 
975
		brands.add("Vivo");
974
            List<FofoLineItem> flis = fofoLineItemRepository.selectByInventoryItemId(activationItemDetail.getInventoryItemId());
976
		brands.add("Samsung");
975
            LOGGER.info("flis" + flis);
977
		brands.add("Realme");
976
 
978
		brands.add("MI");
977
            int maxFofoOrderItemId = flis.stream().mapToInt(x -> x.getFofoOrderItemId()).max().orElseThrow(NoSuchElementException::new);
979
		brands.add("Tecno");
978
            LOGGER.info("maxFofoOrderItemId" + maxFofoOrderItemId);
980
		brands.add("Itel");
979
 
981
		brands.add("Nokia");
980
            FofoOrderItem foi = fofoOrderItemRepository.selectById(maxFofoOrderItemId);
982
		brands.add("Lava");
981
 
983
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
982
            FofoOrder fo = fofoOrderRepository.selectByOrderId(foi.getOrderId());
984
 
983
 
985
		model.addAttribute("brands", brands);
984
            activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());
986
 
985
 
987
		for (String brand : brands) {
986
        }
988
			Map<YearMonth, Double> yearMonthValue = activationBrandMonthMap.get(brand);
987
        LOGGER.info("activationItemDetails" + activationItemDetails);
989
			for (int i = 5; i >= 0; i--) {
988
 
990
				LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
989
        model.addAttribute("activationItemDetails", activationItemDetails);
991
				if (yearMonthValue != null) {
990
 
992
					if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
991
        return "activation-pending-item-details";
993
						yearMonthValue.put(YearMonth.from(startMonth), 0.0);
992
    }
994
					}
993
 
995
 
994
    @RequestMapping(value = "/getMonthlySamsungUpgradeOffer", method = RequestMethod.GET)
996
				} else {
995
    public String getMonthlySamsungUpgradeOffer(HttpServletRequest request, Model model) throws Exception {
997
					yearMonthValue = new HashMap<>();
996
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
998
					yearMonthValue.put(YearMonth.from(startMonth), 0.0);
997
        int fofoId = loginDetails.getFofoId();
999
				}
998
 
1000
			}
999
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
1001
			Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
1000
        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1002
			activationBrandMonthMap.put(brand, sortedMonthBrandValue);
1001
 
1003
			sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
1002
        List<YearMonth> yms = new ArrayList<YearMonth>();
1004
		}
1003
 
1005
 
1004
        for (int i = 0; i <= 5; i++) {
1006
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
1005
            yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
1007
		model.addAttribute("sortedBrandValue", sortedBrandValue);
1006
        }
1008
		model.addAttribute("fofoId", fofoId);
1007
        Collections.reverse(yms);
1009
		return "activation-tabular";
1008
        model.addAttribute("yms", yms);
1010
	}
1009
        LOGGER.info("ym" + yms);
1011
 
1010
 
1012
	@RequestMapping(value = "/getMonthlyActivationItemDetail", method = RequestMethod.GET)
1011
        List<SamsungUpgradeOfferModel> suos = samsungUpgradeOfferRepository.selectUpgradeOfferGroupByYearMonth(fofoId, UpgradeOfferStatus.approved, startOfMonth);
1013
	public String getMonthlyActivationItemDetail(HttpServletRequest request,
1012
 
1014
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1013
        LOGGER.info("suos" + suos);
1015
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand,
1014
 
1016
			@RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model)
1015
        List<BrandAmountModel> beforeSixMonthOffers = samsungUpgradeOfferRepository.selectUpgradeOfferByYearMonthGroupByBrand(fofoId, UpgradeOfferStatus.approved, startOfMonth);
1017
			throws Exception {
1016
 
1018
 
1017
        Map<String, Double> pendingUpgradeOfferBeforeSixMonthMap = beforeSixMonthOffers.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
1019
		LOGGER.info("params" + fofoId + brand + yearMonth);
1018
 
1020
 
1019
        model.addAttribute("pendingUpgradeOfferBeforeSixMonthMap", pendingUpgradeOfferBeforeSixMonthMap);
1021
		List<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository
1020
 
1022
				.selectBrandPendingActivationItemDetails(fofoId, brand, yearMonth);
1021
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
1023
 
1022
 
1024
		for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {
1023
        Map<String, Map<YearMonth, Double>> upgradeOfferBrandMonthMap = new HashMap<>();
1025
 
1024
 
1026
			List<FofoLineItem> flis = fofoLineItemRepository
1025
        for (SamsungUpgradeOfferModel suo : suos) {
1027
					.selectByInventoryItemId(activationItemDetail.getInventoryItemId());
1026
            Map<YearMonth, Double> brandValue = new HashMap<>();
1028
 
1027
 
1029
			LOGGER.info("flis" + flis);
1028
            if (upgradeOfferBrandMonthMap.containsKey(suo.getBrand())) {
1030
 
1029
                brandValue = upgradeOfferBrandMonthMap.get(suo.getBrand());
1031
			int maxFofoOrderItemId = flis.stream().mapToInt(x -> x.getFofoOrderItemId()).max()
1030
                brandValue.put(YearMonth.parse(suo.getYearMonth(), dateTimeFormatter), (double) suo.getAmount());
1032
					.orElseThrow(NoSuchElementException::new);
1031
            } else {
1033
			LOGGER.info("maxFofoOrderItemId" + maxFofoOrderItemId);
1032
 
1034
 
1033
                brandValue.put(YearMonth.parse(suo.getYearMonth(), dateTimeFormatter), (double) suo.getAmount());
1035
			FofoOrderItem foi = fofoOrderItemRepository.selectById(maxFofoOrderItemId);
1034
 
1036
 
1035
            }
1037
			FofoOrder fo = fofoOrderRepository.selectByOrderId(foi.getOrderId());
1036
            upgradeOfferBrandMonthMap.put(suo.getBrand(), brandValue);
1038
 
1037
        }
1039
			activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());
1038
 
1040
 
1039
        Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
1041
		}
1040
        String brand = "Samsung";
1042
		LOGGER.info("activationItemDetails" + activationItemDetails);
1041
 
1043
 
1042
        Map<YearMonth, Double> yearMonthValue = upgradeOfferBrandMonthMap.get(brand);
1044
		model.addAttribute("activationItemDetails", activationItemDetails);
1043
        for (int i = 5; i >= 0; i--) {
1045
 
1044
            LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
1046
		return "activation-pending-item-details";
1045
            if (yearMonthValue != null) {
1047
	}
1046
                if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
1048
 
1047
                    yearMonthValue.put(YearMonth.from(startMonth), 0.0);
1049
	@RequestMapping(value = "/getMonthlyActivationBeforeSixMonthsItemDetail", method = RequestMethod.GET)
1048
                }
1050
	public String getMonthlyActivationItemDetail(HttpServletRequest request,
1049
 
1051
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1050
            } else {
1052
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model)
1051
                yearMonthValue = new HashMap<>();
1053
			throws Exception {
1052
                yearMonthValue.put(YearMonth.from(startMonth), 0.0);
1054
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1053
            }
1055
 
1054
        }
1056
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1055
        Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
1057
 
1056
        upgradeOfferBrandMonthMap.put(brand, sortedMonthBrandValue);
1058
		List<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository
1057
        sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
1059
				.selectBrandPendingActivationItemDetailByYearMonth(fofoId, brand, startOfMonth);
1058
        LOGGER.info("sortedBrandValue" + sortedBrandValue);
1060
 
1059
 
1061
		for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {
1060
        model.addAttribute("brand", brand);
1062
 
1061
        model.addAttribute("sortedBrandValue", sortedBrandValue);
1063
			List<FofoLineItem> flis = fofoLineItemRepository
1062
        model.addAttribute("fofoId", fofoId);
1064
					.selectByInventoryItemId(activationItemDetail.getInventoryItemId());
1063
        return "upgrade-offer-tabular";
1065
			LOGGER.info("flis" + flis);
1064
 
1066
 
1065
    }
1067
			int maxFofoOrderItemId = flis.stream().mapToInt(x -> x.getFofoOrderItemId()).max()
1066
 
1068
					.orElseThrow(NoSuchElementException::new);
1067
    @RequestMapping(value = "/getMonthlyUpgradeOfferItemDetail", method = RequestMethod.GET)
1069
			LOGGER.info("maxFofoOrderItemId" + maxFofoOrderItemId);
1068
    public String getMonthlyUpgradeOfferItemDetail(HttpServletRequest request, @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId, @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, @RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model) throws Exception {
1070
 
1069
 
1071
			FofoOrderItem foi = fofoOrderItemRepository.selectById(maxFofoOrderItemId);
1070
        LOGGER.info("params" + fofoId + brand + yearMonth);
1072
 
1071
        List<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository.selectUpgradeOfferItemDetails(fofoId, UpgradeOfferStatus.approved, brand, yearMonth);
1073
			FofoOrder fo = fofoOrderRepository.selectByOrderId(foi.getOrderId());
1072
 
1074
 
1073
        model.addAttribute("offerItems", offerItems);
1075
			activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());
1074
 
1076
 
1075
        return "upgrade-offer-item-detail";
1077
		}
1076
    }
1078
		LOGGER.info("activationItemDetails" + activationItemDetails);
1077
 
1079
 
1078
    @RequestMapping(value = "/getUpgradeOfferBeforeSixMonthItemDetail", method = RequestMethod.GET)
1080
		model.addAttribute("activationItemDetails", activationItemDetails);
1079
    public String getUpgradeOfferBeforeSixMonthItemDetail(HttpServletRequest request, @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId, @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model) throws Exception {
1081
 
1080
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
1082
		return "activation-pending-item-details";
1081
 
1083
	}
1082
        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1084
 
1083
 
1085
	@RequestMapping(value = "/getMonthlySamsungUpgradeOffer", method = RequestMethod.GET)
1084
        List<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository.selectUpgradeOfferItemDetailByYearMonth(fofoId, UpgradeOfferStatus.approved, brand, startOfMonth);
1086
	public String getMonthlySamsungUpgradeOffer(HttpServletRequest request, Model model) throws Exception {
1085
 
1087
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1086
        model.addAttribute("offerItems", offerItems);
1088
		int fofoId = loginDetails.getFofoId();
1087
 
1089
 
1088
        return "upgrade-offer-item-detail";
1090
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1089
    }
1091
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1090
 
1092
 
1091
    @RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
1093
		List<YearMonth> yms = new ArrayList<YearMonth>();
1092
    public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId) throws Exception {
1094
 
1093
 
1095
		for (int i = 0; i <= 5; i++) {
1094
        Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1096
			yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
1095
        Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
1097
		}
1096
 
1098
		Collections.reverse(yms);
1097
        Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1099
		model.addAttribute("yms", yms);
1098
        if (authId != 0) {
1100
		LOGGER.info("ym" + yms);
1099
            List<Integer> fofoIds = pp.get(authId);
1101
 
1100
            fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1102
		List<SamsungUpgradeOfferModel> suos = samsungUpgradeOfferRepository.selectUpgradeOfferGroupByYearMonth(fofoId,
1101
        } else {
1103
				UpgradeOfferStatus.approved, startOfMonth);
1102
        }
1104
 
1103
 
1105
		LOGGER.info("suos" + suos);
1104
        model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1106
 
1105
        model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1107
		List<BrandAmountModel> beforeSixMonthOffers = samsungUpgradeOfferRepository
1106
 
1108
				.selectUpgradeOfferByYearMonthGroupByBrand(fofoId, UpgradeOfferStatus.approved, startOfMonth);
1107
        return "auth_user_partner_detail";
1109
 
1108
    }
1110
		Map<String, Double> pendingUpgradeOfferBeforeSixMonthMap = beforeSixMonthOffers.stream()
1109
 
1111
				.collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
1110
    @RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1112
 
1111
    public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId) throws Exception {
1113
		model.addAttribute("pendingUpgradeOfferBeforeSixMonthMap", pendingUpgradeOfferBeforeSixMonthMap);
1112
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1114
 
1113
        String email = loginDetails.getEmailId();
1115
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
1114
 
1116
 
1115
        Set<Integer> authfofoIds = new HashSet<>();
1117
		Map<String, Map<YearMonth, Double>> upgradeOfferBrandMonthMap = new HashMap<>();
1116
        authfofoIds = csService1.getAuthFofoIds(email, true);
1118
 
1117
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1119
		for (SamsungUpgradeOfferModel suo : suos) {
1118
                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1120
			Map<YearMonth, Double> brandValue = new HashMap<>();
1119
 
1121
 
1120
        Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
1122
			if (upgradeOfferBrandMonthMap.containsKey(suo.getBrand())) {
1121
        Map<Integer, PartnerDetailModel> fofoIdAndallValues = adminUser.getPartnersStatDataFromFile();
1123
				brandValue = upgradeOfferBrandMonthMap.get(suo.getBrand());
1122
        if (warehouseId != 0) {
1124
				brandValue.put(YearMonth.parse(suo.getYearMonth(), dateTimeFormatter), (double) suo.getAmount());
1123
            List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1125
			} else {
1124
            /*
1126
 
1125
             * List<Integer> fofoIds =
1127
				brandValue.put(YearMonth.parse(suo.getYearMonth(), dateTimeFormatter), (double) suo.getAmount());
1126
             * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1128
 
1127
             * .map(x -> x.getId()).collect(Collectors.toList());
1129
			}
1128
             */
1130
			upgradeOfferBrandMonthMap.put(suo.getBrand(), brandValue);
1129
            fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1131
		}
1130
        } else {
1132
 
1131
 
1133
		Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
1132
            List<Integer> fofoIds = new ArrayList<>(authfofoIds);
1134
		String brand = "Samsung";
1133
            fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1135
 
1134
        }
1136
		Map<YearMonth, Double> yearMonthValue = upgradeOfferBrandMonthMap.get(brand);
1135
        ChartInvestmentModel cm = adminUser.getAllStatePartnerType(fofoIdAndallValues);
1137
		for (int i = 5; i >= 0; i--) {
1136
        model.addAttribute("chartPieMap", gson.toJson(cm));
1138
			LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
1137
 
1139
			if (yearMonthValue != null) {
1138
        LOGGER.info("adminUserChart" + gson.toJson(cm));
1140
				if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
1139
 
1141
					yearMonthValue.put(YearMonth.from(startMonth), 0.0);
1140
        Map<Integer, MonthlyTarget> monthlyTargetMap = monthlyTargetRepository.selectByDate(YearMonth.now()).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1142
				}
1141
 
1143
 
1142
        model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1144
			} else {
1143
        model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1145
				yearMonthValue = new HashMap<>();
1144
        model.addAttribute("monthlyTargetMap", monthlyTargetMap);
1146
				yearMonthValue.put(YearMonth.from(startMonth), 0.0);
1145
 
1147
			}
1146
        List<PartnerType> partnerTypes = Arrays.asList(PartnerType.values()).stream().filter(x -> !x.equals(PartnerType.ALL)).collect(Collectors.toList());
1148
		}
1147
 
1149
		Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
1148
        model.addAttribute("partnerTypes", partnerTypes);
1150
		upgradeOfferBrandMonthMap.put(brand, sortedMonthBrandValue);
1149
 
1151
		sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
1150
        return "auth_user_partner_detail";
1152
		LOGGER.info("sortedBrandValue" + sortedBrandValue);
1151
    }
1153
 
1152
 
1154
		model.addAttribute("brand", brand);
1153
 
1155
		model.addAttribute("sortedBrandValue", sortedBrandValue);
1154
    @RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
1156
		model.addAttribute("fofoId", fofoId);
1155
    public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model, @RequestParam List<Integer> warehouseId) throws Exception {
1157
		return "upgrade-offer-tabular";
1156
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1158
 
1157
        String email = loginDetails.getEmailId();
1159
	}
1158
        Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
1160
 
1159
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1161
	@RequestMapping(value = "/getMonthlyUpgradeOfferItemDetail", method = RequestMethod.GET)
1160
                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1162
	public String getMonthlyUpgradeOfferItemDetail(HttpServletRequest request,
1161
        List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1163
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1162
        if (!warehouseId.contains(0)) {
1164
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand,
1163
            warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1165
			@RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model)
1164
        } else {
1166
			throws Exception {
1165
            LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1167
 
1166
            warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1168
		LOGGER.info("params" + fofoId + brand + yearMonth);
1167
 
1169
		List<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository
1168
        }
1170
				.selectUpgradeOfferItemDetails(fofoId, UpgradeOfferStatus.approved, brand, yearMonth);
1169
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1171
 
1170
        model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
1172
		model.addAttribute("offerItems", offerItems);
1171
        model.addAttribute("warehouseId", warehouseId);
1173
 
1172
        model.addAttribute("warehouseMap", warehouseMap);
1174
		return "upgrade-offer-item-detail";
1173
 
1175
	}
1174
        return "warehouse_brand_stock";
1176
 
1175
    }
1177
	@RequestMapping(value = "/getUpgradeOfferBeforeSixMonthItemDetail", method = RequestMethod.GET)
1176
 
1178
	public String getUpgradeOfferBeforeSixMonthItemDetail(HttpServletRequest request,
1177
    @RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1179
			@RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1178
    public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1180
			@RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model)
1179
        inventoryService.getItemAvailabilityAndIndent();
1181
			throws Exception {
1180
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1182
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1181
        return "response";
1183
 
1182
    }
1184
		LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1183
 
1185
 
1184
    @RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1186
		List<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository
1185
    public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model, @RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category) throws Exception {
1187
				.selectUpgradeOfferItemDetailByYearMonth(fofoId, UpgradeOfferStatus.approved, brand, startOfMonth);
1186
 
1188
 
1187
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1189
		model.addAttribute("offerItems", offerItems);
1188
        List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
1190
 
1189
        List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
1191
		return "upgrade-offer-item-detail";
1190
 
1192
	}
1191
        model.addAttribute("warehouseMap", warehouseMap);
1193
 
1192
        model.addAttribute("brands", listbrands);
1194
	@RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
1193
        model.addAttribute("listCategory", listCategory);
1195
	public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId)
1194
 
1196
			throws Exception {
1195
        model.addAttribute("selectedBrand", brands);
1197
 
1196
        model.addAttribute("selectedWarehouse", warehouseId);
1198
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1197
        model.addAttribute("selectedCategory", category);
1199
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
1198
 
1200
 
1199
        return "warehouse_brand_item_stock";
1201
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1200
    }
1202
		if (authId != 0) {
1201
 
1203
			List<Integer> fofoIds = pp.get(authId);
1202
    @RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1204
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1203
    public String getWarehouseWiseItemStock(HttpServletRequest request, Model model, @RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category) throws Exception {
1205
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1204
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1206
		} else {
1205
        if (warehouseId.contains(0)) {
1207
		}
1206
            warehouseId.addAll(warehouseMap.keySet());
1208
 
1207
        }
1209
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1208
        List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository.selectWarehouseItemStock(warehouseId, brands, category);
1210
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1209
 
1211
 
1210
        model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1212
		return "auth_user_partner_detail";
1211
        model.addAttribute("warehouseMap", warehouseMap);
1213
	}
1212
        return "warehouse_item_details";
1214
 
1213
    }
1215
	@RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
1214
 
1216
	public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId)
1215
    @RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
1217
			throws Exception {
1216
    public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand) throws Exception {
1218
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1217
 
1219
		String email = loginDetails.getEmailId();
1218
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1220
 
1219
        String email = loginDetails.getEmailId();
1221
		Set<Integer> authfofoIds = new HashSet<>();
1220
 
1222
		authfofoIds = csService1.getAuthFofoIds(email, true);
1221
        Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
1223
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1222
 
1224
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1223
        Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1225
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1224
 
1226
 
1225
        List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
1227
		Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
1226
 
1228
		Map<Integer, PartnerDetailModel> fofoIdAndallValues = adminUser.getPartnersStatDataFromFile();
1227
        for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
1229
		if (warehouseId != 0) {
1228
            WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
1230
			List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
1229
            if (bpt != null) {
1231
			/*
1230
                bpt.setAmtd(un.getUnbilledMtd());
1232
			 * List<Integer> fofoIds =
1231
                bpt.setUamtdQty(un.getUnbilledQty());
1233
			 * fofoStoreRepository.selectActivePartnerByWarehouse(warehouseId).stream()
1232
            } else {
1234
			 * .map(x -> x.getId()).collect(Collectors.toList());
1233
                bpt = new WarehouseWiseBrandSaleModel();
1235
			 */
1234
                bpt.setWarehouseId(un.getWarehouseId());
1236
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1235
                bpt.setAmtd(un.getUnbilledMtd());
1237
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1236
                bpt.setUamtdQty(un.getUnbilledQty());
1238
		} else {
1237
                bpt.setLms(0);
1239
 
1238
                bpt.setLmtd(0);
1240
			List<Integer> fofoIds = new ArrayList<>(authfofoIds);
1239
                bpt.setMtd(0);
1241
			fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey()))
1240
                bpt.setMtdQty(0);
1242
					.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1241
                bpt.setLmtd(0);
1243
		}
1242
                bpt.setLmtdQty(0);
1244
		ChartInvestmentModel cm = adminUser.getAllStatePartnerType(fofoIdAndallValues);
1243
                warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
1245
		model.addAttribute("chartPieMap", gson.toJson(cm));
1244
            }
1246
 
1245
        }
1247
		LOGGER.info("adminUserChart" + gson.toJson(cm));
1246
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1248
 
1247
 
1249
		Map<Integer, MonthlyTarget> monthlyTargetMap = monthlyTargetRepository.selectByDate(YearMonth.now()).stream()
1248
        Set<String> brands = inventoryService.getAllTagListingBrands();
1250
				.collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1249
        model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1251
 
1250
        model.addAttribute("warehouseMap", warehouseMap);
1252
		model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1251
        model.addAttribute("brands", brands);
1253
		model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1252
        model.addAttribute("selectedbrand", brand);
1254
		model.addAttribute("monthlyTargetMap", monthlyTargetMap);
1253
        return "warehousewise_brand_partners_sale";
1255
 
1254
    }
1256
		List<PartnerType> partnerTypes = Arrays.asList(PartnerType.values()).stream()
1255
 
1257
				.filter(x -> !x.equals(PartnerType.ALL)).collect(Collectors.toList());
1256
    @RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
1258
 
1257
    public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand) throws Exception {
1259
		model.addAttribute("partnerTypes", partnerTypes);
1258
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1260
 
1259
        String email = loginDetails.getEmailId();
1261
		return "auth_user_partner_detail";
1260
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1262
	}
1261
        Set<Integer> authfofoIds = storeGuyMap.get(email);
1263
 
1262
 
1264
 
1263
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1265
	@RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
1264
        if (authfofoIds == null) {
1266
	public String getWarehouseWiseBrandStock(HttpServletRequest request, Model model,
1265
            List<Position> positions1 = positionRepository.selectAll(authUser.getId());
1267
			@RequestParam List<Integer> warehouseId) throws Exception {
1266
            if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER).count() > 0) {
1268
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1267
                authfofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream().flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
1269
		String email = loginDetails.getEmailId();
1268
            }
1270
		Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
1269
        }
1271
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1270
        List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
1272
				.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1271
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1273
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1272
 
1274
		List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1273
        Set<String> brands = inventoryService.getAllTagListingBrands();
1275
		if (!warehouseId.contains(0)) {
1274
        model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1276
			warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1275
        model.addAttribute("warehouseMap", warehouseMap);
1277
		} else {
1276
        model.addAttribute("brands", brands);
1278
			LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1277
        model.addAttribute("selectedbrand", brand);
1279
			warehouseWiseBrandStock = saholicInventoryCISRepository
1278
        return "warehousewise_accessoriesbrand_sale";
1280
					.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
1279
    }
1281
 
1280
 
1282
		}
1281
    @RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
1283
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1282
    public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model, @RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1284
		model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
1283
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1285
		model.addAttribute("warehouseId", warehouseId);
1284
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1286
		model.addAttribute("warehouseMap", warehouseMap);
1285
        String email = loginDetails.getEmailId();
1287
 
1286
        Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
1288
		return "warehouse_brand_stock";
1287
        Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1289
	}
1288
 
1290
 
1289
        List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
1291
	@RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1290
 
1292
	public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1291
        for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
1293
		inventoryService.getItemAvailabilityAndIndent();
1292
            WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
1294
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1293
            if (bpt != null) {
1295
		return "response";
1294
                bpt.setAmtd(un.getAmtd());
1296
	}
1295
                bpt.setUamtdQty(un.getUnmtdQty());
1297
 
1296
            } else {
1298
	@RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
1297
                bpt = new WarehouseBrandWiseItemSaleModel();
1299
	public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model model,
1298
                bpt.setWarehouseId(un.getWarehouseId());
1300
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1299
                bpt.setItemId(un.getItemId());
1301
			throws Exception {
1300
                bpt.setAmtd(un.getAmtd());
1302
 
1301
                bpt.setUamtdQty(un.getUnmtdQty());
1303
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1302
                bpt.setBrand(un.getBrand());
1304
		List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
1303
                bpt.setModelName(un.getModelName());
1305
		List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
1304
                bpt.setModelNumber(un.getModelNumber());
1306
 
1305
                bpt.setColor(un.getColor());
1307
		model.addAttribute("warehouseMap", warehouseMap);
1306
                bpt.setLms(0);
1308
		model.addAttribute("brands", listbrands);
1307
                bpt.setLmtd(0);
1309
		model.addAttribute("listCategory", listCategory);
1308
                bpt.setMtd(0);
1310
 
1309
                bpt.setMtdQty(0);
1311
		model.addAttribute("selectedBrand", brands);
1310
                bpt.setLmtd(0);
1312
		model.addAttribute("selectedWarehouse", warehouseId);
1311
                bpt.setLmtdQty(0);
1313
		model.addAttribute("selectedCategory", category);
1312
                branditemSalesMap.put(un.getItemId(), bpt);
1314
 
1313
            }
1315
		return "warehouse_brand_item_stock";
1314
        }
1316
	}
1315
        model.addAttribute("branditemSales", branditemSalesMap);
1317
 
1316
        model.addAttribute("warehouseMap", warehouseMap);
1318
	@RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
1317
        return "warehouse_partner_itemwise_sale";
1319
	public String getWarehouseWiseItemStock(HttpServletRequest request, Model model,
1318
    }
1320
			@RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String category)
1319
 
1321
			throws Exception {
1320
    @RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
1322
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1321
    public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model, @RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1323
		if (warehouseId.contains(0)) {
1322
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1324
			warehouseId.addAll(warehouseMap.keySet());
1323
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1325
		}
1324
        String email = loginDetails.getEmailId();
1326
		List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository
1325
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1327
				.selectWarehouseItemStock(warehouseId, brands, category);
1326
        Set<Integer> authfofoIds = storeGuyMap.get(email);
1328
 
1327
        List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
1329
		model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1328
        model.addAttribute("branditemSales", branditemSales);
1330
		model.addAttribute("warehouseMap", warehouseMap);
1329
        model.addAttribute("warehouseMap", warehouseMap);
1331
		return "warehouse_item_details";
1330
        return "warehouse_accessories_itemwsie_sale";
1332
	}
1331
    }
1333
 
1332
 
1334
	@RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
1333
    @RequestMapping(value = "/contactUs", method = RequestMethod.GET)
1335
	public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String brand)
1334
    public String contactUs(HttpServletRequest request, Model model) throws Throwable {
1336
			throws Exception {
1335
        model.addAttribute("appContextPath", request.getContextPath());
1337
 
1336
        return "contact-us";
1338
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1337
    }
1339
		String email = loginDetails.getEmailId();
1338
 
1340
 
1339
    @RequestMapping(value = "/notifications", method = RequestMethod.GET)
1341
		Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
1340
    public String getNotificationsWithType(HttpServletRequest request, @RequestParam(required = false) MessageType messageType, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
1342
 
1341
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1343
		Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
1342
        int userId = 0;
1344
				.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream()
1343
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1345
				.collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
1344
        if (isAdmin) {
1346
 
1345
            userId = loginDetails.getFofoId();
1347
		List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository
1346
        } else {
1348
				.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
1347
            userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1349
 
1348
        }
1350
		for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
1349
        List<Notification> notifications = null;
1351
			WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
1350
 
1352
			if (bpt != null) {
1351
        List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType, userId, offset, limit);
1353
				bpt.setAmtd(un.getUnbilledMtd());
1352
        LOGGER.info("messageType" + messageType);
1354
				bpt.setUamtdQty(un.getUnbilledQty());
1353
        notifications = fofoUser.getNotifications(notificationCampaigns, messageType);
1355
			} else {
1354
 
1356
				bpt = new WarehouseWiseBrandSaleModel();
1355
        model.addAttribute("notifications", notifications);
1357
				bpt.setWarehouseId(un.getWarehouseId());
1356
 
1358
				bpt.setAmtd(un.getUnbilledMtd());
1357
        LOGGER.info("notifications" + notifications);
1359
				bpt.setUamtdQty(un.getUnbilledQty());
1358
        return "notification-template";
1360
				bpt.setLms(0);
1359
    }
1361
				bpt.setLmtd(0);
1360
 
1362
				bpt.setMtd(0);
1361
    @RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1363
				bpt.setMtdQty(0);
1362
    public ResponseEntity<?> retailerDocumentById(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid) throws ProfitMandiBusinessException {
1364
				bpt.setLmtd(0);
1363
        Document document = documentRepository.selectById(documentId);
1365
				bpt.setLmtdQty(0);
1364
        NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1366
				warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
1365
        if (nc.getDocumentId() == null) {
1367
			}
1366
            throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1368
		}
1367
        }
1369
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1368
        if (nc.getDocumentId() != documentId) {
1370
 
1369
            throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1371
		Set<String> brands = inventoryService.getAllTagListingBrands();
1370
        }
1372
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1371
        return responseSender.ok(document);
1373
		model.addAttribute("warehouseMap", warehouseMap);
1372
    }
1374
		model.addAttribute("brands", brands);
1373
 
1375
		model.addAttribute("selectedbrand", brand);
1374
    @RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1376
		return "warehousewise_brand_partners_sale";
1375
    public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model) throws ProfitMandiBusinessException {
1377
	}
1376
 
1378
 
1377
        NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1379
	@RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
1378
 
1380
	public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model model,
1379
        if (nc.getDocumentId() == null) {
1381
			@RequestParam String brand) throws Exception {
1380
            throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1382
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1381
        }
1383
		String email = loginDetails.getEmailId();
1382
 
1384
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1383
        Document document = documentRepository.selectById(nc.getDocumentId());
1385
		Set<Integer> authfofoIds = storeGuyMap.get(email);
1384
 
1386
 
1385
        FileInputStream file = null;
1387
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1386
        try {
1388
		if (authfofoIds == null) {
1387
            file = new FileInputStream(document.getPath() + File.separator + document.getName());
1389
			List<Position> positions1 = positionRepository.selectAll(authUser.getId());
1388
        } catch (FileNotFoundException e) {
1390
			if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
1389
            LOGGER.error("Retailer Document file not found : ", e);
1391
					.count() > 0) {
1390
            throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1392
				authfofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream()
1391
        }
1393
						.flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
1392
        // ByteArrayOutputStream byteArrayOutputStream = new
1394
			}
1393
        // ByteArrayOutputStream();
1395
		}
1394
        // ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1396
		List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository
1395
 
1397
				.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
1396
        final HttpHeaders headers = new HttpHeaders();
1398
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1397
        String contentType = "";
1399
 
1398
        if (document.getContentType() == ContentType.JPEG) {
1400
		Set<String> brands = inventoryService.getAllTagListingBrands();
1399
            contentType = "image/jpeg";
1401
		model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1400
        } else if (document.getContentType() == ContentType.PNG) {
1402
		model.addAttribute("warehouseMap", warehouseMap);
1401
            contentType = "image/png";
1403
		model.addAttribute("brands", brands);
1402
        } else if (document.getContentType() == ContentType.PDF) {
1404
		model.addAttribute("selectedbrand", brand);
1403
            contentType = "application/pdf";
1405
		return "warehousewise_accessoriesbrand_sale";
1404
        }
1406
	}
1405
        headers.set("Content-Type", contentType);
1407
 
1406
        headers.set("Content-disposition", "inline; filename=" + document.getName());
1408
	@RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
1407
        headers.setContentLength(document.getSize());
1409
	public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model model,
1408
        final InputStreamResource inputStreamResource = new InputStreamResource(file);
1410
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1409
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1411
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1410
    }
1412
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1411
 
1413
		String email = loginDetails.getEmailId();
1412
    @RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
1414
		Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
1413
    public String getItemWiseTertiary(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws ProfitMandiBusinessException {
1415
		Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository
1414
        List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
1416
				.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream()
1415
 
1417
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1416
        LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
1418
 
1417
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1419
		List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository
1418
        model.addAttribute("customRetailer", customRetailer);
1420
				.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
1419
        model.addAttribute("itemWiseTertiary", itemWiseTertiary);
1421
 
1420
        return "item-wise-tertiary";
1422
		for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
1421
    }
1423
			WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
1422
 
1424
			if (bpt != null) {
1423
    @RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
1425
				bpt.setAmtd(un.getAmtd());
1424
    public String getItemWiseIndent(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws ProfitMandiBusinessException {
1426
				bpt.setUamtdQty(un.getUnmtdQty());
1425
 
1427
			} else {
1426
        List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
1428
				bpt = new WarehouseBrandWiseItemSaleModel();
1427
        model.addAttribute("unbilledOrders", unbilledOrders);
1429
				bpt.setWarehouseId(un.getWarehouseId());
1428
 
1430
				bpt.setItemId(un.getItemId());
1429
        return "item-wise-indent";
1431
				bpt.setAmtd(un.getAmtd());
1430
    }
1432
				bpt.setUamtdQty(un.getUnmtdQty());
1431
 
1433
				bpt.setBrand(un.getBrand());
1432
    @RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
1434
				bpt.setModelName(un.getModelName());
1433
    public String getPartnerInvestment(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1435
				bpt.setModelNumber(un.getModelNumber());
1434
        Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
1436
				bpt.setColor(un.getColor());
1435
        PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
1437
				bpt.setLms(0);
1436
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1438
				bpt.setLmtd(0);
1437
        model.addAttribute("partnerDetailModel", partnerDetailModel);
1439
				bpt.setMtd(0);
1438
        model.addAttribute("customRetailer", customRetailer);
1440
				bpt.setMtdQty(0);
1439
        return "partner-investment";
1441
				bpt.setLmtd(0);
1440
    }
1442
				bpt.setLmtdQty(0);
1441
 
1443
				branditemSalesMap.put(un.getItemId(), bpt);
1442
    @RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
1444
			}
1443
    public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId, @RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
1445
		}
1444
        List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository.selectPartnerPendingIndentItem(itemId, warehouseId);
1446
		model.addAttribute("branditemSales", branditemSalesMap);
1445
 
1447
		model.addAttribute("warehouseMap", warehouseMap);
1446
        model.addAttribute("partnerPendingIndent", partnerPendingIndent);
1448
		return "warehouse_partner_itemwise_sale";
1447
        return "partner-pending-indent-item";
1449
	}
1448
    }
1450
 
1449
 
1451
	@RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
1450
    @RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
1452
	public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model model,
1451
    public String getPartnerActivateStockItem(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1453
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1452
        List<ActivateItemModel> activateStocks = new ArrayList<>();
1454
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1453
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
1455
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1454
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1456
		String email = loginDetails.getEmailId();
1455
 
1457
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1456
        for (InventoryItem inventoryItem : inventoryItems) {
1458
		Set<Integer> authfofoIds = storeGuyMap.get(email);
1457
            TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
1459
		List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository
1458
            Item item = itemRepository.selectById(inventoryItem.getItemId());
1460
				.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
1459
            ActivateItemModel aim = new ActivateItemModel();
1461
		model.addAttribute("branditemSales", branditemSales);
1460
            aim.setFofoId(inventoryItem.getFofoId());
1462
		model.addAttribute("warehouseMap", warehouseMap);
1461
            aim.setQuantity(inventoryItem.getGoodQuantity());
1463
		return "warehouse_accessories_itemwsie_sale";
1462
            aim.setAmount(tagListing.getSellingPrice());
1464
	}
1463
            aim.setItemDescription(item.getItemDescription());
1465
 
1464
            aim.setItemId(inventoryItem.getItemId());
1466
	@RequestMapping(value = "/contactUs", method = RequestMethod.GET)
1465
            activateStocks.add(aim);
1467
	public String contactUs(HttpServletRequest request, Model model) throws Throwable {
1466
        }
1468
		model.addAttribute("appContextPath", request.getContextPath());
1467
 
1469
		return "contact-us";
1468
        model.addAttribute("activateStocks", activateStocks);
1470
	}
1469
        model.addAttribute("customRetailer", customRetailer);
1471
 
1470
        return "partner-activate-stock";
1472
	@RequestMapping(value = "/notifications", method = RequestMethod.GET)
1471
    }
1473
	public String getNotificationsWithType(HttpServletRequest request,
1472
 
1474
			@RequestParam(required = false) MessageType messageType,
1473
    @RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
1475
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1474
    public String getPatnerBrandWiseMTDSale(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1476
			@RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
1475
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
1477
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1476
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1478
		int userId = 0;
1477
        Map<String, Double> brandMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
1479
		boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1478
        Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
1480
		if (isAdmin) {
1479
        Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
1481
			userId = loginDetails.getFofoId();
1480
        Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
1482
		} else {
1481
 
1483
			userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1482
        LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
1484
		}
1483
        model.addAttribute("brandMtdAmount", brandMtdAmount);
1485
		List<Notification> notifications = null;
1484
        model.addAttribute("brandMtdQty", brandMtdQty);
1486
 
1485
        model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
1487
		List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType,
1486
        model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
1488
				userId, offset, limit);
1487
 
1489
		LOGGER.info("messageType" + messageType);
1488
        model.addAttribute("customRetailer", customRetailer);
1490
		notifications = fofoUser.getNotifications(notificationCampaigns, messageType);
1489
        return "partner-brand-mtd-sale";
1491
 
1490
    }
1492
		model.addAttribute("notifications", notifications);
1491
 
1493
 
1492
    @RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
1494
		LOGGER.info("notifications" + notifications);
1493
    public String getPatnerBrandWiseLMTDSale(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1495
		return "notification-template";
1494
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
1496
	}
1495
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1497
 
1496
        Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1498
	@RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
1497
                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
1499
	public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1498
        Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
1500
			@RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid)
1499
                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
1501
			throws ProfitMandiBusinessException {
1500
 
1502
		Document document = documentRepository.selectById(documentId);
1501
        Double accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false)).get(fofoId);
1503
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1502
        Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false)).get(fofoId);
1504
		if (nc.getDocumentId() == null) {
1503
 
1505
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1504
        model.addAttribute("brandLMtdAmount", brandLMtdAmount);
1506
		}
1505
        model.addAttribute("brandLmtdQty", brandLmtdQty);
1507
		if (nc.getDocumentId() != documentId) {
1506
        model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
1508
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1507
        model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
1509
		}
1508
        model.addAttribute("customRetailer", customRetailer);
1510
		return responseSender.ok(document);
1509
        return "partner-brand-lmtd-sale";
1511
	}
1510
    }
1512
 
1511
 
1513
	@RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
1512
    @RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
1514
	public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model)
1513
    public String getPatnerBrandWiseLMSSale(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1515
			throws ProfitMandiBusinessException {
1514
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
1516
 
1515
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1517
		NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1516
        int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1518
 
1517
 
1519
		if (nc.getDocumentId() == null) {
1518
        Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1520
			throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1519
                curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
1521
		}
1520
        Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
1522
 
1521
                curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
1523
		Document document = documentRepository.selectById(nc.getDocumentId());
1522
 
1524
 
1523
        Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
1525
		FileInputStream file = null;
1524
        Long accesorieslmsqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
1526
		try {
1525
 
1527
			file = new FileInputStream(document.getPath() + File.separator + document.getName());
1526
        model.addAttribute("brandLMSAmount", brandLMSAmount);
1528
		} catch (FileNotFoundException e) {
1527
        model.addAttribute("brandLmsQty", brandLmsQty);
1529
			LOGGER.error("Retailer Document file not found : ", e);
1528
        model.addAttribute("accesorieslmssale", accesorieslmssale);
1530
			throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1529
        model.addAttribute("accesorieslmsqty", accesorieslmsqty);
1531
		}
1530
        model.addAttribute("customRetailer", customRetailer);
1532
		// ByteArrayOutputStream byteArrayOutputStream = new
1531
        return "partner-brand-lms-sale";
1533
		// ByteArrayOutputStream();
1532
    }
1534
		// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
1533
 
1535
 
1534
    @RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
1536
		final HttpHeaders headers = new HttpHeaders();
1535
    public String getPatnerInStock(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1537
		String contentType = "";
1536
 
1538
		if (document.getContentType() == ContentType.JPEG) {
1537
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1539
			contentType = "image/jpeg";
1538
 
1540
		} else if (document.getContentType() == ContentType.PNG) {
1539
        List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository.selectSumInStockMobileGroupByBrand(fofoId);
1541
			contentType = "image/png";
1540
        List<InStockBrandModel> accesStock = currentInventorySnapshotRepository.selectSumInStockAccessoriesGroupByBrand(fofoId);
1542
		} else if (document.getContentType() == ContentType.PDF) {
1541
 
1543
			contentType = "application/pdf";
1542
        List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository.selectInStockItemsByBrand(fofoId);
1544
		}
1543
 
1545
		headers.set("Content-Type", contentType);
1544
        Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1546
		headers.set("Content-disposition", "inline; filename=" + document.getName());
1545
 
1547
		headers.setContentLength(document.getSize());
1546
        model.addAttribute("stockItemMap", stockItemMap);
1548
		final InputStreamResource inputStreamResource = new InputStreamResource(file);
1547
        model.addAttribute("mobileStock", mobileStocks);
1549
		return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1548
        model.addAttribute("accesStock", accesStock);
1550
	}
1549
        model.addAttribute("customRetailer", customRetailer);
1551
 
1550
        return "partner-instock-item";
1552
	@RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
1551
    }
1553
	public String getItemWiseTertiary(HttpServletRequest request,
1552
 
1554
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1553
    @RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
1555
			throws ProfitMandiBusinessException {
1554
    public String getOpenTicketByFofoId(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1556
		List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
1555
        Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
1557
 
1556
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1558
		LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
1557
        List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId()).collect(Collectors.toList());
1559
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1558
        List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
1560
		model.addAttribute("customRetailer", customRetailer);
1559
 
1561
		model.addAttribute("itemWiseTertiary", itemWiseTertiary);
1560
        for (TicketAssigned ticketAssign : ticketAssigns) {
1562
		return "item-wise-tertiary";
1561
            AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
1563
	}
1562
            ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
1564
 
1563
        }
1565
	@RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
1564
        model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
1566
	public String getItemWiseIndent(HttpServletRequest request,
1565
        model.addAttribute("ticketAssigns", ticketAssigns);
1567
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model)
1566
        model.addAttribute("customRetailer", customRetailer);
1568
			throws ProfitMandiBusinessException {
1567
        return "open-ticket";
1569
 
1568
    }
1570
		List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
1569
 
1571
		model.addAttribute("unbilledOrders", unbilledOrders);
1570
    @RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
1572
 
1571
    public String getPartnerSecondarySale(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model) throws Exception {
1573
		return "item-wise-indent";
1572
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
1574
	}
1573
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1575
 
1574
        int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1576
	@RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
1575
        LocalDateTime startDate = null;
1577
	public String getPartnerInvestment(HttpServletRequest request,
1576
        LocalDateTime endDate = null;
1578
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1577
        List<InStockBrandModel> secondarySale = null;
1579
		Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
1578
        Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
1580
		PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
1579
 
1581
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1580
        if (timeValue.equals("mtd")) {
1582
		model.addAttribute("partnerDetailModel", partnerDetailModel);
1581
            startDate = curDate.withDayOfMonth(1);
1583
		model.addAttribute("customRetailer", customRetailer);
1582
            endDate = curDate.with(LocalTime.MAX);
1584
		return "partner-investment";
1583
            secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1585
	}
1584
            secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId).stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1586
 
1585
            LOGGER.info("secondarySalemtd" + secondarySale);
1587
	@RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
1586
        } else if (timeValue.equals("lmtd")) {
1588
	public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
1587
            startDate = curDate.withDayOfMonth(1).minusMonths(1);
1589
			@RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
1588
            endDate = curDate.with(LocalTime.MAX).minusMonths(1);
1590
		List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository
1589
            secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId).stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1591
				.selectPartnerPendingIndentItem(itemId, warehouseId);
1590
 
1592
 
1591
            secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1593
		model.addAttribute("partnerPendingIndent", partnerPendingIndent);
1592
            LOGGER.info("secondarySalelmtd" + secondarySale);
1594
		return "partner-pending-indent-item";
1593
 
1595
	}
1594
        } else {
1596
 
1595
            startDate = curDate.withDayOfMonth(1).minusMonths(1);
1597
	@RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
1596
            endDate = curDate.withDayOfMonth(1);
1598
	public String getPartnerActivateStockItem(HttpServletRequest request,
1597
            secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId).stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1599
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1598
 
1600
		List<ActivateItemModel> activateStocks = new ArrayList<>();
1599
            secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1601
		List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
1600
            LOGGER.info("secondarySalelms" + secondarySale);
1602
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1601
 
1603
 
1602
        }
1604
		for (InventoryItem inventoryItem : inventoryItems) {
1603
 
1605
			TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
1604
        LOGGER.info("secondarySale" + secondarySale);
1606
			Item item = itemRepository.selectById(inventoryItem.getItemId());
1605
        model.addAttribute("secondarySale", secondarySale);
1607
			ActivateItemModel aim = new ActivateItemModel();
1606
        model.addAttribute("secondaryItemSale", secondaryItemSale);
1608
			aim.setFofoId(inventoryItem.getFofoId());
1607
        model.addAttribute("customRetailer", customRetailer);
1609
			aim.setQuantity(inventoryItem.getGoodQuantity());
1608
 
1610
			aim.setAmount(tagListing.getSellingPrice());
1609
        return "partner-secondary-order";
1611
			aim.setItemDescription(item.getItemDescription());
1610
    }
1612
			aim.setItemId(inventoryItem.getItemId());
1611
 
1613
			activateStocks.add(aim);
1612
    @RequestMapping(value = "/getMobileBrandWise", method = RequestMethod.GET)
1614
		}
1613
    public String getMobileBrandWise(HttpServletRequest request, Model model) throws Exception {
1615
 
1614
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1616
		model.addAttribute("activateStocks", activateStocks);
1615
        String email = loginDetails.getEmailId();
1617
		model.addAttribute("customRetailer", customRetailer);
1616
 
1618
		return "partner-activate-stock";
1617
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1619
	}
1618
        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
1620
 
1619
 
1621
	@RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
1620
        Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
1622
	public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
1621
        partnersBrandSaleMap = fofoStoreRepository.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds)).stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1623
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1622
 
1624
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1623
        List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
1625
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1624
        for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
1626
		Map<String, Double> brandMtdAmount = fofoOrderItemRepository
1625
            BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
1627
				.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
1626
            if (bpt != null) {
1628
		Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1),
1627
                bpt.setAmtd(un.getUnbilledMtd());
1629
				curDate.with(LocalTime.MAX), fofoId);
1628
                bpt.setUamtdQty(un.getUnbilledMTDQty());
1630
		Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1629
            } else {
1631
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
1630
                bpt = new BrandWisePartnerSaleModel();
1632
		Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1631
                bpt.setBrand(un.getBrand());
1633
				curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
1632
                bpt.setAmtd(un.getUnbilledMtd());
1634
 
1633
                bpt.setUamtdQty(un.getUnbilledMTDQty());
1635
		LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
1634
                bpt.setLms(0);
1636
		model.addAttribute("brandMtdAmount", brandMtdAmount);
1635
                bpt.setLmtd(0);
1637
		model.addAttribute("brandMtdQty", brandMtdQty);
1636
                bpt.setMtd(0);
1638
		model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
1637
                bpt.setMtdQty(0);
1639
		model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
1638
                bpt.setLmtd(0);
1640
 
1639
                bpt.setLmtdQty(0);
1641
		model.addAttribute("customRetailer", customRetailer);
1640
                partnersBrandSaleMap.put(un.getBrand(), bpt);
1642
		return "partner-brand-mtd-sale";
1641
            }
1643
	}
1642
        }
1644
 
1643
 
1645
	@RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
1644
        model.addAttribute("brandSalesMap", partnersBrandSaleMap);
1646
	public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
1645
 
1647
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1646
        return "mobile-brand-wise-report";
1648
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1647
    }
1649
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1648
 
1650
		Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1649
    @RequestMapping(value = "/getAccessoriesBrandWise", method = RequestMethod.GET)
1651
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
1650
    public String getAccessoriesBrandWise(HttpServletRequest request, Model model) throws Exception {
1652
		Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
1651
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1653
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
1652
        String email = loginDetails.getEmailId();
1654
 
1653
 
1655
		Double accesorieslmtdsale = fofoOrderRepository
1654
        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
1656
				.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1),
1655
 
1657
						curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false))
1656
        List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
1658
				.get(fofoId);
1657
 
1659
		Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1658
        accessoriesBrandSales = fofoStoreRepository.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
1660
				curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1),
1659
 
1661
				Optional.of(false)).get(fofoId);
1660
        model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
1662
 
1661
        return "accessories-brand-wise-report";
1663
		model.addAttribute("brandLMtdAmount", brandLMtdAmount);
1662
    }
1664
		model.addAttribute("brandLmtdQty", brandLmtdQty);
1663
 
1665
		model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
1664
    @RequestMapping(value = "/getMobileLMSGraph", method = RequestMethod.GET)
1666
		model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
1665
    public String getMobileLMSGraph(HttpServletRequest request, @RequestParam(required = false) int warehouseId, @RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate, @RequestParam List<Integer> fofoIds, @RequestParam String filterType, Model model) throws Exception {
1667
		model.addAttribute("customRetailer", customRetailer);
1666
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream().collect(Collectors.groupingBy(
1668
		return "partner-brand-lmtd-sale";
1667
                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1669
	}
1668
 
1670
 
1669
        ChartModel cm;
1671
	@RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
1670
        if (warehouseId != 0) {
1672
	public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
1671
            cm = adminUser.getBrandWiseLms(Arrays.asList(warehouseId), fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(), endDate.toLocalDate(), filterType);
1673
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1672
        } else {
1674
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1673
            cm = adminUser.getBrandWiseLms(new ArrayList<>(warehouseIdFofoIdMap.keySet()), fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(), endDate.toLocalDate(), filterType);
1675
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1674
 
1676
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1675
        }
1677
 
1676
 
1678
		Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
1677
        LOGGER.info("chartMap" + gson.toJson(cm));
1679
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
1678
        model.addAttribute("chartMap", gson.toJson(cm));
1680
		Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
1679
        return "brand-wise-mobile-lms-chart";
1681
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
1680
    }
1682
 
1681
 
1683
		Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId,
1682
    @RequestMapping(value = "/getMobileLMSFilter", method = RequestMethod.GET)
1684
				curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
1683
    public String getMobileLMSFilter(HttpServletRequest request, @RequestParam(required = false, defaultValue = "0") int warehouseId, @RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate, Model model) throws Exception {
1685
		Long accesorieslmsqty = fofoOrderRepository
1684
 
1686
				.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId,
1685
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1687
						curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false))
1686
        String email = loginDetails.getEmailId();
1688
				.get(fofoId);
1687
 
1689
 
1688
        if (date == null) {
1690
		model.addAttribute("brandLMSAmount", brandLMSAmount);
1689
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
1691
		model.addAttribute("brandLmsQty", brandLmsQty);
1690
 
1692
		model.addAttribute("accesorieslmssale", accesorieslmssale);
1691
            LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1693
		model.addAttribute("accesorieslmsqty", accesorieslmsqty);
1692
            date = startOfMonth.toLocalDate().atStartOfDay();
1694
		model.addAttribute("customRetailer", customRetailer);
1693
        }
1695
		return "partner-brand-lms-sale";
1694
 
1696
	}
1695
        if (endDate == null) {
1697
 
1696
            LocalDateTime curDate = LocalDate.now().atTime(LocalTime.MAX);
1698
	@RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
1697
 
1699
	public String getPatnerInStock(HttpServletRequest request,
1698
            endDate = curDate;
1700
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1699
 
1701
 
1700
        }
1702
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1701
 
1703
 
1702
        Map<String, Object> map = adminUser.getFilter(warehouseId, email, date, endDate);
1704
		List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository
1703
        model.addAttribute("warehouseId", warehouseId);
1705
				.selectSumInStockMobileGroupByBrand(fofoId);
1704
        model.addAllAttributes(map);
1706
		List<InStockBrandModel> accesStock = currentInventorySnapshotRepository
1705
 
1707
				.selectSumInStockAccessoriesGroupByBrand(fofoId);
1706
        return "chart-filter-lms";
1708
 
1707
    }
1709
		List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository
1708
 
1710
				.selectInStockItemsByBrand(fofoId);
1709
    @RequestMapping(value = "/getMobileLMPGraph", method = RequestMethod.GET)
1711
 
1710
    public String getMobileLMPGraph(HttpServletRequest request, @RequestParam(required = false) int warehouseId, @RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate, @RequestParam List<Integer> fofoIds, @RequestParam String filterType, Model model) throws Exception {
1712
		Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream()
1711
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream().collect(Collectors.groupingBy(
1713
				.collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1712
                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1714
 
1713
 
1715
		model.addAttribute("stockItemMap", stockItemMap);
1714
        ChartModel cm;
1716
		model.addAttribute("mobileStock", mobileStocks);
1715
        if (warehouseId != 0) {
1717
		model.addAttribute("accesStock", accesStock);
1716
            cm = adminUser.getBrandWiseLmp(Arrays.asList(warehouseId), fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(), endDate.toLocalDate(), filterType);
1718
		model.addAttribute("customRetailer", customRetailer);
1717
        } else {
1719
		return "partner-instock-item";
1718
            cm = adminUser.getBrandWiseLmp(new ArrayList<>(warehouseIdFofoIdMap.keySet()), fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(), endDate.toLocalDate(), filterType);
1720
	}
1719
 
1721
 
1720
        }
1722
	@RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
1721
 
1723
	public String getOpenTicketByFofoId(HttpServletRequest request,
1722
        LOGGER.info("chartMap" + gson.toJson(cm));
1724
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
1723
        model.addAttribute("chartMap", gson.toJson(cm));
1725
		Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
1724
        return "brand-wise-mobile-lmp-chart";
1726
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1725
    }
1727
		List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId())
1726
 
1728
				.collect(Collectors.toList());
1727
    @RequestMapping(value = "/getSaleCountByMilestone", method = RequestMethod.GET)
1729
		List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
1728
    public String getSaleCountByMilestone(HttpServletRequest request, @RequestParam(required = false, defaultValue = "0") int warehouseId, Model model) throws Exception {
1730
 
1729
 
1731
		for (TicketAssigned ticketAssign : ticketAssigns) {
1730
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1732
			AuthUser authUser = authRepository.selectById(ticketAssign.getAssineeId());
1731
        String email = loginDetails.getEmailId();
1733
			ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
1732
        Set<Integer> authFofoIds = csService1.getAuthFofoIds(email, true);
1734
		}
1733
 
1735
		model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
1734
        Set<Integer> fofoIdlist = fofoStoreRepository.selectActiveStores().stream().filter(x -> !x.isInternal()).map(x -> x.getId()).collect(Collectors.toSet());
1736
		model.addAttribute("ticketAssigns", ticketAssigns);
1735
 
1737
		model.addAttribute("customRetailer", customRetailer);
1736
        Set<Integer> fofoIds = authFofoIds.stream().filter(x -> fofoIdlist.contains(x)).collect(Collectors.toSet());
1738
		return "open-ticket";
1737
        Map<Integer, Double> last3MonthSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
1739
	}
1738
                LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now(), 0, false);
1740
 
1739
 
1741
	@RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
1740
        if (fofoIds != null && fofoIds.size() > 0) {
1742
	public String getPartnerSecondarySale(HttpServletRequest request,
1741
            if (warehouseId != 0) {
1743
			@RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model)
1742
                fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId).stream().map(x -> x).collect(Collectors.toSet());
1744
			throws Exception {
1743
            }
1745
		LocalDateTime curDate = LocalDate.now().atStartOfDay();
1744
            Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
1746
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1745
            if (partnerStats != null) {
1747
		int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
1746
                List<PartnerDetailModel> partnerDetails = fofoIds.stream().filter(x -> partnerStats.containsKey(x)).map(x -> partnerStats.get(x)).collect(Collectors.toList());
1748
		LocalDateTime startDate = null;
1747
                Map<Milestone, List<Integer>> avg3Monthlms = new HashMap<>();
1749
		LocalDateTime endDate = null;
1748
                if (!last3MonthSale.isEmpty()) {
1750
		List<InStockBrandModel> secondarySale = null;
1749
                    int days = 60 + LocalDateTime.now().getDayOfMonth();
1751
		Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
1750
                    for (Entry<Integer, Double> last3MonthEntry : last3MonthSale.entrySet()) {
1752
 
1751
                        if (fofoIds.contains(last3MonthEntry.getKey())) {
1753
		if (timeValue.equals("mtd")) {
1752
                            Double monthSale = last3MonthEntry.getValue();
1754
			startDate = curDate.withDayOfMonth(1);
1753
                            if (monthSale == null) {
1755
			endDate = curDate.with(LocalTime.MAX);
1754
                                monthSale = (double) 0;
1756
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1755
 
1757
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1756
                            }
1758
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1757
                            double avg3MonthSale = (monthSale / days) * 30;
1759
			LOGGER.info("secondarySalemtd" + secondarySale);
1758
                            Milestone milestone = Milestone.get((int) avg3MonthSale);
1760
		} else if (timeValue.equals("lmtd")) {
1759
 
1761
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
1760
                            List<Integer> values = null;
1762
			endDate = curDate.with(LocalTime.MAX).minusMonths(1);
1761
 
1763
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1762
                            if (avg3Monthlms.containsKey(milestone)) {
1764
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1763
 
1765
 
1764
                                values = avg3Monthlms.get(milestone);
1766
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1765
                                values.add(last3MonthEntry.getKey());
1767
			LOGGER.info("secondarySalelmtd" + secondarySale);
1766
                                avg3Monthlms.put(milestone, values);
1768
 
1767
 
1769
		} else {
1768
                            } else {
1770
			startDate = curDate.withDayOfMonth(1).minusMonths(1);
1769
                                values = new ArrayList<>();
1771
			endDate = curDate.withDayOfMonth(1);
1770
 
1772
			secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId)
1771
                                values.add(last3MonthEntry.getKey());
1773
					.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
1772
                                avg3Monthlms.put(milestone, values);
1774
 
1773
 
1775
			secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
1774
                            }
1776
			LOGGER.info("secondarySalelms" + secondarySale);
1775
                        }
1777
 
1776
 
1778
		}
1777
                    }
1779
 
1778
 
1780
		LOGGER.info("secondarySale" + secondarySale);
1779
                }
1781
		model.addAttribute("secondarySale", secondarySale);
1780
 
1782
		model.addAttribute("secondaryItemSale", secondaryItemSale);
1781
                if (partnerDetails != null) {
1783
		model.addAttribute("customRetailer", customRetailer);
1782
 
1784
 
1783
                    Map<Milestone, List<Integer>> mtdMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getMtd()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
1785
		return "partner-secondary-order";
1784
                    Map<Milestone, List<Integer>> lmtdMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getLmtd()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
1786
	}
1785
 
1787
 
1786
                    Map<Milestone, List<Integer>> lmsMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getLms()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
1788
	@RequestMapping(value = "/getMobileBrandWise", method = RequestMethod.GET)
1787
 
1789
	public String getMobileBrandWise(HttpServletRequest request, Model model) throws Exception {
1788
                    model.addAttribute("mtdMap", mtdMap);
1790
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1789
                    model.addAttribute("lmtdMap", lmtdMap);
1791
		String email = loginDetails.getEmailId();
1790
                    model.addAttribute("avg3Monthlms", avg3Monthlms);
1792
 
1791
                    model.addAttribute("lmsMap", lmsMap);
1793
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1792
                }
1794
		Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
1793
 
1795
 
1794
            }
1796
		Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
1795
        }
1797
		partnersBrandSaleMap = fofoStoreRepository.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds))
1796
 
1798
				.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1797
        model.addAttribute("warehouseMap", ProfitMandiConstants.WAREHOUSE_MAP);
1799
 
1798
        model.addAttribute("warehouseId", warehouseId);
1800
		List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository
1799
        model.addAttribute("milestones", Milestone.values());
1801
				.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
1800
 
1802
		for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
1801
        return "sale-milestone";
1803
			BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
1802
 
1804
			if (bpt != null) {
1803
    }
1805
				bpt.setAmtd(un.getUnbilledMtd());
1804
 
1806
				bpt.setUamtdQty(un.getUnbilledMTDQty());
1805
    @RequestMapping(value = "/getPurchaseCountByMileStone", method = RequestMethod.GET)
1807
			} else {
1806
    public String getPurchaseCountByMileStone(HttpServletRequest request, @RequestParam(required = false, defaultValue = "0") int warehouseId, Model model) throws Exception {
1808
				bpt = new BrandWisePartnerSaleModel();
1807
 
1809
				bpt.setBrand(un.getBrand());
1808
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1810
				bpt.setAmtd(un.getUnbilledMtd());
1809
        String email = loginDetails.getEmailId();
1811
				bpt.setUamtdQty(un.getUnbilledMTDQty());
1810
 
1812
				bpt.setLms(0);
1811
        Set<Integer> authFofoIds = csService1.getAuthFofoIds(email, true);
1813
				bpt.setLmtd(0);
1812
 
1814
				bpt.setMtd(0);
1813
        Set<Integer> fofoIdlist = fofoStoreRepository.selectActiveStores().stream().filter(x -> !x.isInternal()).map(x -> x.getId()).collect(Collectors.toSet());
1815
				bpt.setMtdQty(0);
1814
        Set<Integer> fofoIds = authFofoIds.stream().filter(x -> fofoIdlist.contains(x)).collect(Collectors.toSet());
1816
				bpt.setLmtd(0);
1815
 
1817
				bpt.setLmtdQty(0);
1816
        Map<Integer, Double> last3MonthS = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(
1818
				partnersBrandSaleMap.put(un.getBrand(), bpt);
1817
                LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now());
1819
			}
1818
 
1820
		}
1819
        if (fofoIds != null && fofoIds.size() > 0) {
1821
 
1820
            if (warehouseId != 0) {
1822
		model.addAttribute("brandSalesMap", partnersBrandSaleMap);
1821
                fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId).stream().map(x -> x).collect(Collectors.toSet());
1823
 
1822
            }
1824
		return "mobile-brand-wise-report";
1823
            Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
1825
	}
1824
            if (partnerStats != null) {
1826
 
1825
                List<PartnerDetailModel> partnerDetails = fofoIds.stream().filter(x -> partnerStats.containsKey(x)).map(x -> partnerStats.get(x)).collect(Collectors.toList());
1827
	@RequestMapping(value = "/getAccessoriesBrandWise", method = RequestMethod.GET)
1826
                Map<Milestone, List<Integer>> avg3MonthS = new HashMap<>();
1828
	public String getAccessoriesBrandWise(HttpServletRequest request, Model model) throws Exception {
1827
                if (!last3MonthS.isEmpty()) {
1829
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1828
                    int days = 60 + LocalDateTime.now().getDayOfMonth();
1830
		String email = loginDetails.getEmailId();
1829
                    for (Entry<Integer, Double> last3MonthSEntry : last3MonthS.entrySet()) {
1831
 
1830
                        if (fofoIds.contains(last3MonthSEntry.getKey())) {
1832
		Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
1831
                            Double monthSec = last3MonthSEntry.getValue();
1833
 
1832
                            if (monthSec == null) {
1834
		List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
1833
                                monthSec = (double) 0;
1835
 
1834
 
1836
		accessoriesBrandSales = fofoStoreRepository
1835
                            }
1837
				.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
1836
                            double avg3MonthSale = (monthSec / days) * 30;
1838
 
1837
                            Milestone milestone = Milestone.get((int) avg3MonthSale);
1839
		model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
1838
 
1840
		return "accessories-brand-wise-report";
1839
                            List<Integer> values = null;
1841
	}
1840
                            if (avg3MonthS.containsKey(milestone)) {
1842
 
1841
                                values = avg3MonthS.get(milestone);
1843
	@RequestMapping(value = "/getMobileLMSGraph", method = RequestMethod.GET)
1842
                                values.add(last3MonthSEntry.getKey());
1844
	public String getMobileLMSGraph(HttpServletRequest request, @RequestParam(required = false) int warehouseId,
1843
 
1845
			@RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate,
1844
                                avg3MonthS.put(milestone, values);
1846
			@RequestParam List<Integer> fofoIds, @RequestParam String filterType, Model model) throws Exception {
1845
                            } else {
1847
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1846
 
1848
				.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream().collect(Collectors.groupingBy(
1847
                                values = new ArrayList<>();
1849
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1848
 
1850
 
1849
                                values.add(last3MonthSEntry.getKey());
1851
		ChartModel cm;
1850
 
1852
		if (warehouseId != 0) {
1851
                                avg3MonthS.put(milestone, values);
1853
			cm = adminUser.getBrandWiseLms(Arrays.asList(warehouseId),
1852
 
1854
					fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(),
1853
                            }
1855
					endDate.toLocalDate(), filterType);
1854
                        }
1856
		} else {
1855
 
1857
			cm = adminUser.getBrandWiseLms(new ArrayList<>(warehouseIdFofoIdMap.keySet()),
1856
                    }
1858
					fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(),
1857
 
1859
					endDate.toLocalDate(), filterType);
1858
                }
1860
 
1859
 
1861
		}
1860
                if (partnerDetails != null) {
1862
 
1861
                    Map<Milestone, List<Integer>> smtdMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarymtd()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
1863
		LOGGER.info("chartMap" + gson.toJson(cm));
1862
                    Map<Milestone, List<Integer>> slmtdMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarylmtd()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
1864
		model.addAttribute("chartMap", gson.toJson(cm));
1863
                    Map<Milestone, List<Integer>> lmsMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarylms()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
1865
		return "brand-wise-mobile-lms-chart";
1864
 
1866
	}
1865
                    model.addAttribute("smtdMap", smtdMap);
1867
 
1866
                    model.addAttribute("slmtdMap", slmtdMap);
1868
	@RequestMapping(value = "/getMobileLMSFilter", method = RequestMethod.GET)
1867
                    model.addAttribute("avg3MonthS", avg3MonthS);
1869
	public String getMobileLMSFilter(HttpServletRequest request,
1868
                    model.addAttribute("lmsMap", lmsMap);
1870
			@RequestParam(required = false, defaultValue = "0") int warehouseId,
1869
 
1871
			@RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate,
1870
                }
1872
			Model model) throws Exception {
1871
 
1873
 
1872
            }
1874
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1873
        }
1875
		String email = loginDetails.getEmailId();
1874
 
1876
 
1875
        model.addAttribute("warehouseMap", ProfitMandiConstants.WAREHOUSE_MAP);
1877
		if (date == null) {
1876
        model.addAttribute("warehouseId", warehouseId);
1878
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
1877
        model.addAttribute("milestones", Milestone.values());
1879
 
1878
 
1880
			LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
1879
        return "purchase-milestone";
1881
			date = startOfMonth.toLocalDate().atStartOfDay();
1880
 
1882
		}
1881
    }
1883
 
1882
 
1884
		if (endDate == null) {
1883
    @RequestMapping(value = "/getActivatedModelWarehouseWise", method = RequestMethod.GET)
1885
			LocalDateTime curDate = LocalDate.now().atTime(LocalTime.MAX);
1884
    public String getActivatedModelWarehouseWise(HttpServletRequest request, Model model, @RequestParam String brand) throws Exception {
1886
 
1885
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1887
			endDate = curDate;
1886
        List<Integer> fofoIds = getFofoIds(loginDetails);
1888
 
1887
        List<WarehouseWiseActivatedModel> warehouseWiseActivatedModels = activatedImeiRepository.selectActivatedModelGroupByWarehouse(brand, fofoIds);
1889
		}
1888
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1890
 
1889
 
1891
		Map<String, Object> map = adminUser.getFilter(warehouseId, email, date, endDate);
1890
        List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
1892
		model.addAttribute("warehouseId", warehouseId);
1891
 
1893
		model.addAllAttributes(map);
1892
        List<String> brands = mobileBrands.stream().map(x -> (String) x.get("name")).collect(Collectors.toList());
1894
 
1893
        LOGGER.info("brands" + brands.add("Redmi"));
1895
		return "chart-filter-lms";
1894
 
1896
	}
1895
        model.addAttribute("warehouseWiseActivatedModels", warehouseWiseActivatedModels);
1897
 
1896
        model.addAttribute("warehouseMap", warehouseMap);
1898
	@RequestMapping(value = "/getMobileLMPGraph", method = RequestMethod.GET)
1897
        model.addAttribute("brands", brands);
1899
	public String getMobileLMPGraph(HttpServletRequest request, @RequestParam(required = false) int warehouseId,
1898
        model.addAttribute("selectedbrand", brand);
1900
			@RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate,
1899
        return "warehousewise_activated_model";
1901
			@RequestParam List<Integer> fofoIds, @RequestParam String filterType, Model model) throws Exception {
1900
    }
1902
		Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1901
 
1903
				.selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream().collect(Collectors.groupingBy(
1902
    @RequestMapping(value = "/getActivatedModelByBrand", method = RequestMethod.GET)
1904
						FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
1903
    public String getActivatedModelByBrand(HttpServletRequest request, Model model) throws Exception {
1905
 
1904
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1906
		ChartModel cm;
1905
        Set<Integer> fofoIds = csService1.getAuthFofoIds(loginDetails.getEmailId(), true);
1907
		if (warehouseId != 0) {
1906
 
1908
			cm = adminUser.getBrandWiseLmp(Arrays.asList(warehouseId),
1907
        List<BrandWiseActivatedModel> activatedModels = activatedImeiRepository.selectActivatedModelGroupByBrand(new ArrayList<>(fofoIds));
1909
					fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(),
1908
        model.addAttribute("activatedModels", activatedModels);
1910
					endDate.toLocalDate(), filterType);
1909
        return "activation-brandwise-report";
1911
		} else {
1910
    }
1912
			cm = adminUser.getBrandWiseLmp(new ArrayList<>(warehouseIdFofoIdMap.keySet()),
1911
 
1913
					fofoIds.stream().map(x -> x).collect(Collectors.toList()), date.toLocalDate(),
1912
    @RequestMapping(value = "/getWarehouseBrandWiseItemActivatedModel", method = RequestMethod.GET)
1914
					endDate.toLocalDate(), filterType);
1913
    public String getWarehouseBrandWiseItemActivatedModel(HttpServletRequest request, Model model, @RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
1915
 
1914
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1916
		}
1915
        List<Integer> fofoIds = getFofoIds(loginDetails);
1917
 
1916
 
1918
		LOGGER.info("chartMap" + gson.toJson(cm));
1917
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1919
		model.addAttribute("chartMap", gson.toJson(cm));
1918
        List<WarehouseBrandWiseItemActivatedModel> activatedItems = activatedImeiRepository.selectWarehouseBrandActivatedItem(warehouseId, brand, fofoIds);
1920
		return "brand-wise-mobile-lmp-chart";
1919
        model.addAttribute("warehouseMap", warehouseMap);
1921
	}
1920
        model.addAttribute("activatedItems", activatedItems);
1922
 
1921
        return "warehouse-activated-itemwise-model";
1923
	@RequestMapping(value = "/getSaleCountByMilestone", method = RequestMethod.GET)
1922
 
1924
	public String getSaleCountByMilestone(HttpServletRequest request,
1923
    }
1925
			@RequestParam(required = false, defaultValue = "0") int warehouseId, Model model) throws Exception {
1924
 
1926
 
1925
    @RequestMapping(value = "/getActivatedImeiUpdationDate", method = RequestMethod.GET)
1927
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1926
    public String getActivatedImeiUpdationDate(HttpServletRequest request, Model model) throws Exception {
1928
		String email = loginDetails.getEmailId();
1927
 
1929
		Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
1928
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1930
		Map<Integer, Double> last3MonthSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
1929
 
1931
				LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now(), 0, false);
1930
        List<ActivationImeiUpdationModel> activationImeiUpdations = activatedImeiRepository.selectActivatedUpdationDate();
1932
 
1931
        model.addAttribute("warehouseMap", warehouseMap);
1933
		if (fofoIds != null && fofoIds.size() > 0) {
1932
        model.addAttribute("activationImeiUpdations", activationImeiUpdations);
1934
			if (warehouseId != 0) {
1933
        return "activation-updation-timestamp";
1935
				fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId)
1934
 
1936
						.stream().map(x -> x).collect(Collectors.toSet());
1935
    }
1937
			}
1936
 
1938
			Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
1937
    private List<Integer> getFofoIds(LoginDetails loginDetails) throws ProfitMandiBusinessException {
1939
			if (partnerStats != null) {
1938
        String email = loginDetails.getEmailId();
1940
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().filter(x -> partnerStats.containsKey(x))
1939
 
1941
						.map(x -> partnerStats.get(x)).collect(Collectors.toList());
1940
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1942
				Map<Milestone, List<Integer>> avg3Monthlms = new HashMap<>();
1941
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1943
				if (!last3MonthSale.isEmpty()) {
1942
 
1944
					int days = 60 + LocalDateTime.now().getDayOfMonth();
1943
        Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
1945
					for (Entry<Integer, Double> last3MonthEntry : last3MonthSale.entrySet()) {
1944
        if (emails.contains(authUser.getEmailId())) {
1946
						if (fofoIds.contains(last3MonthEntry.getKey())) {
1945
            fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
1947
							Double monthSale = last3MonthEntry.getValue();
1946
            LOGGER.info("fofoIds" + fofoIds);
1948
							if (monthSale == null) {
1947
        }
1949
								monthSale = (double) 0;
1948
 
1950
 
1949
        if (fofoIds == null) {
1951
							}
1950
            List<Position> positions1 = positionRepository.selectAll(authUser.getId());
1952
							double avg3MonthSale = (monthSale / days) * 30;
1951
            if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER).count() > 0) {
1953
							Milestone milestone = Milestone.get((int) avg3MonthSale);
1952
                fofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream().flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
1954
 
1953
            }
1955
							List<Integer> values = null;
1954
        }
1956
 
1955
        return new ArrayList<>(fofoIds);
1957
							if (avg3Monthlms.containsKey(milestone)) {
1956
    }
1958
 
1957
 
1959
								values = avg3Monthlms.get(milestone);
1958
    @RequestMapping(value = "/getMonthWiseSale", method = RequestMethod.GET)
1960
								values.add(last3MonthEntry.getKey());
1959
    public String getPartnerSaleByMonth(HttpServletRequest request, @RequestParam List<Integer> fofoIds, Model model) throws Exception {
1961
								avg3Monthlms.put(milestone, values);
1960
 
1962
 
1961
        YearMonth now = YearMonth.now();
1963
							} else {
1962
        YearMonth ym = YearMonth.now().minusMonths(12);
1964
								values = new ArrayList<>();
1963
        List<YearMonth> list = new ArrayList<>();
1965
 
1964
        while (!now.isBefore(ym)) {
1966
								values.add(last3MonthEntry.getKey());
1965
            list.add(now);
1967
								avg3Monthlms.put(milestone, values);
1966
            now = now.minusMonths(1);
1968
 
1967
        }
1969
							}
1968
 
1970
						}
1969
        model.addAttribute("yearMonth", list);
1971
 
1970
 
1972
					}
1971
        List<PartnerMonthlySaleModel> partnerMonthlySaleModels = fofoOrderItemRepository.selectPartnerMonthlySale(fofoIds, LocalDateTime.now().minusMonths(12).withDayOfMonth(1));
1973
 
1972
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
1974
				}
1973
        Map<Integer, Map<YearMonth, Double>> partnerMonthSaleMap = new HashMap<>();
1975
 
1974
        if (!partnerMonthlySaleModels.isEmpty()) {
1976
				if (partnerDetails != null) {
1975
 
1977
 
1976
            partnerMonthSaleMap = partnerMonthlySaleModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.toMap(
1978
					Map<Milestone, List<Integer>> mtdMap = partnerDetails.stream()
1977
                    x -> YearMonth.parse(x.getYearMonth(), dateTimeFormatter), x -> (double) x.getAmount())));
1979
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getMtd()),
1978
        }
1980
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
1979
 
1981
					Map<Milestone, List<Integer>> lmtdMap = partnerDetails.stream()
1980
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers().entrySet().stream().filter(x -> fofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1982
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getLmtd()),
1981
 
1983
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
1982
        model.addAttribute("customRetailerMap", customRetailerMap);
1984
 
1983
 
1985
					Map<Milestone, List<Integer>> lmsMap = partnerDetails.stream()
1984
        model.addAttribute("customRetailerMap", customRetailerMap);
1986
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getLms()),
1985
 
1987
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
1986
        model.addAttribute("partnerMonthSaleMap", partnerMonthSaleMap);
1988
 
1987
        return "monthly-partner-sale";
1989
					model.addAttribute("mtdMap", mtdMap);
1988
 
1990
					model.addAttribute("lmtdMap", lmtdMap);
1989
    }
1991
					model.addAttribute("avg3Monthlms", avg3Monthlms);
1990
 
1992
					model.addAttribute("lmsMap", lmsMap);
1991
    @RequestMapping(value = "/getMonthWisePurchase", method = RequestMethod.GET)
1993
				}
1992
    public String getMonthWisePurchase(HttpServletRequest request, @RequestParam List<Integer> fofoIds, Model model) throws Exception {
1994
 
1993
 
1995
			}
1994
        YearMonth now = YearMonth.now();
1996
		}
1995
        YearMonth ym = YearMonth.now().minusMonths(12);
1997
 
1996
        List<YearMonth> list = new ArrayList<>();
1998
		model.addAttribute("warehouseMap", ProfitMandiConstants.WAREHOUSE_MAP);
1997
        while (!now.isBefore(ym)) {
1999
		model.addAttribute("warehouseId", warehouseId);
1998
            list.add(now);
2000
		model.addAttribute("milestones", Milestone.values());
1999
            now = now.minusMonths(1);
2001
 
2000
        }
2002
		return "sale-milestone";
2001
 
2003
 
2002
        model.addAttribute("yearMonth", list);
2004
	}
2003
 
2005
 
2004
        List<PartnerMonthlySaleModel> partnerMonthlySaleModels = orderRepository.selectSecondaryGroupByYearMonth(
2006
	@RequestMapping(value = "/getPurchaseCountByMileStone", method = RequestMethod.GET)
2005
                fofoIds, LocalDate.now().withDayOfMonth(1).atStartOfDay().minusMonths(12));
2007
	public String getPurchaseCountByMileStone(HttpServletRequest request,
2006
        Map<Integer, Map<YearMonth, Double>> partnerMonthPurchaseMap = partnerMonthlySaleModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.groupingBy(
2008
			@RequestParam(required = false, defaultValue = "0") int warehouseId, Model model) throws Exception {
2007
                y -> YearMonth.parse(y.getYearMonth(), DateTimeFormatter.ofPattern("MM-yyyy")), Collectors.summingDouble(x -> x.getAmount()))));
2009
 
2008
 
2010
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2009
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers().entrySet().stream().filter(x -> fofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
2011
		String email = loginDetails.getEmailId();
2010
        model.addAttribute("customRetailerMap", customRetailerMap);
2012
		Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
2011
        model.addAttribute("partnerMonthPurchaseMap", partnerMonthPurchaseMap);
2013
		Map<Integer, Double> last3MonthS = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(
2012
        return "monthly-partner-purchase";
2014
				LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now());
-
 
2015
 
-
 
2016
		if (fofoIds != null && fofoIds.size() > 0) {
-
 
2017
			if (warehouseId != 0) {
-
 
2018
				fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId)
-
 
2019
						.stream().map(x -> x).collect(Collectors.toSet());
-
 
2020
			}
-
 
2021
			Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
-
 
2022
			if (partnerStats != null) {
-
 
2023
				List<PartnerDetailModel> partnerDetails = fofoIds.stream().filter(x -> partnerStats.containsKey(x))
-
 
2024
						.map(x -> partnerStats.get(x)).collect(Collectors.toList());
-
 
2025
				Map<Milestone, List<Integer>> avg3MonthS = new HashMap<>();
-
 
2026
				if (!last3MonthS.isEmpty()) {
-
 
2027
					int days = 60 + LocalDateTime.now().getDayOfMonth();
-
 
2028
					for (Entry<Integer, Double> last3MonthSEntry : last3MonthS.entrySet()) {
-
 
2029
						if (fofoIds.contains(last3MonthSEntry.getKey())) {
-
 
2030
							Double monthSec = last3MonthSEntry.getValue();
-
 
2031
							if (monthSec == null) {
-
 
2032
								monthSec = (double) 0;
-
 
2033
 
-
 
2034
							}
-
 
2035
							double avg3MonthSale = (monthSec / days) * 30;
-
 
2036
							Milestone milestone = Milestone.get((int) avg3MonthSale);
-
 
2037
 
-
 
2038
							List<Integer> values = null;
-
 
2039
							if (avg3MonthS.containsKey(milestone)) {
-
 
2040
								values = avg3MonthS.get(milestone);
-
 
2041
								values.add(last3MonthSEntry.getKey());
-
 
2042
 
-
 
2043
								avg3MonthS.put(milestone, values);
-
 
2044
							} else {
-
 
2045
 
-
 
2046
								values = new ArrayList<>();
-
 
2047
 
-
 
2048
								values.add(last3MonthSEntry.getKey());
-
 
2049
 
-
 
2050
								avg3MonthS.put(milestone, values);
-
 
2051
 
-
 
2052
							}
-
 
2053
						}
-
 
2054
 
-
 
2055
					}
-
 
2056
 
-
 
2057
				}
-
 
2058
 
-
 
2059
				if (partnerDetails != null) {
-
 
2060
					Map<Milestone, List<Integer>> smtdMap = partnerDetails.stream()
-
 
2061
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarymtd()),
-
 
2062
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
-
 
2063
					Map<Milestone, List<Integer>> slmtdMap = partnerDetails.stream()
-
 
2064
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarylmtd()),
-
 
2065
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
-
 
2066
					Map<Milestone, List<Integer>> lmsMap = partnerDetails.stream()
-
 
2067
							.collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarylms()),
-
 
2068
									Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
-
 
2069
 
-
 
2070
					model.addAttribute("smtdMap", smtdMap);
-
 
2071
					model.addAttribute("slmtdMap", slmtdMap);
-
 
2072
					model.addAttribute("avg3MonthS", avg3MonthS);
-
 
2073
					model.addAttribute("lmsMap", lmsMap);
-
 
2074
 
-
 
2075
				}
-
 
2076
 
-
 
2077
			}
-
 
2078
		}
-
 
2079
 
-
 
2080
		model.addAttribute("warehouseMap", ProfitMandiConstants.WAREHOUSE_MAP);
-
 
2081
		model.addAttribute("warehouseId", warehouseId);
-
 
2082
		model.addAttribute("milestones", Milestone.values());
-
 
2083
 
-
 
2084
		return "purchase-milestone";
-
 
2085
 
-
 
2086
	}
-
 
2087
 
-
 
2088
	@RequestMapping(value = "/getActivatedModelWarehouseWise", method = RequestMethod.GET)
-
 
2089
	public String getActivatedModelWarehouseWise(HttpServletRequest request, Model model, @RequestParam String brand)
-
 
2090
			throws Exception {
-
 
2091
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
-
 
2092
		List<Integer> fofoIds = getFofoIds(loginDetails);
-
 
2093
		List<WarehouseWiseActivatedModel> warehouseWiseActivatedModels = activatedImeiRepository
-
 
2094
				.selectActivatedModelGroupByWarehouse(brand, fofoIds);
-
 
2095
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
-
 
2096
 
-
 
2097
		List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
-
 
2098
 
-
 
2099
		List<String> brands = mobileBrands.stream().map(x -> (String) x.get("name")).collect(Collectors.toList());
-
 
2100
		LOGGER.info("brands" + brands.add("Redmi"));
-
 
2101
 
-
 
2102
		model.addAttribute("warehouseWiseActivatedModels", warehouseWiseActivatedModels);
-
 
2103
		model.addAttribute("warehouseMap", warehouseMap);
-
 
2104
		model.addAttribute("brands", brands);
-
 
2105
		model.addAttribute("selectedbrand", brand);
-
 
2106
		return "warehousewise_activated_model";
-
 
2107
	}
-
 
2108
 
-
 
2109
	@RequestMapping(value = "/getActivatedModelByBrand", method = RequestMethod.GET)
-
 
2110
	public String getActivatedModelByBrand(HttpServletRequest request, Model model) throws Exception {
-
 
2111
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
-
 
2112
		Set<Integer> fofoIds = csService1.getAuthFofoIds(loginDetails.getEmailId(), true);
-
 
2113
 
-
 
2114
		List<BrandWiseActivatedModel> activatedModels = activatedImeiRepository
-
 
2115
				.selectActivatedModelGroupByBrand(new ArrayList<>(fofoIds));
-
 
2116
		model.addAttribute("activatedModels", activatedModels);
-
 
2117
		return "activation-brandwise-report";
-
 
2118
	}
-
 
2119
 
-
 
2120
	@RequestMapping(value = "/getWarehouseBrandWiseItemActivatedModel", method = RequestMethod.GET)
-
 
2121
	public String getWarehouseBrandWiseItemActivatedModel(HttpServletRequest request, Model model,
-
 
2122
			@RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
-
 
2123
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
-
 
2124
		List<Integer> fofoIds = getFofoIds(loginDetails);
-
 
2125
 
-
 
2126
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
-
 
2127
		List<WarehouseBrandWiseItemActivatedModel> activatedItems = activatedImeiRepository
-
 
2128
				.selectWarehouseBrandActivatedItem(warehouseId, brand, fofoIds);
-
 
2129
		model.addAttribute("warehouseMap", warehouseMap);
-
 
2130
		model.addAttribute("activatedItems", activatedItems);
-
 
2131
		return "warehouse-activated-itemwise-model";
-
 
2132
 
-
 
2133
	}
-
 
2134
 
-
 
2135
	@RequestMapping(value = "/getActivatedImeiUpdationDate", method = RequestMethod.GET)
-
 
2136
	public String getActivatedImeiUpdationDate(HttpServletRequest request, Model model) throws Exception {
-
 
2137
 
-
 
2138
		Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
-
 
2139
 
-
 
2140
		List<ActivationImeiUpdationModel> activationImeiUpdations = activatedImeiRepository
-
 
2141
				.selectActivatedUpdationDate();
-
 
2142
		model.addAttribute("warehouseMap", warehouseMap);
-
 
2143
		model.addAttribute("activationImeiUpdations", activationImeiUpdations);
-
 
2144
		return "activation-updation-timestamp";
-
 
2145
 
-
 
2146
	}
-
 
2147
 
-
 
2148
	private List<Integer> getFofoIds(LoginDetails loginDetails) throws ProfitMandiBusinessException {
-
 
2149
		String email = loginDetails.getEmailId();
-
 
2150
 
-
 
2151
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
-
 
2152
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
-
 
2153
 
-
 
2154
		Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
-
 
2155
		if (emails.contains(authUser.getEmailId())) {
-
 
2156
			fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
-
 
2157
			LOGGER.info("fofoIds" + fofoIds);
-
 
2158
		}
-
 
2159
 
-
 
2160
		if (fofoIds == null) {
-
 
2161
			List<Position> positions1 = positionRepository.selectAll(authUser.getId());
-
 
2162
			if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER)
-
 
2163
					.count() > 0) {
-
 
2164
				fofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream().flatMap(x -> x.stream())
-
 
2165
						.map(x -> x.getPartnerId()).collect(Collectors.toSet());
-
 
2166
			}
-
 
2167
		}
-
 
2168
		return new ArrayList<>(fofoIds);
-
 
2169
	}
-
 
2170
 
-
 
2171
	@RequestMapping(value = "/getMonthWiseSale", method = RequestMethod.GET)
-
 
2172
	public String getPartnerSaleByMonth(HttpServletRequest request, @RequestParam List<Integer> fofoIds, Model model)
-
 
2173
			throws Exception {
-
 
2174
 
-
 
2175
		YearMonth now = YearMonth.now();
-
 
2176
		YearMonth ym = YearMonth.now().minusMonths(12);
-
 
2177
		List<YearMonth> list = new ArrayList<>();
-
 
2178
		while (!now.isBefore(ym)) {
-
 
2179
			list.add(now);
-
 
2180
			now = now.minusMonths(1);
-
 
2181
		}
-
 
2182
 
-
 
2183
		model.addAttribute("yearMonth", list);
-
 
2184
 
-
 
2185
		List<PartnerMonthlySaleModel> partnerMonthlySaleModels = fofoOrderItemRepository
-
 
2186
				.selectPartnerMonthlySale(fofoIds, LocalDateTime.now().minusMonths(12).withDayOfMonth(1));
-
 
2187
		DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
-
 
2188
		Map<Integer, Map<YearMonth, Double>> partnerMonthSaleMap = new HashMap<>();
-
 
2189
		if (!partnerMonthlySaleModels.isEmpty()) {
-
 
2190
 
-
 
2191
			partnerMonthSaleMap = partnerMonthlySaleModels.stream()
-
 
2192
					.collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.toMap(
-
 
2193
							x -> YearMonth.parse(x.getYearMonth(), dateTimeFormatter), x -> (double) x.getAmount())));
-
 
2194
		}
-
 
2195
 
-
 
2196
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers().entrySet().stream()
-
 
2197
				.filter(x -> fofoIds.contains(x.getKey()))
-
 
2198
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
-
 
2199
 
-
 
2200
		model.addAttribute("customRetailerMap", customRetailerMap);
-
 
2201
 
-
 
2202
		model.addAttribute("customRetailerMap", customRetailerMap);
-
 
2203
 
-
 
2204
		model.addAttribute("partnerMonthSaleMap", partnerMonthSaleMap);
-
 
2205
		return "monthly-partner-sale";
-
 
2206
 
-
 
2207
	}
-
 
2208
 
-
 
2209
	@RequestMapping(value = "/getMonthWisePurchase", method = RequestMethod.GET)
-
 
2210
	public String getMonthWisePurchase(HttpServletRequest request, @RequestParam List<Integer> fofoIds, Model model)
-
 
2211
			throws Exception {
-
 
2212
 
-
 
2213
		YearMonth now = YearMonth.now();
-
 
2214
		YearMonth ym = YearMonth.now().minusMonths(12);
-
 
2215
		List<YearMonth> list = new ArrayList<>();
-
 
2216
		while (!now.isBefore(ym)) {
-
 
2217
			list.add(now);
-
 
2218
			now = now.minusMonths(1);
-
 
2219
		}
-
 
2220
 
-
 
2221
		model.addAttribute("yearMonth", list);
-
 
2222
 
-
 
2223
		List<PartnerMonthlySaleModel> partnerMonthlySaleModels = orderRepository.selectSecondaryGroupByYearMonth(
-
 
2224
				fofoIds, LocalDate.now().withDayOfMonth(1).atStartOfDay().minusMonths(12));
-
 
2225
		Map<Integer, Map<YearMonth, Double>> partnerMonthPurchaseMap = partnerMonthlySaleModels.stream()
-
 
2226
				.collect(Collectors.groupingBy(x -> x.getFofoId(),
-
 
2227
						Collectors.groupingBy(
-
 
2228
								y -> YearMonth.parse(y.getYearMonth(), DateTimeFormatter.ofPattern("MM-yyyy")),
-
 
2229
								Collectors.summingDouble(x -> x.getAmount()))));
-
 
2230
 
-
 
2231
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers().entrySet().stream()
-
 
2232
				.filter(x -> fofoIds.contains(x.getKey()))
-
 
2233
				.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
-
 
2234
		model.addAttribute("customRetailerMap", customRetailerMap);
-
 
2235
		model.addAttribute("partnerMonthPurchaseMap", partnerMonthPurchaseMap);
-
 
2236
		return "monthly-partner-purchase";
-
 
2237
 
2013
 
2238
	}
2014
    }
2239
}
2015
}