Subversion Repositories SmartDukaan

Rev

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