Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
23405 amit.gupta 1
package com.spice.profitmandi.web.controller;
2
 
25721 tejbeer 3
import java.time.LocalDate;
4
import java.time.LocalDateTime;
26131 tejbeer 5
import java.time.LocalTime;
23785 amit.gupta 6
import java.util.ArrayList;
23405 amit.gupta 7
import java.util.Arrays;
23796 amit.gupta 8
import java.util.Collections;
9
import java.util.Comparator;
10
import java.util.HashMap;
24406 amit.gupta 11
import java.util.HashSet;
23785 amit.gupta 12
import java.util.Iterator;
23405 amit.gupta 13
import java.util.List;
14
import java.util.Map;
27769 tejbeer 15
import java.util.Map.Entry;
23785 amit.gupta 16
import java.util.Set;
25721 tejbeer 17
import java.util.function.Function;
23405 amit.gupta 18
import java.util.stream.Collectors;
19
 
20
import javax.servlet.http.HttpServletRequest;
21
 
24231 amit.gupta 22
import org.apache.commons.io.output.ByteArrayOutputStream;
23717 amit.gupta 23
import org.apache.logging.log4j.LogManager;
23568 govind 24
import org.apache.logging.log4j.Logger;
23796 amit.gupta 25
import org.apache.thrift.TException;
24349 amit.gupta 26
import org.json.JSONArray;
23779 amit.gupta 27
import org.json.JSONObject;
23405 amit.gupta 28
import org.springframework.beans.factory.annotation.Autowired;
24231 amit.gupta 29
import org.springframework.core.io.ByteArrayResource;
30
import org.springframework.http.HttpHeaders;
31
import org.springframework.http.HttpStatus;
32
import org.springframework.http.ResponseEntity;
25721 tejbeer 33
import org.springframework.mail.javamail.JavaMailSender;
23405 amit.gupta 34
import org.springframework.stereotype.Controller;
35
import org.springframework.transaction.annotation.Transactional;
36
import org.springframework.ui.Model;
37
import org.springframework.web.bind.annotation.RequestBody;
38
import org.springframework.web.bind.annotation.RequestMapping;
39
import org.springframework.web.bind.annotation.RequestMethod;
23779 amit.gupta 40
import org.springframework.web.bind.annotation.RequestParam;
23405 amit.gupta 41
 
25736 tejbeer 42
import com.mongodb.DBObject;
23785 amit.gupta 43
import com.spice.profitmandi.common.enumuration.CounterSize;
26846 tejbeer 44
import com.spice.profitmandi.common.enumuration.MessageType;
23405 amit.gupta 45
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
25798 tejbeer 46
import com.spice.profitmandi.common.model.BrandStockPrice;
25796 tejbeer 47
import com.spice.profitmandi.common.model.CatalogIdAggregateValue;
24231 amit.gupta 48
import com.spice.profitmandi.common.model.CatalogListingModel;
23785 amit.gupta 49
import com.spice.profitmandi.common.model.CustomRetailer;
25721 tejbeer 50
import com.spice.profitmandi.common.model.PlannedModel;
26846 tejbeer 51
import com.spice.profitmandi.common.model.SendNotificationModel;
23779 amit.gupta 52
import com.spice.profitmandi.common.model.StockAllocationModel;
26951 amit.gupta 53
import com.spice.profitmandi.common.model.SuggestedPoIdModel;
54
import com.spice.profitmandi.common.model.SuggestedPoModel;
24231 amit.gupta 55
import com.spice.profitmandi.common.util.FileUtil;
25721 tejbeer 56
import com.spice.profitmandi.common.util.Utils;
57
import com.spice.profitmandi.common.util.Utils.Attachment;
26721 tejbeer 58
import com.spice.profitmandi.dao.entity.auth.AuthUser;
25721 tejbeer 59
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
23785 amit.gupta 60
import com.spice.profitmandi.dao.entity.catalog.Item;
23405 amit.gupta 61
import com.spice.profitmandi.dao.entity.catalog.TagListing;
27088 tejbeer 62
import com.spice.profitmandi.dao.entity.cs.Region;
25796 tejbeer 63
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
64
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23785 amit.gupta 65
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
25721 tejbeer 66
import com.spice.profitmandi.dao.entity.fofo.MonthlyPlanned;
26951 amit.gupta 67
import com.spice.profitmandi.dao.entity.fofo.PlannedDetail;
26846 tejbeer 68
import com.spice.profitmandi.dao.entity.fofo.SuggestedPo;
69
import com.spice.profitmandi.dao.entity.fofo.SuggestedPoDetail;
27768 tejbeer 70
import com.spice.profitmandi.dao.entity.inventory.SaholicCIS;
23796 amit.gupta 71
import com.spice.profitmandi.dao.entity.transaction.Order;
26846 tejbeer 72
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
23796 amit.gupta 73
import com.spice.profitmandi.dao.entity.user.User;
26978 tejbeer 74
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26721 tejbeer 75
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
25721 tejbeer 76
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
23405 amit.gupta 77
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
78
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
25721 tejbeer 79
import com.spice.profitmandi.dao.repository.cs.CsService;
27088 tejbeer 80
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
81
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
23779 amit.gupta 82
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25736 tejbeer 83
import com.spice.profitmandi.dao.repository.dtr.Mongo;
26846 tejbeer 84
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
23405 amit.gupta 85
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
25732 tejbeer 86
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
25721 tejbeer 87
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
88
import com.spice.profitmandi.dao.repository.fofo.MonthlyPlannedRepository;
27081 tejbeer 89
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeRepository;
26951 amit.gupta 90
import com.spice.profitmandi.dao.repository.fofo.PlannedDetailRepository;
91
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
26846 tejbeer 92
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoDetailRepository;
93
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoRepository;
27768 tejbeer 94
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
23796 amit.gupta 95
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
96
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
97
import com.spice.profitmandi.dao.repository.user.UserRepository;
26846 tejbeer 98
import com.spice.profitmandi.service.NotificationService;
23798 amit.gupta 99
import com.spice.profitmandi.service.authentication.RoleManager;
25736 tejbeer 100
import com.spice.profitmandi.service.inventory.InventoryService;
27768 tejbeer 101
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
23779 amit.gupta 102
import com.spice.profitmandi.service.inventory.StockAllocationService;
103
import com.spice.profitmandi.service.user.RetailerService;
25547 amit.gupta 104
import com.spice.profitmandi.service.wallet.WalletService;
23796 amit.gupta 105
import com.spice.profitmandi.thrift.clients.PaymentClient;
106
import com.spice.profitmandi.thrift.clients.TransactionClient;
107
import com.spice.profitmandi.thrift.clients.UserClient;
23405 amit.gupta 108
import com.spice.profitmandi.web.model.LoginDetails;
109
import com.spice.profitmandi.web.util.CookiesProcessor;
110
import com.spice.profitmandi.web.util.MVCResponseSender;
111
 
23796 amit.gupta 112
import in.shop2020.logistics.PickUpType;
113
import in.shop2020.model.v1.order.LineItem;
114
import in.shop2020.model.v1.order.OrderSource;
115
import in.shop2020.model.v1.order.OrderStatus;
116
import in.shop2020.model.v1.order.OrderType;
117
import in.shop2020.model.v1.order.Transaction;
118
import in.shop2020.model.v1.order.TransactionService;
119
import in.shop2020.model.v1.order.TransactionStatus;
120
import in.shop2020.model.v1.user.ItemPriceQuantity;
121
import in.shop2020.model.v1.user.ShoppingCartException;
122
import in.shop2020.model.v1.user.UserContextService.Client;
123
import in.shop2020.payments.Attribute;
124
import in.shop2020.payments.PaymentException;
125
import in.shop2020.payments.PaymentStatus;
126
 
23405 amit.gupta 127
@Controller
128
@Transactional(rollbackFor = Throwable.class)
129
public class IndentController {
130
 
23568 govind 131
	private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
23796 amit.gupta 132
	private static final int WALLET_GATEWAY_ID = 8;
24406 amit.gupta 133
	private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));
23405 amit.gupta 134
 
23796 amit.gupta 135
	private final List<OrderStatus> validOrderStatusList = Arrays.asList(OrderStatus.ACCEPTED,
136
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
137
			OrderStatus.DELIVERY_SUCCESS, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
138
			OrderStatus.REACHED_DESTINATION_CITY);
139
 
24231 amit.gupta 140
	private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,
141
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
142
			OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
143
			OrderStatus.REACHED_DESTINATION_CITY);
25721 tejbeer 144
 
26951 amit.gupta 145
	private static final int PLANNING_OPEN_DAY = 20;
146
	private static final int PLANNING_CLOSE_DAY = 1;
147
 
25547 amit.gupta 148
	@Autowired
149
	WalletService walletService;
24231 amit.gupta 150
 
23405 amit.gupta 151
	@Autowired
25721 tejbeer 152
	private JavaMailSender googleMailSender;
153
 
154
	@Autowired
23405 amit.gupta 155
	private CookiesProcessor cookiesProcessor;
24231 amit.gupta 156
 
23796 amit.gupta 157
	@Autowired
158
	private UserWalletRepository userWalletRepository;
23785 amit.gupta 159
 
23779 amit.gupta 160
	@Autowired
23796 amit.gupta 161
	private UserRepository userRepository;
162
 
163
	@Autowired
23779 amit.gupta 164
	FofoStoreRepository fofoStoreRepository;
23405 amit.gupta 165
 
166
	@Autowired
23796 amit.gupta 167
	private OrderRepository orderRepository;
168
 
169
	@Autowired
26846 tejbeer 170
	private UserAccountRepository userAccountRepository;
171
 
172
	@Autowired
23405 amit.gupta 173
	private ItemRepository itemRepository;
174
 
175
	@Autowired
23779 amit.gupta 176
	private StockAllocationService stockAllocationService;
177
 
178
	@Autowired
179
	private RetailerService retailerService;
23405 amit.gupta 180
 
181
	@Autowired
182
	private TagListingRepository tagListingRepository;
183
 
184
	@Autowired
185
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
186
 
187
	@Autowired
23796 amit.gupta 188
	private PurchaseRepository purchaseRepository;
189
 
190
	@Autowired
23405 amit.gupta 191
	private MVCResponseSender mvcResponseSender;
192
 
23785 amit.gupta 193
	@Autowired
25721 tejbeer 194
	private FocusedModelRepository focusedModelRepository;
195
 
196
	@Autowired
197
	private MonthlyPlannedRepository monthlyPlannedRepository;
198
 
199
	@Autowired
200
	private FofoOrderRepository fofoOrderRepository;
25732 tejbeer 201
 
25721 tejbeer 202
	@Autowired
25732 tejbeer 203
	private FofoOrderItemRepository fofoOrderItemRepository;
204
 
205
	@Autowired
25721 tejbeer 206
	private PlannedDetailRepository plannedDetailRepository;
25732 tejbeer 207
 
25721 tejbeer 208
	@Autowired
23785 amit.gupta 209
	RoleManager roleManager;
23405 amit.gupta 210
 
25721 tejbeer 211
	@Autowired
27081 tejbeer 212
	PartnerTypeChangeRepository partnerTypeChangeRepository;
213
 
214
	@Autowired
25736 tejbeer 215
	private Mongo mongoClient;
216
 
217
	@Autowired
218
	private InventoryService inventoryService;
219
 
220
	@Autowired
26721 tejbeer 221
	private CsService csService;
25721 tejbeer 222
 
26721 tejbeer 223
	@Autowired
224
	private AuthRepository authRepository;
225
 
26846 tejbeer 226
	@Autowired
227
	private SuggestedPoRepository monthlyPoRepository;
228
 
229
	@Autowired
230
	private SuggestedPoDetailRepository monthlyPoDetailRepository;
231
 
232
	@Autowired
233
	private NotificationService notificationService;
234
 
27088 tejbeer 235
	@Autowired
236
	private RegionRepository regionRepository;
237
 
238
	@Autowired
239
	private PartnerRegionRepository partnerRegionRepository;
240
 
27768 tejbeer 241
	@Autowired
242
	private SaholicInventoryCISRepository saholicInventoryCISRepository;
243
 
244
	@Autowired
245
	private SaholicInventoryService saholicInventoryService;
246
 
23779 amit.gupta 247
	@RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
25721 tejbeer 248
	public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,
26978 tejbeer 249
			@RequestParam int itemQty, @RequestParam int fofoId) throws Exception {
27088 tejbeer 250
		if (fofoId == 0) {
251
 
252
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
253
			fofoId = loginDetails.getFofoId();
254
 
26990 tejbeer 255
		}
27088 tejbeer 256
 
26082 tejbeer 257
		LocalDate currentMonthDate = LocalDate.now();
258
		MonthlyPlanned monthlyPlanned = null;
25721 tejbeer 259
 
26951 amit.gupta 260
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26082 tejbeer 261
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
26978 tejbeer 262
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
263
			LOGGER.info("monthlyPlanned" + monthlyPlanned);
264
			saveMonthlyPlanned(monthlyPlanned, fofoId, currentMonthDate, catalogId, itemQty);
26082 tejbeer 265
		}
266
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
267
		return "response";
268
	}
269
 
270
	private void saveMonthlyPlanned(MonthlyPlanned monthlyPlanned, int fofoId, LocalDate currentMonthDate,
271
			int catalogId, int itemQty) {
25721 tejbeer 272
		if (monthlyPlanned == null) {
273
			monthlyPlanned = new MonthlyPlanned();
26082 tejbeer 274
			monthlyPlanned.setFofoId(fofoId);
275
			monthlyPlanned.setYearMonth(currentMonthDate);
25721 tejbeer 276
			monthlyPlannedRepository.persist(monthlyPlanned);
277
			PlannedDetail pd = new PlannedDetail();
278
			pd.setCatalogId(catalogId);
279
			pd.setPlannedId(monthlyPlanned.getId());
280
			pd.setQuantity(itemQty);
281
			pd.setUpdatedTimestamp(LocalDateTime.now());
282
			plannedDetailRepository.persist(pd);
283
 
23786 amit.gupta 284
		} else {
25721 tejbeer 285
			PlannedDetail plannedDetail = plannedDetailRepository.selectByPlannedIdCatalogId(monthlyPlanned.getId(),
286
					catalogId);
287
			if (plannedDetail == null) {
288
				plannedDetail = new PlannedDetail();
289
				plannedDetail.setCatalogId(catalogId);
290
				plannedDetail.setPlannedId(monthlyPlanned.getId());
291
				plannedDetail.setQuantity(itemQty);
292
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
293
				plannedDetailRepository.persist(plannedDetail);
294
			} else if (itemQty == 0) {
295
				plannedDetailRepository.delete(plannedDetail);
296
 
297
			} else {
298
				plannedDetail.setCatalogId(catalogId);
299
				plannedDetail.setQuantity(itemQty);
300
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
301
			}
302
 
23785 amit.gupta 303
		}
25721 tejbeer 304
 
305
	}
306
 
307
	@RequestMapping(value = "/open-indent/confirm", method = RequestMethod.POST)
26748 tejbeer 308
	public String confirmOpenIndent(HttpServletRequest request,
309
			@RequestParam(required = false, defaultValue = "0") int fofoId, Model model) throws Exception {
310
 
311
		if (fofoId == 0) {
312
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
313
			fofoId = loginDetails.getFofoId();
314
		}
25721 tejbeer 315
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
26748 tejbeer 316
 
26951 amit.gupta 317
		LocalDate currentDate = LocalDate.now();
318
		LocalDate planningMonthDate = null;
26082 tejbeer 319
		MonthlyPlanned monthlyPlanned = null;
26951 amit.gupta 320
		if (currentDate.isAfter(currentDate.withDayOfMonth(PLANNING_OPEN_DAY))) {
321
			planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
322
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
25721 tejbeer 323
 
26082 tejbeer 324
			confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
325
		}
326
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
327
 
328
		return "response";
329
	}
330
 
331
	private void confirmMonthlyPlanned(MonthlyPlanned monthlyPlanned, CustomRetailer customRetailer, int fofoId)
332
			throws Exception {
25721 tejbeer 333
		List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());
334
 
335
		List<PlannedModel> plannedModel = new ArrayList<>();
336
		for (PlannedDetail plannedDetail : plannedDetails) {
337
 
338
			List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());
339
			String itemDesription = items.get(0).getItemDescriptionNoColor();
340
			PlannedModel pm = new PlannedModel();
341
			pm.setItemDescription(itemDesription);
342
			pm.setStoreName(customRetailer.getBusinessName());
343
			pm.setQty(plannedDetail.getQuantity());
26082 tejbeer 344
			pm.setFofoId(fofoId);
25721 tejbeer 345
			plannedModel.add(pm);
346
			LOGGER.info("plannedModel" + plannedModel);
347
 
23785 amit.gupta 348
		}
26978 tejbeer 349
		List<String> ccemails = new ArrayList<>();
350
		LOGGER.info("ccemails" + ccemails);
351
		Map<EscalationType, String> emailEsclationType = csService.getAuthUserAndEsclationTypeByPartnerId(fofoId);
352
		LOGGER.info("emailEsclationType" + emailEsclationType);
353
		ccemails.add(emailEsclationType.get(EscalationType.L1));
354
		ccemails.add(emailEsclationType.get(EscalationType.L2));
355
		LOGGER.info("ccemails" + ccemails);
356
		List<String> bccemails = new ArrayList<>();
357
		bccemails.add(emailEsclationType.get(EscalationType.L3));
358
		LOGGER.info("bccemails" + bccemails);
25721 tejbeer 359
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
360
				Arrays.asList("Partner Id", "Partner Name", "Model Name", "Qty"),
361
				plannedModel.stream()
362
						.map(x -> Arrays.asList(x.getFofoId(), x.getStoreName(), x.getItemDescription(), x.getQty()))
363
						.collect(Collectors.toList()));
364
		LOGGER.info("baos" + baos);
26978 tejbeer 365
		Utils.sendMailWithAttachments(googleMailSender, new String[] { customRetailer.getEmail() },
366
				ccemails.toArray(new String[ccemails.size()]), bccemails.toArray(new String[bccemails.size()]),
25721 tejbeer 367
				"Planned Indent", "PFA",
368
				new Attachment[] { new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())), });
369
 
23405 amit.gupta 370
	}
371
 
24231 amit.gupta 372
	@RequestMapping(value = "/indent/download", method = RequestMethod.GET)
373
	public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,
374
			@RequestParam(required = false, defaultValue = "0") int fofoId,
375
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 376
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
377
		Set<Integer> roleIds = loginDetails.getRoleIds();
24231 amit.gupta 378
		LOGGER.info("Counter size is {}", counterSize);
379
		LOGGER.info("Fofo Id is {}", fofoId);
25721 tejbeer 380
		if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {
24231 amit.gupta 381
			List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
382
					.collect(Collectors.toList());
383
			Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
23415 amit.gupta 384
 
24232 amit.gupta 385
			List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,
386
					true);
387
			Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream()
388
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
23405 amit.gupta 389
 
24232 amit.gupta 390
			Map<String, Integer> catalogUserQtyMap = new HashMap<>();
25702 amit.gupta 391
			currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {
24232 amit.gupta 392
				int retailerId = x.getFofoId();
393
				int catalogId;
394
				try {
395
					catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();
396
					String key = catalogId + "-" + retailerId;
397
					if (!catalogUserQtyMap.containsKey(key)) {
398
						catalogUserQtyMap.put(key, 0);
399
					}
400
					catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());
401
				} catch (ProfitMandiBusinessException e) {
402
					// TODO Auto-generated catch block
403
					throw new RuntimeException(e);
24231 amit.gupta 404
				}
405
			});
23779 amit.gupta 406
 
24231 amit.gupta 407
			List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);
24232 amit.gupta 408
			Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {
409
				try {
410
					return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"
411
							+ x.getRetailerId();
412
				} catch (ProfitMandiBusinessException e) {
413
					// TODO Auto-generated catch block
414
					return "";
415
				}
416
			}, Collectors.summingInt(x -> x.getLineItem().getQuantity())));
23779 amit.gupta 417
 
24232 amit.gupta 418
			Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();
419
 
420
			List<TagListing> tagListings = tagListingRepository.selectAll(true);
421
			Iterator<TagListing> iterator = tagListings.iterator();
24231 amit.gupta 422
			while (iterator.hasNext()) {
423
				TagListing tagListing = iterator.next();
424
				Item item = itemRepository.selectById(tagListing.getItemId());
24232 amit.gupta 425
				int catalogId = item.getCatalogItemId();
24231 amit.gupta 426
				if (item.getCategoryId() != 10006) {
427
					continue;
428
				}
23779 amit.gupta 429
 
24232 amit.gupta 430
				int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)
431
						? modelStockAllocationMap.get(catalogId)
432
						: 0;
433
				for (int retailerId : fofoIds) {
434
					String key = catalogId + "-" + retailerId;
435
					if (catalogListingMap.containsKey(key)) {
436
						continue;
24231 amit.gupta 437
					}
24232 amit.gupta 438
					int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;
439
					int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;
440
					if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {
441
						continue;
442
					}
443
					CatalogListingModel catalogListingModel = new CatalogListingModel();
444
					catalogListingModel.setFofoId(retailerId);
445
					catalogListingModel.setModelName(item.getModelName());
446
					catalogListingModel.setModelNumber(item.getModelNumber());
447
					catalogListingModel.setCatalogId(catalogId);
448
					catalogListingModel.setDp(tagListing.getSellingPrice());
449
					catalogListingModel.setMop(tagListing.getMop());
450
					catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
451
					catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);
452
					catalogListingModel.setInTransitQuantity(catalogInTransit);
453
					catalogListingModel
454
							.setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);
24233 amit.gupta 455
					catalogListingModel.setStockInHand(catalogInStock);
24232 amit.gupta 456
					catalogListingModel.setBrand(item.getBrand());
457
					catalogListingModel.setModelName(item.getModelName());
458
					catalogListingModel.setModelNumber(item.getModelNumber());
459
					catalogListingModel.setCategoryId(item.getCategoryId());
460
					catalogListingMap.put(key, catalogListingModel);
23405 amit.gupta 461
				}
462
			}
25853 amit.gupta 463
			List<List<?>> listOfRows = new ArrayList<>();
24231 amit.gupta 464
			for (CatalogListingModel clm : catalogListingMap.values()) {
465
				CustomRetailer cr = customRetailersMap.get(clm.getFofoId());
24349 amit.gupta 466
				listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),
467
						clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),
468
						clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),
469
						clm.getToBeOrdered()));
24231 amit.gupta 470
			}
24349 amit.gupta 471
			ByteArrayOutputStream baos = FileUtil
472
					.getCSVByteStream(
473
							Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number",
474
									"DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
475
							listOfRows);
24231 amit.gupta 476
			HttpHeaders headers = new HttpHeaders();
477
			headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
478
			headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
24232 amit.gupta 479
			return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
480
					HttpStatus.OK);
23405 amit.gupta 481
		}
24231 amit.gupta 482
		return null;
24232 amit.gupta 483
 
23405 amit.gupta 484
	}
485
 
24349 amit.gupta 486
	@RequestMapping(value = "/itemsByCatalogId")
487
	public String getItemsByCatalogId(HttpServletRequest request, Model model,
24410 amit.gupta 488
			@RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
25378 tejbeer 489
			throws ProfitMandiBusinessException {
24410 amit.gupta 490
		if (catalogId == 0) {
491
			catalogId = itemRepository.selectById(itemId).getCatalogItemId();
492
		}
24349 amit.gupta 493
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
24414 amit.gupta 494
		LOGGER.info("Items {}", items);
25378 tejbeer 495
		Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
496
				.collect(Collectors.toMap(Item::getId, Item::getColor));
24413 amit.gupta 497
		Map<Integer, TagListing> tagsMap = tagListingRepository
498
				.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
25378 tejbeer 499
				.stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
24414 amit.gupta 500
		LOGGER.info("Items color map {}", itemsColorMap);
24349 amit.gupta 501
		JSONArray response = new JSONArray();
24413 amit.gupta 502
		itemsColorMap.keySet().stream().forEach(x -> {
25378 tejbeer 503
			response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",
504
					tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));
24349 amit.gupta 505
		});
506
		model.addAttribute("response", response.toString());
507
		return "response";
24410 amit.gupta 508
 
24349 amit.gupta 509
	}
510
 
23405 amit.gupta 511
	@RequestMapping(value = "/indent/loadIndent")
23785 amit.gupta 512
	public String loadOpenIndent(HttpServletRequest request, Model model,
513
			@RequestParam(required = false, defaultValue = "0") int fofoId,
25736 tejbeer 514
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 515
 
516
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
517
		Set<Integer> roleIds = loginDetails.getRoleIds();
23785 amit.gupta 518
		LOGGER.info("Counter size is {}", counterSize);
519
		LOGGER.info("Fofo Id is {}", fofoId);
25736 tejbeer 520
		boolean isAdmin = roleManager.isAdmin(roleIds);
25796 tejbeer 521
 
25797 tejbeer 522
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
523
				.collect(Collectors.toList());
524
 
25796 tejbeer 525
		Map<String, Object> equalsMap = new HashMap<>();
526
		equalsMap.put("categoryId", 10006);
25797 tejbeer 527
		equalsMap.put("brand", brands);
25796 tejbeer 528
		Map<String, List<?>> notEqualsMap = new HashMap<>();
529
 
530
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
531
		Map<Integer, Integer> currentStockMap;
532
 
25721 tejbeer 533
		if (!isAdmin && fofoId == 0) {
23786 amit.gupta 534
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
25796 tejbeer 535
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
536
			equalsStockJoinMap.put("fofoId", fofoId);
537
			currentStockMap = itemRepository
25800 tejbeer 538
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
539
							equalsStockJoinMap, notEqualsJoinMap, "availability")
25796 tejbeer 540
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25797 tejbeer 541
			LOGGER.info("currentStock");
23786 amit.gupta 542
		} else {
543
			if (fofoId == 0) {
25796 tejbeer 544
 
545
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
546
				equalsStockJoinMap.put("fofoId", fofoId);
547
 
548
				currentStockMap = itemRepository
25800 tejbeer 549
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 550
								equalsStockJoinMap, notEqualsJoinMap, "availability")
551
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
552
 
23779 amit.gupta 553
			} else {
25796 tejbeer 554
 
555
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
556
				equalsStockJoinMap.put("fofoId", fofoId);
557
 
558
				currentStockMap = itemRepository
25800 tejbeer 559
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 560
								equalsStockJoinMap, notEqualsJoinMap, "availability")
561
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
562
 
23405 amit.gupta 563
			}
23786 amit.gupta 564
		}
25796 tejbeer 565
 
566
		LOGGER.info("currentStock" + currentStockMap);
25797 tejbeer 567
 
23796 amit.gupta 568
		Map<Integer, Integer> itemsInTransit = null;
23855 amit.gupta 569
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
25702 amit.gupta 570
		if (!isAdmin) {
23786 amit.gupta 571
			tagListings = new ArrayList<>(tagListings);
25797 tejbeer 572
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
23796 amit.gupta 573
			inTransitOrders = this.filterValidOrders(inTransitOrders);
574
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
575
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
576
		} else {
577
			itemsInTransit = new HashMap<>();
23786 amit.gupta 578
		}
25797 tejbeer 579
 
23796 amit.gupta 580
		int totalPcs = 0;
25797 tejbeer 581
 
23796 amit.gupta 582
		float totalAmount = 0;
24231 amit.gupta 583
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
27088 tejbeer 584
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
585
				.collect(Collectors.toList());
25796 tejbeer 586
 
27088 tejbeer 587
		LOGGER.info("regionIds" + regionIds);
588
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
589
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
590
		LOGGER.info("focusedModelMap" + focusedModelMap);
26956 amit.gupta 591
		LocalDate planningMonthDate = null;
26082 tejbeer 592
		MonthlyPlanned monthlyPlanned = null;
26176 tejbeer 593
		List<Integer> fofoOrderIds = null;
26082 tejbeer 594
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 595
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26956 amit.gupta 596
			planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
597
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
26082 tejbeer 598
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
26176 tejbeer 599
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
600
					LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
601
					.collect(Collectors.toList());
26082 tejbeer 602
 
603
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 604
		} else {
26956 amit.gupta 605
			planningMonthDate = LocalDate.now().withDayOfMonth(1);
26176 tejbeer 606
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
26956 amit.gupta 607
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
608
			model.addAttribute("planningMonth", planningMonthDate.getMonth());
26176 tejbeer 609
			model.addAttribute("mtd", true);
26131 tejbeer 610
			model.addAttribute("freezed", true);
26176 tejbeer 611
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
612
					curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
613
					.collect(Collectors.toList());
26082 tejbeer 614
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
26978 tejbeer 615
		}
26082 tejbeer 616
 
25721 tejbeer 617
		Map<Integer, Integer> plannedDetailMap = null;
618
		if (monthlyPlanned != null) {
619
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
620
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
621
 
622
		}
25797 tejbeer 623
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
26176 tejbeer 624
 
25796 tejbeer 625
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
626
		Map<String, Object> equalsJoinMap = new HashMap<>();
26618 tejbeer 627
 
25796 tejbeer 628
		equalsJoinMap.put("orderId", fofoOrderIds);
26618 tejbeer 629
		Map<Integer, Integer> last15daysMap = null;
26748 tejbeer 630
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
24231 amit.gupta 631
 
26618 tejbeer 632
			last15daysMap = itemRepository
633
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
634
							notEqualsJoinMap, "quantity")
635
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
636
		}
25796 tejbeer 637
		LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 638
 
25796 tejbeer 639
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
640
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
641
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
642
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
643
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
25797 tejbeer 644
		LOGGER.info("catalogIdItemMap");
24231 amit.gupta 645
 
25796 tejbeer 646
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
25797 tejbeer 647
		equalsItemJoinMap.put("active", 1);
25800 tejbeer 648
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
649
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
25797 tejbeer 650
		LOGGER.info("tagListingCatalogIds");
25796 tejbeer 651
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
652
			int catalogId = catalogIdAggregateValue.getCatalogId();
653
			Item item = catalogIdItemMap.get(catalogId).get(0);
654
			TagListing tagListing = taglistingMap.get(item.getId());
24231 amit.gupta 655
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
656
			if (!catalogListingMap.containsKey(catalogId)) {
657
				catalogListingModel = new CatalogListingModel();
658
				catalogListingModel.setCatalogId(catalogId);
659
				catalogListingModel.setDp(tagListing.getSellingPrice());
660
				catalogListingModel.setMop(tagListing.getMop());
661
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
25721 tejbeer 662
				if (plannedDetailMap != null) {
663
 
664
					Integer quantity = plannedDetailMap.get(catalogId);
665
					if (quantity != null) {
666
						catalogListingModel.setAllocatedQuantity(quantity);
667
					}
668
				}
669
 
25796 tejbeer 670
				if (last15daysMap != null) {
671
					Integer last15DaysSale = last15daysMap.get(catalogId);
672
 
25721 tejbeer 673
					if (last15DaysSale != null) {
674
						catalogListingModel.setLast15DaysSale(last15DaysSale);
675
					} else {
676
						catalogListingModel.setLast15DaysSale(0);
677
					}
678
				} else {
679
					catalogListingModel.setLast15DaysSale(0);
680
				}
681
 
24231 amit.gupta 682
				catalogListingModel.setBrand(item.getBrand());
683
				if (item.getCategoryId() == 10006) {
684
					catalogListingModel.setCategoryId(item.getCategoryId());
685
				}
25721 tejbeer 686
 
687
				FocusedModel fm = focusedModelMap.get(catalogId);
688
				if (fm != null) {
689
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
690
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
691
 
692
				} else {
693
					catalogListingModel.setRecommendedQty(0);
694
					catalogListingModel.setMinimumQty(0);
695
				}
696
 
24231 amit.gupta 697
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 698
 
24231 amit.gupta 699
			}
25736 tejbeer 700
			int itemAvailability = 0;
25796 tejbeer 701
			if (currentStockMap != null) {
702
				Integer qty = currentStockMap.get(catalogId);
25736 tejbeer 703
				itemAvailability = qty == null ? 0 : qty;
704
				catalogListingModel.setStockInHand(itemAvailability);
705
			} else {
706
				catalogListingModel.setStockInHand(0);
707
			}
24231 amit.gupta 708
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
709
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
710
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
26179 tejbeer 711
			if (plannedDetailMap != null) {
26177 tejbeer 712
				if (plannedDetailMap.get(catalogId) != null) {
24231 amit.gupta 713
 
26177 tejbeer 714
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
715
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
716
					LOGGER.info("remaning" + remaining);
26176 tejbeer 717
 
26177 tejbeer 718
					if (remaining != 0) {
719
						catalogListingModel.setRemaining(remaining);
720
					} else {
721
						catalogListingModel.setRemaining(0);
722
					}
26176 tejbeer 723
				}
724
			}
23786 amit.gupta 725
		}
25721 tejbeer 726
 
26963 amit.gupta 727
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
23786 amit.gupta 728
		if (fofoId > 0) {
729
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
730
			model.addAttribute("retailerName",
731
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
732
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
733
			model.addAttribute("retailerId", customRetailer.getPartnerId());
734
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 735
		} else {
23786 amit.gupta 736
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 737
		}
23786 amit.gupta 738
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 739
 
740
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
741
 
25721 tejbeer 742
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 743
				Comparator.reverseOrder());
25721 tejbeer 744
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25796 tejbeer 745
		model.addAttribute("catalogTagListings",
746
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 747
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
26177 tejbeer 748
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26956 amit.gupta 749
		model.addAttribute("previousPlanningMonth", planningMonthDate.minusMonths(1).getMonth());
750
		model.addAttribute("currentPlanningMonth", planningMonthDate.getMonth());
26131 tejbeer 751
 
23786 amit.gupta 752
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 753
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 754
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 755
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 756
		return "open-indent";
25796 tejbeer 757
 
23405 amit.gupta 758
	}
23796 amit.gupta 759
 
26131 tejbeer 760
	@RequestMapping(value = "/indent/loadIndentPreviousMonth")
761
	public String previousMonthLoadOpenIndent(HttpServletRequest request, Model model,
762
			@RequestParam(required = false, defaultValue = "0") int fofoId,
763
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
26956 amit.gupta 764
		LocalDate planMonthStart = null;
765
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
766
			planMonthStart = LocalDate.now().plusMonths(1).withDayOfMonth(1);
767
		} else {
768
			planMonthStart = LocalDate.now().withDayOfMonth(1);
769
		}
26131 tejbeer 770
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
771
		Set<Integer> roleIds = loginDetails.getRoleIds();
772
		LOGGER.info("Counter size is {}", counterSize);
773
		LOGGER.info("Fofo Id is {}", fofoId);
774
		boolean isAdmin = roleManager.isAdmin(roleIds);
775
 
776
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
777
				.collect(Collectors.toList());
778
 
779
		Map<String, Object> equalsMap = new HashMap<>();
780
		equalsMap.put("categoryId", 10006);
781
		equalsMap.put("brand", brands);
782
		Map<String, List<?>> notEqualsMap = new HashMap<>();
783
 
784
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
785
		Map<Integer, Integer> currentStockMap;
786
 
787
		if (!isAdmin && fofoId == 0) {
788
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
789
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
790
			equalsStockJoinMap.put("fofoId", fofoId);
791
			currentStockMap = itemRepository
792
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
793
							equalsStockJoinMap, notEqualsJoinMap, "availability")
794
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
795
			LOGGER.info("currentStock");
796
		} else {
797
			if (fofoId == 0) {
798
 
799
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
800
				equalsStockJoinMap.put("fofoId", fofoId);
801
 
802
				currentStockMap = itemRepository
803
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
804
								equalsStockJoinMap, notEqualsJoinMap, "availability")
805
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
806
 
807
			} else {
808
 
809
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
810
				equalsStockJoinMap.put("fofoId", fofoId);
811
 
812
				currentStockMap = itemRepository
813
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
814
								equalsStockJoinMap, notEqualsJoinMap, "availability")
815
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
816
 
817
			}
818
		}
819
 
820
		LOGGER.info("currentStock" + currentStockMap);
821
 
822
		Map<Integer, Integer> itemsInTransit = null;
823
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
824
		if (!isAdmin) {
825
			tagListings = new ArrayList<>(tagListings);
826
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
827
			inTransitOrders = this.filterValidOrders(inTransitOrders);
828
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
829
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
830
		} else {
831
			itemsInTransit = new HashMap<>();
832
		}
833
 
834
		int totalPcs = 0;
835
 
836
		float totalAmount = 0;
837
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
838
 
27088 tejbeer 839
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
840
				.collect(Collectors.toList());
26131 tejbeer 841
 
27088 tejbeer 842
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
843
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
844
 
26978 tejbeer 845
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId,
846
				planMonthStart.minusMonths(1));
26956 amit.gupta 847
		model.addAttribute("planningMonth", planMonthStart.minusMonths(1).getMonth());
848
		model.addAttribute("previousPlanningMonth", planMonthStart.minusMonths(1).getMonth());
849
		model.addAttribute("currentPlanningMonth", planMonthStart.getMonth());
26131 tejbeer 850
 
851
		Map<Integer, Integer> plannedDetailMap = null;
852
		if (monthlyPlanned != null) {
853
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
854
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
855
 
856
		}
857
 
858
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
859
		List<Integer> fofoOrderIds = fofoOrderRepository
860
				.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
26978 tejbeer 861
						planMonthStart.minusMonths(1).atStartOfDay(), planMonthStart.atStartOfDay())
26131 tejbeer 862
				.stream().map(x -> x.getId()).collect(Collectors.toList());
26721 tejbeer 863
 
26131 tejbeer 864
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
865
		Map<String, Object> equalsJoinMap = new HashMap<>();
866
		equalsJoinMap.put("orderId", fofoOrderIds);
26721 tejbeer 867
		Map<Integer, Integer> lastMonthSaleMap = null;
868
		if (!fofoOrderIds.isEmpty()) {
869
			lastMonthSaleMap = itemRepository
870
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
871
							notEqualsJoinMap, "quantity")
872
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
873
		}
26131 tejbeer 874
		LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);
875
 
876
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
877
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
878
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
879
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
880
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
881
		LOGGER.info("catalogIdItemMap");
882
 
883
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
884
		equalsItemJoinMap.put("active", 1);
885
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
886
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
887
		LOGGER.info("tagListingCatalogIds");
888
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
889
			int catalogId = catalogIdAggregateValue.getCatalogId();
890
			Item item = catalogIdItemMap.get(catalogId).get(0);
891
			TagListing tagListing = taglistingMap.get(item.getId());
892
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
893
			if (!catalogListingMap.containsKey(catalogId)) {
894
				catalogListingModel = new CatalogListingModel();
895
				catalogListingModel.setCatalogId(catalogId);
896
				catalogListingModel.setDp(tagListing.getSellingPrice());
897
				catalogListingModel.setMop(tagListing.getMop());
898
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
899
				if (plannedDetailMap != null) {
900
 
901
					Integer quantity = plannedDetailMap.get(catalogId);
902
					if (quantity != null) {
903
						catalogListingModel.setAllocatedQuantity(quantity);
904
					}
905
				}
906
 
907
				if (lastMonthSaleMap != null) {
908
					Integer lastMonthSale = lastMonthSaleMap.get(catalogId);
909
 
910
					if (lastMonthSale != null) {
911
						catalogListingModel.setLastMonthSaleMap(lastMonthSale);
912
					} else {
913
						catalogListingModel.setLastMonthSaleMap(0);
914
					}
915
				} else {
916
					catalogListingModel.setLast15DaysSale(0);
917
				}
918
 
919
				catalogListingModel.setBrand(item.getBrand());
920
				if (item.getCategoryId() == 10006) {
921
					catalogListingModel.setCategoryId(item.getCategoryId());
922
				}
923
 
924
				FocusedModel fm = focusedModelMap.get(catalogId);
925
				if (fm != null) {
926
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
927
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
928
 
929
				} else {
930
					catalogListingModel.setRecommendedQty(0);
931
					catalogListingModel.setMinimumQty(0);
932
				}
933
 
934
				catalogListingMap.put(catalogId, catalogListingModel);
935
 
936
			}
937
			int itemAvailability = 0;
938
			if (currentStockMap != null) {
939
				Integer qty = currentStockMap.get(catalogId);
940
				itemAvailability = qty == null ? 0 : qty;
941
				catalogListingModel.setStockInHand(itemAvailability);
942
			} else {
943
				catalogListingModel.setStockInHand(0);
944
			}
945
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
946
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
947
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
948
 
949
		}
950
 
26963 amit.gupta 951
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26131 tejbeer 952
		if (fofoId > 0) {
953
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
954
			model.addAttribute("retailerName",
955
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
956
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
957
			model.addAttribute("retailerId", customRetailer.getPartnerId());
958
			model.addAttribute("counterSize", fs.getCounterSize().toString());
959
		} else {
960
			model.addAttribute("counterSize", counterSize.toString());
961
		}
962
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
963
 
964
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
965
 
966
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
967
				Comparator.reverseOrder());
968
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
969
		model.addAttribute("catalogTagListings",
970
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
971
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
972
		model.addAttribute("previousMonth", true);
973
		model.addAttribute("freezed", true);
26177 tejbeer 974
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26131 tejbeer 975
		model.addAttribute("customRetailers", customRetailers);
976
		model.addAttribute("totalAmount", totalAmount);
977
		model.addAttribute("monthlyPlanned", monthlyPlanned);
978
		model.addAttribute("totalPcs", totalPcs);
979
		return "open-indent";
980
 
981
	}
982
 
23796 amit.gupta 983
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
25812 amit.gupta 984
		int orderRemovedCount = 0;
23796 amit.gupta 985
		Iterator<Order> orderIterator = lastOrdersList.iterator();
986
		while (orderIterator.hasNext()) {
987
			Order o = orderIterator.next();
988
			if (o.getInvoiceNumber() != null) {
989
				try {
990
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
991
					orderIterator.remove();
25812 amit.gupta 992
					orderRemovedCount++;
23796 amit.gupta 993
				} catch (Exception e) {
994
 
995
				}
996
			}
997
		}
25812 amit.gupta 998
		LOGGER.info("Order removed count is {}", orderRemovedCount);
23796 amit.gupta 999
		return lastOrdersList;
1000
	}
1001
 
24406 amit.gupta 1002
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
24410 amit.gupta 1003
	public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
1004
			throws Exception {
24406 amit.gupta 1005
		JSONArray jsonArray = new JSONArray(jsonArrayString);
24410 amit.gupta 1006
		for (int i = 0; i < jsonArray.length(); i++) {
24406 amit.gupta 1007
			JSONObject obj = jsonArray.getJSONObject(i);
25378 tejbeer 1008
 
24406 amit.gupta 1009
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
25378 tejbeer 1010
			if (tl == null) {
1011
				continue;
1012
			} else {
1013
				tl.setActive(obj.getBoolean("active"));
1014
				tagListingRepository.persist(tl);
1015
			}
24406 amit.gupta 1016
		}
24410 amit.gupta 1017
		model.addAttribute("response", true);
23855 amit.gupta 1018
		return "response";
1019
	}
24231 amit.gupta 1020
 
1021
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
23796 amit.gupta 1022
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
1023
		boolean success = false;
1024
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1025
		int fofoId = loginDetails.getFofoId();
1026
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
1027
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
1028
		Client userClient = new UserClient().getClient();
24231 amit.gupta 1029
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
23796 amit.gupta 1030
 
24231 amit.gupta 1031
		if (totalAmount > 0) {
23796 amit.gupta 1032
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
1033
			User user = userRepository.selectById(loginDetails.getFofoId());
1034
			userClient = new UserClient().getClient();
1035
			LOGGER.info("Setting wallet amount in cart");
24231 amit.gupta 1036
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
1037
					7890, OrderSource.WEBSITE.getValue(), true);
23796 amit.gupta 1038
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
1039
			createPayment(user, totalAmount, transactionId);
24231 amit.gupta 1040
			TransactionService.Client transactionClient = new TransactionClient().getClient();
23796 amit.gupta 1041
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
24231 amit.gupta 1042
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 1043
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
24231 amit.gupta 1044
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 1045
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
1046
			transactionClient = new TransactionClient().getClient();
1047
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
1048
			try {
1049
				transactionClient.enqueueTransactionInfoEmail(transactionId);
1050
			} catch (Exception e1) {
1051
				e1.printStackTrace();
1052
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
1053
			}
1054
			resetCart(transactionClient.getTransaction(transactionId));
1055
		}
1056
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
1057
		return "response";
1058
	}
24231 amit.gupta 1059
 
1060
	private void createPayment(User user, double totalAmount, long transactionId)
1061
			throws NumberFormatException, PaymentException, TException {
23796 amit.gupta 1062
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
1063
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
1064
		paymentAttributes.add(new Attribute("payMethod", "7890"));
24231 amit.gupta 1065
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
1066
				false);
1067
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
1068
				PaymentStatus.SUCCESS, null, paymentAttributes);
23796 amit.gupta 1069
	}
24231 amit.gupta 1070
 
23796 amit.gupta 1071
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
1072
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
24231 amit.gupta 1073
		/*
1074
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
1075
		 * currentInventorySnapshots = currentInventorySnapshotRepository
1076
		 * .selectItemsStock(fofoId); itemCisMap =
1077
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
1078
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1079
		 * List<StockAllocationModel> stockAllocationList =
1080
		 * stockAllocationService.getStockAllocation(fofoId, true);
1081
		 * 
1082
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
1083
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
1084
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
1085
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
1086
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
1087
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
1088
		 * validOrderStatusList); inTransitOrders =
1089
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
1090
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
1091
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
1092
		 * x.getLineItem().getQuantity())));
1093
		 * 
1094
		 * Iterator<TagListing> iterator = tagListings.iterator();
1095
		 * 
1096
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
1097
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
1098
		 * tagListing.getAllocatedQuantity()); if
1099
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
1100
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
1101
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
1102
		 * itemCisMap.get(tagListing.getItemId());
1103
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
1104
		 * itemIdAvailability.getAvailability()); StockAllocationModel
1105
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
1106
		 * 
1107
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
1108
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
1109
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
1110
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
1111
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
1112
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
1113
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
1114
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
1115
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
1116
		 */
23796 amit.gupta 1117
		return itemQuantities;
1118
 
1119
	}
24231 amit.gupta 1120
 
23796 amit.gupta 1121
	private long resetCart(Transaction transaction) {
1122
		long sum = 0;
1123
		Map<Long, Double> items = new HashMap<Long, Double>();
1124
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
1125
			sum += order.getGvAmount();
1126
			for (LineItem lineitem : order.getLineitems()) {
1127
				Long itemId = lineitem.getItem_id();
1128
				Double quantity = items.get(itemId);
1129
				if (quantity == null) {
1130
					quantity = lineitem.getQuantity();
1131
				} else {
1132
					quantity = quantity + lineitem.getQuantity();
1133
				}
1134
				items.put(itemId, quantity);
1135
			}
1136
		}
1137
 
1138
		LOGGER.debug("Items to reset in cart are: " + items);
1139
 
1140
		try {
1141
			Client userClient = new UserClient().getClient();
1142
			userClient.resetCart(transaction.getShoppingCartid(), items);
1143
		} catch (TException e) {
1144
			LOGGER.error("Error while updating information in payment database.", e);
1145
		} catch (ShoppingCartException e) {
1146
			LOGGER.error("Error while reseting the cart in cart database.", e);
1147
		} catch (Exception e) {
1148
			LOGGER.error("Unexpected exception", e);
1149
		}
1150
		return sum;
1151
	}
1152
 
25721 tejbeer 1153
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
1154
	public String getFocusedModel(HttpServletRequest request,
1155
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1156
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1157
			throws ProfitMandiBusinessException {
25736 tejbeer 1158
 
1159
		long size = 0;
25721 tejbeer 1160
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
27081 tejbeer 1161
 
25736 tejbeer 1162
		size = focusedModelRepository.selectAllCount();
1163
		if (!focusedModels.isEmpty()) {
1164
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
27088 tejbeer 1165
			Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25721 tejbeer 1166
 
27088 tejbeer 1167
			LOGGER.info("regionMap" + regionMap);
25736 tejbeer 1168
			model.addAttribute("focusedModels", focusedModels);
1169
			model.addAttribute("itemMap", itemMap);
27088 tejbeer 1170
			model.addAttribute("regionMap", regionMap);
25736 tejbeer 1171
			model.addAttribute("start", offset + 1);
1172
			model.addAttribute("size", size);
1173
			model.addAttribute("url", "/getPaginatedFocusedModel");
1174
 
1175
			if (focusedModels.size() < limit) {
1176
				model.addAttribute("end", offset + focusedModels.size());
1177
			} else {
1178
				model.addAttribute("end", offset + limit);
1179
			}
1180
		} else {
1181
 
1182
			model.addAttribute("walletRequest", focusedModels);
1183
			model.addAttribute("size", size);
1184
 
1185
		}
1186
 
27088 tejbeer 1187
		List<Region> regions = regionRepository.selectAll();
27081 tejbeer 1188
 
27088 tejbeer 1189
		model.addAttribute("regions", regions);
1190
 
25721 tejbeer 1191
		return "focused_model";
1192
	}
1193
 
25736 tejbeer 1194
	@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
1195
	public String getPaginatedFocusedModel(HttpServletRequest request,
1196
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1197
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1198
			throws ProfitMandiBusinessException {
1199
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
1200
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
1201
 
1202
		if (!focusedModels.isEmpty()) {
1203
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
27088 tejbeer 1204
			Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25736 tejbeer 1205
			model.addAttribute("focusedModels", focusedModels);
1206
			model.addAttribute("itemMap", itemMap);
27088 tejbeer 1207
			model.addAttribute("regionMap", regionMap);
25736 tejbeer 1208
			model.addAttribute("url", "/getPaginatedFocusedModel");
1209
		} else {
1210
			model.addAttribute("focusedModels", focusedModels);
1211
 
1212
		}
27081 tejbeer 1213
 
27088 tejbeer 1214
		List<Region> regions = regionRepository.selectAll();
1215
 
1216
		model.addAttribute("regions", regions);
25736 tejbeer 1217
		return "focused-model-paginated";
1218
	}
1219
 
25721 tejbeer 1220
	private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
1221
		Map<Integer, Item> itemMap = new HashMap<>();
1222
		for (FocusedModel focusedModel : focusedModels) {
1223
			List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
1224
			itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
1225
		}
1226
 
1227
		return itemMap;
1228
	}
1229
 
27088 tejbeer 1230
	private Map<Integer, Region> getRegionByRegionId(List<FocusedModel> focusedModels) {
1231
		Map<Integer, Region> regionMap = new HashMap<>();
1232
		for (FocusedModel focusedModel : focusedModels) {
1233
			Region region = regionRepository.selectById(focusedModel.getRegionId());
1234
			regionMap.put(region.getId(), region);
1235
		}
1236
 
1237
		return regionMap;
1238
	}
1239
 
25721 tejbeer 1240
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
1241
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int recommended,
27088 tejbeer 1242
			@RequestParam int minimumQty, @RequestParam int regionId, Model model) throws ProfitMandiBusinessException {
25721 tejbeer 1243
 
1244
		FocusedModel fm = new FocusedModel();
1245
		fm.setCatalogId(catalogId);
1246
		fm.setMinimumQty(minimumQty);
1247
		fm.setRecommendedQty(recommended);
27088 tejbeer 1248
		fm.setRegionId(regionId);
25721 tejbeer 1249
		fm.setCreatedTimestamp(LocalDateTime.now());
1250
		focusedModelRepository.persist(fm);
1251
		return "focused_model";
1252
	}
1253
 
1254
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
1255
	public String removeFocusedModelItem(HttpServletRequest request,
27081 tejbeer 1256
			@RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
25721 tejbeer 1257
 
27081 tejbeer 1258
		focusedModelRepository.deleteById(id);
25721 tejbeer 1259
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1260
		return "response";
1261
	}
25736 tejbeer 1262
 
25798 tejbeer 1263
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
1264
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 1265
 
25798 tejbeer 1266
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
1267
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
1268
 
1269
		mobileBrands.stream().forEach(x -> {
1270
			String brand = (String) x.get("name");
1271
			if (brandStockPricesMap.containsKey(brand)) {
1272
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
1273
				brandStockPrice.setBrandUrl((String) x.get("url"));
1274
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
1275
				brandStockPrices.add(brandStockPrice);
1276
			}
1277
		});
1278
 
1279
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
1280
				.collect(Collectors.toList());
1281
	}
1282
 
26721 tejbeer 1283
	@RequestMapping(value = "/getPartnerAllocation")
1284
	public String getPartnerAllocation(HttpServletRequest request, Model model) throws Exception {
1285
 
1286
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1287
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1288
 
1289
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1290
 
1291
		List<Integer> fofoIds = pp.get(authUser.getId());
1292
 
1293
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
1294
		Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
1295
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1296
 
1297
		model.addAttribute("customRetailersMap", customRetailersMap);
1298
		model.addAttribute("fofoStoreMap", fofoStoreMap);
1299
		return "partners_allocation";
1300
 
1301
	}
1302
 
26846 tejbeer 1303
	@RequestMapping(value = "/partnerPendingOrder")
1304
	public String partnerPendingOrder(HttpServletRequest request, Model model) throws Exception {
1305
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1306
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1307
 
1308
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1309
 
1310
		List<Integer> fofoIds = pp.get(authUser.getId());
1311
 
1312
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
1313
 
1314
		model.addAttribute("customRetailersMap", customRetailersMap);
1315
 
1316
		return "partner-po";
1317
 
1318
	}
1319
 
1320
	@RequestMapping(value = "/getPartnerloadContent")
1321
	public String getPartnerloadContent(HttpServletRequest request, Model model,
1322
			@RequestParam(required = false, defaultValue = "0") int fofoId,
1323
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
1324
 
1325
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1326
		Set<Integer> roleIds = loginDetails.getRoleIds();
1327
		LOGGER.info("Counter size is {}", counterSize);
1328
		LOGGER.info("Fofo Id is {}", fofoId);
1329
		boolean isAdmin = roleManager.isAdmin(roleIds);
1330
 
1331
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1332
				.collect(Collectors.toList());
1333
 
1334
		Map<String, Object> equalsMap = new HashMap<>();
1335
		equalsMap.put("categoryId", 10006);
1336
		equalsMap.put("brand", brands);
1337
		Map<String, List<?>> notEqualsMap = new HashMap<>();
1338
 
1339
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1340
		Map<Integer, Integer> currentStockMap;
1341
 
1342
		if (!isAdmin && fofoId == 0) {
1343
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1344
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
1345
			equalsStockJoinMap.put("fofoId", fofoId);
1346
			currentStockMap = itemRepository
1347
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1348
							equalsStockJoinMap, notEqualsJoinMap, "availability")
1349
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1350
			LOGGER.info("currentStock");
1351
		} else {
1352
			if (fofoId == 0) {
1353
 
1354
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1355
				equalsStockJoinMap.put("fofoId", fofoId);
1356
 
1357
				currentStockMap = itemRepository
1358
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1359
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1360
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1361
 
1362
			} else {
1363
 
1364
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1365
				equalsStockJoinMap.put("fofoId", fofoId);
1366
 
1367
				currentStockMap = itemRepository
1368
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1369
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1370
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1371
 
1372
			}
1373
		}
1374
 
27768 tejbeer 1375
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
26846 tejbeer 1376
		LOGGER.info("currentStock" + currentStockMap);
1377
 
1378
		Map<Integer, Integer> itemsInTransit = null;
1379
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
1380
		if (!isAdmin) {
1381
			tagListings = new ArrayList<>(tagListings);
1382
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
1383
			inTransitOrders = this.filterValidOrders(inTransitOrders);
1384
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1385
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1386
		} else {
1387
			itemsInTransit = new HashMap<>();
1388
		}
1389
 
1390
		int totalPcs = 0;
1391
 
1392
		float totalAmount = 0;
1393
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
1394
 
27088 tejbeer 1395
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1396
				.collect(Collectors.toList());
26846 tejbeer 1397
 
27088 tejbeer 1398
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
1399
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
1400
 
26846 tejbeer 1401
		LocalDate currentMonthDate = LocalDate.now();
1402
		MonthlyPlanned monthlyPlanned = null;
1403
		List<Integer> fofoOrderIds = null;
1404
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 1405
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26846 tejbeer 1406
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
1407
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1408
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
1409
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1410
					LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
1411
					.collect(Collectors.toList());
1412
 
1413
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 1414
		} else {
26846 tejbeer 1415
			currentMonthDate = LocalDate.now().withDayOfMonth(1);
1416
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
1417
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1418
			model.addAttribute("planningMonth", currentMonthDate.getMonth());
1419
			model.addAttribute("mtd", true);
1420
			model.addAttribute("freezed", true);
1421
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1422
					curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
1423
					.collect(Collectors.toList());
1424
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
1425
		}
1426
 
1427
		Map<Integer, Integer> plannedDetailMap = null;
1428
		if (monthlyPlanned != null) {
1429
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1430
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
1431
 
1432
		}
1433
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
1434
 
1435
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
1436
		Map<String, Object> equalsJoinMap = new HashMap<>();
1437
 
1438
		equalsJoinMap.put("orderId", fofoOrderIds);
1439
		Map<Integer, Integer> last15daysMap = null;
1440
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
1441
 
1442
			last15daysMap = itemRepository
1443
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1444
							notEqualsJoinMap, "quantity")
1445
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1446
		}
1447
		LOGGER.info("last15daysMap" + last15daysMap);
1448
 
1449
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
1450
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1451
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1452
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1453
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1454
		LOGGER.info("catalogIdItemMap");
1455
 
1456
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
1457
		equalsItemJoinMap.put("active", 1);
1458
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
1459
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
27768 tejbeer 1460
		Map<Integer, Integer> ourStockAvailability = new HashMap<>();
1461
		Map<Integer, List<SaholicCIS>> itemAvailabilityMap = saholicInventoryService.getSaholicStock()
1462
				.get(fofoStore.getWarehouseId());
1463
 
1464
		Map<Integer, List<Integer>> catalogItemIdMap = itemRepository
1465
				.selectAllByCatalogIds(new HashSet<>(
1466
						tagListingCatalogIds.stream().map(x -> x.getCatalogId()).collect(Collectors.toList())))
1467
				.stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1468
						Collectors.mapping(y -> y.getId(), Collectors.toList())));
1469
		for (Entry<Integer, List<Integer>> catalogItem : catalogItemIdMap.entrySet()) {
1470
			List<Integer> itemIds = catalogItem.getValue();
1471
			int availability = 0;
1472
			for (Integer itemId : itemIds) {
1473
				List<SaholicCIS> scis = itemAvailabilityMap.get(itemId);
1474
				if (scis != null) {
1475
					availability += scis.stream().collect(Collectors.summingInt(x -> x.getAvailability()));
1476
				}
1477
			}
1478
			Integer catalogItemId = catalogItem.getKey();
1479
			ourStockAvailability.put(catalogItemId, availability);
1480
		}
1481
		LOGGER.info("ourStockAvailability" + ourStockAvailability);
1482
 
26846 tejbeer 1483
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
1484
			int catalogId = catalogIdAggregateValue.getCatalogId();
1485
			Item item = catalogIdItemMap.get(catalogId).get(0);
1486
			TagListing tagListing = taglistingMap.get(item.getId());
1487
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1488
			if (!catalogListingMap.containsKey(catalogId)) {
1489
				catalogListingModel = new CatalogListingModel();
1490
				catalogListingModel.setCatalogId(catalogId);
1491
				catalogListingModel.setDp(tagListing.getSellingPrice());
1492
				catalogListingModel.setMop(tagListing.getMop());
1493
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1494
				if (plannedDetailMap != null) {
1495
 
1496
					Integer quantity = plannedDetailMap.get(catalogId);
1497
					if (quantity != null) {
1498
						catalogListingModel.setAllocatedQuantity(quantity);
1499
					}
1500
				}
1501
 
1502
				if (last15daysMap != null) {
1503
					Integer last15DaysSale = last15daysMap.get(catalogId);
1504
 
1505
					if (last15DaysSale != null) {
1506
						catalogListingModel.setLast15DaysSale(last15DaysSale);
1507
					} else {
1508
						catalogListingModel.setLast15DaysSale(0);
1509
					}
1510
				} else {
1511
					catalogListingModel.setLast15DaysSale(0);
1512
				}
1513
 
1514
				catalogListingModel.setBrand(item.getBrand());
1515
				if (item.getCategoryId() == 10006) {
1516
					catalogListingModel.setCategoryId(item.getCategoryId());
1517
				}
1518
 
27768 tejbeer 1519
				Integer ourStock = ourStockAvailability.get(catalogId);
1520
				LOGGER.info("catalogId" + catalogId);
1521
 
1522
				LOGGER.info("ourStock" + ourStock);
1523
				if (ourStock != null) {
1524
					catalogListingModel.setOurStockQty(ourStock);
1525
				}
1526
 
26846 tejbeer 1527
				FocusedModel fm = focusedModelMap.get(catalogId);
1528
				if (fm != null) {
1529
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1530
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
1531
 
1532
				} else {
1533
					catalogListingModel.setRecommendedQty(0);
1534
					catalogListingModel.setMinimumQty(0);
1535
				}
1536
 
1537
				catalogListingMap.put(catalogId, catalogListingModel);
1538
 
1539
			}
1540
			int itemAvailability = 0;
1541
			if (currentStockMap != null) {
1542
				Integer qty = currentStockMap.get(catalogId);
1543
				itemAvailability = qty == null ? 0 : qty;
1544
				catalogListingModel.setStockInHand(itemAvailability);
1545
			} else {
1546
				catalogListingModel.setStockInHand(0);
1547
			}
1548
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
1549
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1550
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
1551
			if (plannedDetailMap != null) {
1552
				if (plannedDetailMap.get(catalogId) != null) {
1553
 
1554
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
1555
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
1556
					LOGGER.info("remaning" + remaining);
1557
 
1558
					if (remaining != 0) {
1559
						catalogListingModel.setRemaining(remaining);
1560
					} else {
1561
						catalogListingModel.setRemaining(0);
1562
					}
1563
				}
1564
			}
1565
		}
1566
 
26963 amit.gupta 1567
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26846 tejbeer 1568
		if (fofoId > 0) {
1569
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1570
			model.addAttribute("retailerName",
1571
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1572
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1573
			model.addAttribute("retailerId", customRetailer.getPartnerId());
1574
			model.addAttribute("counterSize", fs.getCounterSize().toString());
1575
		} else {
1576
			model.addAttribute("counterSize", counterSize.toString());
1577
		}
1578
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
1579
 
1580
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
1581
 
1582
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1583
				Comparator.reverseOrder());
1584
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
1585
		model.addAttribute("catalogTagListings",
1586
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1587
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
27768 tejbeer 1588
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
26846 tejbeer 1589
		model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
1590
		model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());
1591
 
1592
		model.addAttribute("customRetailers", customRetailers);
1593
		model.addAttribute("totalAmount", totalAmount);
1594
		model.addAttribute("monthlyPlanned", monthlyPlanned);
1595
		model.addAttribute("totalPcs", totalPcs);
1596
 
1597
		UserWallet userWallet = walletService.getUserWallet(fofoId);
1598
 
1599
		model.addAttribute("userWallet", userWallet);
1600
 
1601
		return "create-partner-po";
1602
 
1603
	}
1604
 
1605
	@RequestMapping(value = "/createPo", method = RequestMethod.POST)
1606
	public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)
1607
			throws Exception {
1608
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1609
		SuggestedPo mp = new SuggestedPo();
1610
		mp.setFofoId(monthlyPoModel.getFofoId());
1611
		mp.setCreateTimestamp(LocalDateTime.now());
1612
		mp.setStatus("open");
1613
		mp.setAuthId(loginDetails.getEmailId());
1614
		monthlyPoRepository.persist(mp);
1615
 
1616
		for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {
1617
			SuggestedPoDetail mpd = new SuggestedPoDetail();
1618
			mpd.setItemId(poId.getItemId());
1619
			mpd.setQuantity(poId.getQty());
1620
			mpd.setUpdatedTimestamp(LocalDateTime.now());
1621
			mpd.setPoId(mp.getId());
1622
			monthlyPoDetailRepository.persist(mpd);
1623
		}
1624
 
1625
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
1626
		sendNotificationModel.setCampaignName("Alert");
1627
		sendNotificationModel.setMessage("Suggested Po");
1628
		sendNotificationModel.setType("url");
1629
		sendNotificationModel.setTitle("Alert");
26951 amit.gupta 1630
		sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
26846 tejbeer 1631
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1632
		sendNotificationModel.setMessageType(MessageType.notification);
1633
		int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());
1634
 
1635
		sendNotificationModel.setUserIds(Arrays.asList(userId));
1636
		notificationService.sendNotification(sendNotificationModel);
1637
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1638
 
1639
		return "response";
1640
	}
1641
 
1642
	@RequestMapping(value = "/selectItemColor", method = RequestMethod.GET)
1643
	public String selectItemColor(HttpServletRequest request, @RequestParam int catalogId, Model model)
1644
			throws Exception {
1645
 
1646
		List<Item> selecteditems = itemRepository.selectAllByCatalogItemId(catalogId);
1647
 
1648
		List<Item> items = new ArrayList<>();
1649
		for (Item item : selecteditems) {
1650
 
1651
			TagListing tagListing = tagListingRepository.selectByItemId(item.getId(), true);
1652
 
1653
			if (tagListing != null) {
1654
				items.add(item);
1655
			}
1656
 
1657
		}
1658
		model.addAttribute("items", items);
1659
		LOGGER.info("itemIdAndColorMap" + items);
1660
		return "select-item-color";
1661
	}
1662
 
25721 tejbeer 1663
}