Subversion Repositories SmartDukaan

Rev

Rev 28055 | Rev 29667 | 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;
28897 amit.gupta 47
import com.spice.profitmandi.common.model.IntegerIdAggregateValue;
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
 
28055 tejbeer 506
	@RequestMapping(value = "/hotdealsitemsByCatalogId")
507
	public String getHotdealsitemsByCatalogId(HttpServletRequest request, Model model,
508
			@RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
509
			throws ProfitMandiBusinessException {
510
		if (catalogId == 0) {
511
			catalogId = itemRepository.selectById(itemId).getCatalogItemId();
512
		}
513
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
514
		LOGGER.info("Items {}", items);
515
		Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
516
				.collect(Collectors.toMap(Item::getId, Item::getColor));
517
		Map<Integer, TagListing> tagsMap = tagListingRepository
518
				.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
519
				.stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
520
		LOGGER.info("Items color map {}", itemsColorMap);
521
		JSONArray response = new JSONArray();
522
		itemsColorMap.keySet().stream().forEach(x -> {
523
			response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("hotDeals",
524
					tagsMap.get(x) == null ? false : tagsMap.get(x).isHotDeals()));
525
		});
526
		model.addAttribute("response", response.toString());
527
		return "response";
528
 
529
	}
530
 
23405 amit.gupta 531
	@RequestMapping(value = "/indent/loadIndent")
23785 amit.gupta 532
	public String loadOpenIndent(HttpServletRequest request, Model model,
533
			@RequestParam(required = false, defaultValue = "0") int fofoId,
25736 tejbeer 534
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 535
 
536
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
537
		Set<Integer> roleIds = loginDetails.getRoleIds();
23785 amit.gupta 538
		LOGGER.info("Counter size is {}", counterSize);
539
		LOGGER.info("Fofo Id is {}", fofoId);
25736 tejbeer 540
		boolean isAdmin = roleManager.isAdmin(roleIds);
25796 tejbeer 541
 
25797 tejbeer 542
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
543
				.collect(Collectors.toList());
544
 
25796 tejbeer 545
		Map<String, Object> equalsMap = new HashMap<>();
546
		equalsMap.put("categoryId", 10006);
25797 tejbeer 547
		equalsMap.put("brand", brands);
25796 tejbeer 548
		Map<String, List<?>> notEqualsMap = new HashMap<>();
549
 
550
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
551
		Map<Integer, Integer> currentStockMap;
552
 
25721 tejbeer 553
		if (!isAdmin && fofoId == 0) {
23786 amit.gupta 554
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
25796 tejbeer 555
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
556
			equalsStockJoinMap.put("fofoId", fofoId);
557
			currentStockMap = itemRepository
25800 tejbeer 558
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
559
							equalsStockJoinMap, notEqualsJoinMap, "availability")
25796 tejbeer 560
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25797 tejbeer 561
			LOGGER.info("currentStock");
23786 amit.gupta 562
		} else {
563
			if (fofoId == 0) {
25796 tejbeer 564
 
565
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
566
				equalsStockJoinMap.put("fofoId", fofoId);
567
 
568
				currentStockMap = itemRepository
25800 tejbeer 569
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 570
								equalsStockJoinMap, notEqualsJoinMap, "availability")
571
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
572
 
23779 amit.gupta 573
			} else {
25796 tejbeer 574
 
575
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
576
				equalsStockJoinMap.put("fofoId", fofoId);
577
 
578
				currentStockMap = itemRepository
25800 tejbeer 579
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 580
								equalsStockJoinMap, notEqualsJoinMap, "availability")
581
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
582
 
23405 amit.gupta 583
			}
23786 amit.gupta 584
		}
25796 tejbeer 585
 
586
		LOGGER.info("currentStock" + currentStockMap);
25797 tejbeer 587
 
23796 amit.gupta 588
		Map<Integer, Integer> itemsInTransit = null;
23855 amit.gupta 589
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
25702 amit.gupta 590
		if (!isAdmin) {
23786 amit.gupta 591
			tagListings = new ArrayList<>(tagListings);
28055 tejbeer 592
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
593
					OrderRepository.validOrderStatusList);
23796 amit.gupta 594
			inTransitOrders = this.filterValidOrders(inTransitOrders);
595
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
596
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
597
		} else {
598
			itemsInTransit = new HashMap<>();
23786 amit.gupta 599
		}
25797 tejbeer 600
 
23796 amit.gupta 601
		int totalPcs = 0;
25797 tejbeer 602
 
23796 amit.gupta 603
		float totalAmount = 0;
24231 amit.gupta 604
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
27088 tejbeer 605
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
606
				.collect(Collectors.toList());
25796 tejbeer 607
 
27088 tejbeer 608
		LOGGER.info("regionIds" + regionIds);
609
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
610
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
611
		LOGGER.info("focusedModelMap" + focusedModelMap);
26956 amit.gupta 612
		LocalDate planningMonthDate = null;
26082 tejbeer 613
		MonthlyPlanned monthlyPlanned = null;
26176 tejbeer 614
		List<Integer> fofoOrderIds = null;
26082 tejbeer 615
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 616
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26956 amit.gupta 617
			planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
618
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
26082 tejbeer 619
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
26176 tejbeer 620
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
621
					LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
622
					.collect(Collectors.toList());
26082 tejbeer 623
 
624
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 625
		} else {
26956 amit.gupta 626
			planningMonthDate = LocalDate.now().withDayOfMonth(1);
26176 tejbeer 627
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
26956 amit.gupta 628
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
629
			model.addAttribute("planningMonth", planningMonthDate.getMonth());
26176 tejbeer 630
			model.addAttribute("mtd", true);
26131 tejbeer 631
			model.addAttribute("freezed", true);
26176 tejbeer 632
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
633
					curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
634
					.collect(Collectors.toList());
26082 tejbeer 635
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
26978 tejbeer 636
		}
26082 tejbeer 637
 
25721 tejbeer 638
		Map<Integer, Integer> plannedDetailMap = null;
639
		if (monthlyPlanned != null) {
640
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
641
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
642
 
643
		}
25797 tejbeer 644
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
26176 tejbeer 645
 
25796 tejbeer 646
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
647
		Map<String, Object> equalsJoinMap = new HashMap<>();
26618 tejbeer 648
 
25796 tejbeer 649
		equalsJoinMap.put("orderId", fofoOrderIds);
26618 tejbeer 650
		Map<Integer, Integer> last15daysMap = null;
26748 tejbeer 651
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
24231 amit.gupta 652
 
26618 tejbeer 653
			last15daysMap = itemRepository
654
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
655
							notEqualsJoinMap, "quantity")
656
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
657
		}
25796 tejbeer 658
		LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 659
 
25796 tejbeer 660
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
661
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
662
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
663
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
664
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
25797 tejbeer 665
		LOGGER.info("catalogIdItemMap");
24231 amit.gupta 666
 
25796 tejbeer 667
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
25797 tejbeer 668
		equalsItemJoinMap.put("active", 1);
28897 amit.gupta 669
		List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
25800 tejbeer 670
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
25797 tejbeer 671
		LOGGER.info("tagListingCatalogIds");
28897 amit.gupta 672
		for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
25796 tejbeer 673
			int catalogId = catalogIdAggregateValue.getCatalogId();
674
			Item item = catalogIdItemMap.get(catalogId).get(0);
675
			TagListing tagListing = taglistingMap.get(item.getId());
24231 amit.gupta 676
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
677
			if (!catalogListingMap.containsKey(catalogId)) {
678
				catalogListingModel = new CatalogListingModel();
679
				catalogListingModel.setCatalogId(catalogId);
680
				catalogListingModel.setDp(tagListing.getSellingPrice());
681
				catalogListingModel.setMop(tagListing.getMop());
682
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
25721 tejbeer 683
				if (plannedDetailMap != null) {
684
 
685
					Integer quantity = plannedDetailMap.get(catalogId);
686
					if (quantity != null) {
687
						catalogListingModel.setAllocatedQuantity(quantity);
688
					}
689
				}
690
 
25796 tejbeer 691
				if (last15daysMap != null) {
692
					Integer last15DaysSale = last15daysMap.get(catalogId);
693
 
25721 tejbeer 694
					if (last15DaysSale != null) {
695
						catalogListingModel.setLast15DaysSale(last15DaysSale);
696
					} else {
697
						catalogListingModel.setLast15DaysSale(0);
698
					}
699
				} else {
700
					catalogListingModel.setLast15DaysSale(0);
701
				}
702
 
24231 amit.gupta 703
				catalogListingModel.setBrand(item.getBrand());
704
				if (item.getCategoryId() == 10006) {
705
					catalogListingModel.setCategoryId(item.getCategoryId());
706
				}
25721 tejbeer 707
 
708
				FocusedModel fm = focusedModelMap.get(catalogId);
709
				if (fm != null) {
710
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
711
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
712
 
713
				} else {
714
					catalogListingModel.setRecommendedQty(0);
715
					catalogListingModel.setMinimumQty(0);
716
				}
717
 
24231 amit.gupta 718
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 719
 
24231 amit.gupta 720
			}
25736 tejbeer 721
			int itemAvailability = 0;
25796 tejbeer 722
			if (currentStockMap != null) {
723
				Integer qty = currentStockMap.get(catalogId);
25736 tejbeer 724
				itemAvailability = qty == null ? 0 : qty;
725
				catalogListingModel.setStockInHand(itemAvailability);
726
			} else {
727
				catalogListingModel.setStockInHand(0);
728
			}
24231 amit.gupta 729
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
730
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
731
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
26179 tejbeer 732
			if (plannedDetailMap != null) {
26177 tejbeer 733
				if (plannedDetailMap.get(catalogId) != null) {
24231 amit.gupta 734
 
26177 tejbeer 735
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
736
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
737
					LOGGER.info("remaning" + remaining);
26176 tejbeer 738
 
26177 tejbeer 739
					if (remaining != 0) {
740
						catalogListingModel.setRemaining(remaining);
741
					} else {
742
						catalogListingModel.setRemaining(0);
743
					}
26176 tejbeer 744
				}
745
			}
23786 amit.gupta 746
		}
25721 tejbeer 747
 
26963 amit.gupta 748
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
23786 amit.gupta 749
		if (fofoId > 0) {
750
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
751
			model.addAttribute("retailerName",
752
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
753
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
754
			model.addAttribute("retailerId", customRetailer.getPartnerId());
755
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 756
		} else {
23786 amit.gupta 757
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 758
		}
23786 amit.gupta 759
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 760
 
761
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
762
 
25721 tejbeer 763
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 764
				Comparator.reverseOrder());
25721 tejbeer 765
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25796 tejbeer 766
		model.addAttribute("catalogTagListings",
767
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 768
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
26177 tejbeer 769
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26956 amit.gupta 770
		model.addAttribute("previousPlanningMonth", planningMonthDate.minusMonths(1).getMonth());
771
		model.addAttribute("currentPlanningMonth", planningMonthDate.getMonth());
26131 tejbeer 772
 
23786 amit.gupta 773
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 774
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 775
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 776
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 777
		return "open-indent";
25796 tejbeer 778
 
23405 amit.gupta 779
	}
23796 amit.gupta 780
 
26131 tejbeer 781
	@RequestMapping(value = "/indent/loadIndentPreviousMonth")
782
	public String previousMonthLoadOpenIndent(HttpServletRequest request, Model model,
783
			@RequestParam(required = false, defaultValue = "0") int fofoId,
784
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
26956 amit.gupta 785
		LocalDate planMonthStart = null;
786
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
787
			planMonthStart = LocalDate.now().plusMonths(1).withDayOfMonth(1);
788
		} else {
789
			planMonthStart = LocalDate.now().withDayOfMonth(1);
790
		}
26131 tejbeer 791
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
792
		Set<Integer> roleIds = loginDetails.getRoleIds();
793
		LOGGER.info("Counter size is {}", counterSize);
794
		LOGGER.info("Fofo Id is {}", fofoId);
795
		boolean isAdmin = roleManager.isAdmin(roleIds);
796
 
797
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
798
				.collect(Collectors.toList());
799
 
800
		Map<String, Object> equalsMap = new HashMap<>();
801
		equalsMap.put("categoryId", 10006);
802
		equalsMap.put("brand", brands);
803
		Map<String, List<?>> notEqualsMap = new HashMap<>();
804
 
805
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
806
		Map<Integer, Integer> currentStockMap;
807
 
808
		if (!isAdmin && fofoId == 0) {
809
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
810
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
811
			equalsStockJoinMap.put("fofoId", fofoId);
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
			LOGGER.info("currentStock");
817
		} else {
818
			if (fofoId == 0) {
819
 
820
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
821
				equalsStockJoinMap.put("fofoId", fofoId);
822
 
823
				currentStockMap = itemRepository
824
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
825
								equalsStockJoinMap, notEqualsJoinMap, "availability")
826
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
827
 
828
			} else {
829
 
830
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
831
				equalsStockJoinMap.put("fofoId", fofoId);
832
 
833
				currentStockMap = itemRepository
834
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
835
								equalsStockJoinMap, notEqualsJoinMap, "availability")
836
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
837
 
838
			}
839
		}
840
 
841
		LOGGER.info("currentStock" + currentStockMap);
842
 
843
		Map<Integer, Integer> itemsInTransit = null;
844
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
845
		if (!isAdmin) {
846
			tagListings = new ArrayList<>(tagListings);
28055 tejbeer 847
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
848
					OrderRepository.validOrderStatusList);
26131 tejbeer 849
			inTransitOrders = this.filterValidOrders(inTransitOrders);
850
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
851
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
852
		} else {
853
			itemsInTransit = new HashMap<>();
854
		}
855
 
856
		int totalPcs = 0;
857
 
858
		float totalAmount = 0;
859
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
860
 
27088 tejbeer 861
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
862
				.collect(Collectors.toList());
26131 tejbeer 863
 
27088 tejbeer 864
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
865
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
866
 
26978 tejbeer 867
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId,
868
				planMonthStart.minusMonths(1));
26956 amit.gupta 869
		model.addAttribute("planningMonth", planMonthStart.minusMonths(1).getMonth());
870
		model.addAttribute("previousPlanningMonth", planMonthStart.minusMonths(1).getMonth());
871
		model.addAttribute("currentPlanningMonth", planMonthStart.getMonth());
26131 tejbeer 872
 
873
		Map<Integer, Integer> plannedDetailMap = null;
874
		if (monthlyPlanned != null) {
875
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
876
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
877
 
878
		}
879
 
880
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
881
		List<Integer> fofoOrderIds = fofoOrderRepository
882
				.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
26978 tejbeer 883
						planMonthStart.minusMonths(1).atStartOfDay(), planMonthStart.atStartOfDay())
26131 tejbeer 884
				.stream().map(x -> x.getId()).collect(Collectors.toList());
26721 tejbeer 885
 
26131 tejbeer 886
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
887
		Map<String, Object> equalsJoinMap = new HashMap<>();
888
		equalsJoinMap.put("orderId", fofoOrderIds);
26721 tejbeer 889
		Map<Integer, Integer> lastMonthSaleMap = null;
890
		if (!fofoOrderIds.isEmpty()) {
891
			lastMonthSaleMap = itemRepository
892
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
893
							notEqualsJoinMap, "quantity")
894
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
895
		}
26131 tejbeer 896
		LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);
897
 
898
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
899
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
900
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
901
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
902
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
903
		LOGGER.info("catalogIdItemMap");
904
 
905
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
906
		equalsItemJoinMap.put("active", 1);
28897 amit.gupta 907
		List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
26131 tejbeer 908
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
909
		LOGGER.info("tagListingCatalogIds");
28897 amit.gupta 910
		for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
26131 tejbeer 911
			int catalogId = catalogIdAggregateValue.getCatalogId();
912
			Item item = catalogIdItemMap.get(catalogId).get(0);
913
			TagListing tagListing = taglistingMap.get(item.getId());
914
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
915
			if (!catalogListingMap.containsKey(catalogId)) {
916
				catalogListingModel = new CatalogListingModel();
917
				catalogListingModel.setCatalogId(catalogId);
918
				catalogListingModel.setDp(tagListing.getSellingPrice());
919
				catalogListingModel.setMop(tagListing.getMop());
920
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
921
				if (plannedDetailMap != null) {
922
 
923
					Integer quantity = plannedDetailMap.get(catalogId);
924
					if (quantity != null) {
925
						catalogListingModel.setAllocatedQuantity(quantity);
926
					}
927
				}
928
 
929
				if (lastMonthSaleMap != null) {
930
					Integer lastMonthSale = lastMonthSaleMap.get(catalogId);
931
 
932
					if (lastMonthSale != null) {
933
						catalogListingModel.setLastMonthSaleMap(lastMonthSale);
934
					} else {
935
						catalogListingModel.setLastMonthSaleMap(0);
936
					}
937
				} else {
938
					catalogListingModel.setLast15DaysSale(0);
939
				}
940
 
941
				catalogListingModel.setBrand(item.getBrand());
942
				if (item.getCategoryId() == 10006) {
943
					catalogListingModel.setCategoryId(item.getCategoryId());
944
				}
945
 
946
				FocusedModel fm = focusedModelMap.get(catalogId);
947
				if (fm != null) {
948
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
949
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
950
 
951
				} else {
952
					catalogListingModel.setRecommendedQty(0);
953
					catalogListingModel.setMinimumQty(0);
954
				}
955
 
956
				catalogListingMap.put(catalogId, catalogListingModel);
957
 
958
			}
959
			int itemAvailability = 0;
960
			if (currentStockMap != null) {
961
				Integer qty = currentStockMap.get(catalogId);
962
				itemAvailability = qty == null ? 0 : qty;
963
				catalogListingModel.setStockInHand(itemAvailability);
964
			} else {
965
				catalogListingModel.setStockInHand(0);
966
			}
967
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
968
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
969
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
970
 
971
		}
972
 
26963 amit.gupta 973
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26131 tejbeer 974
		if (fofoId > 0) {
975
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
976
			model.addAttribute("retailerName",
977
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
978
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
979
			model.addAttribute("retailerId", customRetailer.getPartnerId());
980
			model.addAttribute("counterSize", fs.getCounterSize().toString());
981
		} else {
982
			model.addAttribute("counterSize", counterSize.toString());
983
		}
984
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
985
 
986
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
987
 
988
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
989
				Comparator.reverseOrder());
990
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
991
		model.addAttribute("catalogTagListings",
992
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
993
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
994
		model.addAttribute("previousMonth", true);
995
		model.addAttribute("freezed", true);
26177 tejbeer 996
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26131 tejbeer 997
		model.addAttribute("customRetailers", customRetailers);
998
		model.addAttribute("totalAmount", totalAmount);
999
		model.addAttribute("monthlyPlanned", monthlyPlanned);
1000
		model.addAttribute("totalPcs", totalPcs);
1001
		return "open-indent";
1002
 
1003
	}
1004
 
23796 amit.gupta 1005
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
25812 amit.gupta 1006
		int orderRemovedCount = 0;
23796 amit.gupta 1007
		Iterator<Order> orderIterator = lastOrdersList.iterator();
1008
		while (orderIterator.hasNext()) {
1009
			Order o = orderIterator.next();
1010
			if (o.getInvoiceNumber() != null) {
1011
				try {
1012
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
1013
					orderIterator.remove();
25812 amit.gupta 1014
					orderRemovedCount++;
23796 amit.gupta 1015
				} catch (Exception e) {
1016
 
1017
				}
1018
			}
1019
		}
25812 amit.gupta 1020
		LOGGER.info("Order removed count is {}", orderRemovedCount);
23796 amit.gupta 1021
		return lastOrdersList;
1022
	}
1023
 
24406 amit.gupta 1024
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
24410 amit.gupta 1025
	public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
1026
			throws Exception {
24406 amit.gupta 1027
		JSONArray jsonArray = new JSONArray(jsonArrayString);
24410 amit.gupta 1028
		for (int i = 0; i < jsonArray.length(); i++) {
24406 amit.gupta 1029
			JSONObject obj = jsonArray.getJSONObject(i);
25378 tejbeer 1030
 
24406 amit.gupta 1031
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
25378 tejbeer 1032
			if (tl == null) {
1033
				continue;
1034
			} else {
1035
				tl.setActive(obj.getBoolean("active"));
1036
				tagListingRepository.persist(tl);
1037
			}
24406 amit.gupta 1038
		}
24410 amit.gupta 1039
		model.addAttribute("response", true);
23855 amit.gupta 1040
		return "response";
1041
	}
24231 amit.gupta 1042
 
28055 tejbeer 1043
	@RequestMapping(value = "/indent/confirm-hotdeals-pause", method = RequestMethod.POST)
1044
	public String hotdealUpdate(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
1045
			throws Exception {
1046
		JSONArray jsonArray = new JSONArray(jsonArrayString);
1047
		for (int i = 0; i < jsonArray.length(); i++) {
1048
			JSONObject obj = jsonArray.getJSONObject(i);
1049
 
1050
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
1051
			if (tl == null) {
1052
				continue;
1053
			} else {
1054
				tl.setHotDeals(obj.getBoolean("hotDeals"));
1055
				tagListingRepository.persist(tl);
1056
			}
1057
		}
1058
		model.addAttribute("response", true);
1059
		return "response";
1060
	}
1061
 
24231 amit.gupta 1062
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
23796 amit.gupta 1063
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
1064
		boolean success = false;
1065
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1066
		int fofoId = loginDetails.getFofoId();
1067
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
1068
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
1069
		Client userClient = new UserClient().getClient();
24231 amit.gupta 1070
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
23796 amit.gupta 1071
 
24231 amit.gupta 1072
		if (totalAmount > 0) {
23796 amit.gupta 1073
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
1074
			User user = userRepository.selectById(loginDetails.getFofoId());
1075
			userClient = new UserClient().getClient();
1076
			LOGGER.info("Setting wallet amount in cart");
24231 amit.gupta 1077
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
1078
					7890, OrderSource.WEBSITE.getValue(), true);
23796 amit.gupta 1079
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
1080
			createPayment(user, totalAmount, transactionId);
24231 amit.gupta 1081
			TransactionService.Client transactionClient = new TransactionClient().getClient();
23796 amit.gupta 1082
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
24231 amit.gupta 1083
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 1084
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
24231 amit.gupta 1085
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 1086
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
1087
			transactionClient = new TransactionClient().getClient();
1088
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
1089
			try {
1090
				transactionClient.enqueueTransactionInfoEmail(transactionId);
1091
			} catch (Exception e1) {
1092
				e1.printStackTrace();
1093
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
1094
			}
1095
			resetCart(transactionClient.getTransaction(transactionId));
1096
		}
1097
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
1098
		return "response";
1099
	}
24231 amit.gupta 1100
 
1101
	private void createPayment(User user, double totalAmount, long transactionId)
1102
			throws NumberFormatException, PaymentException, TException {
23796 amit.gupta 1103
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
1104
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
1105
		paymentAttributes.add(new Attribute("payMethod", "7890"));
24231 amit.gupta 1106
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
1107
				false);
1108
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
1109
				PaymentStatus.SUCCESS, null, paymentAttributes);
23796 amit.gupta 1110
	}
24231 amit.gupta 1111
 
23796 amit.gupta 1112
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
1113
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
24231 amit.gupta 1114
		/*
1115
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
1116
		 * currentInventorySnapshots = currentInventorySnapshotRepository
1117
		 * .selectItemsStock(fofoId); itemCisMap =
1118
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
1119
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1120
		 * List<StockAllocationModel> stockAllocationList =
1121
		 * stockAllocationService.getStockAllocation(fofoId, true);
1122
		 * 
1123
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
1124
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
1125
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
1126
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
1127
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
1128
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
1129
		 * validOrderStatusList); inTransitOrders =
1130
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
1131
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
1132
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
1133
		 * x.getLineItem().getQuantity())));
1134
		 * 
1135
		 * Iterator<TagListing> iterator = tagListings.iterator();
1136
		 * 
1137
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
1138
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
1139
		 * tagListing.getAllocatedQuantity()); if
1140
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
1141
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
1142
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
1143
		 * itemCisMap.get(tagListing.getItemId());
1144
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
1145
		 * itemIdAvailability.getAvailability()); StockAllocationModel
1146
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
1147
		 * 
1148
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
1149
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
1150
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
1151
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
1152
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
1153
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
1154
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
1155
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
1156
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
1157
		 */
23796 amit.gupta 1158
		return itemQuantities;
1159
 
1160
	}
24231 amit.gupta 1161
 
23796 amit.gupta 1162
	private long resetCart(Transaction transaction) {
1163
		long sum = 0;
1164
		Map<Long, Double> items = new HashMap<Long, Double>();
1165
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
1166
			sum += order.getGvAmount();
1167
			for (LineItem lineitem : order.getLineitems()) {
1168
				Long itemId = lineitem.getItem_id();
1169
				Double quantity = items.get(itemId);
1170
				if (quantity == null) {
1171
					quantity = lineitem.getQuantity();
1172
				} else {
1173
					quantity = quantity + lineitem.getQuantity();
1174
				}
1175
				items.put(itemId, quantity);
1176
			}
1177
		}
1178
 
1179
		LOGGER.debug("Items to reset in cart are: " + items);
1180
 
1181
		try {
1182
			Client userClient = new UserClient().getClient();
1183
			userClient.resetCart(transaction.getShoppingCartid(), items);
1184
		} catch (TException e) {
1185
			LOGGER.error("Error while updating information in payment database.", e);
1186
		} catch (ShoppingCartException e) {
1187
			LOGGER.error("Error while reseting the cart in cart database.", e);
1188
		} catch (Exception e) {
1189
			LOGGER.error("Unexpected exception", e);
1190
		}
1191
		return sum;
1192
	}
1193
 
25721 tejbeer 1194
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
1195
	public String getFocusedModel(HttpServletRequest request,
1196
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1197
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1198
			throws ProfitMandiBusinessException {
25736 tejbeer 1199
 
1200
		long size = 0;
25721 tejbeer 1201
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
27081 tejbeer 1202
 
25736 tejbeer 1203
		size = focusedModelRepository.selectAllCount();
1204
		if (!focusedModels.isEmpty()) {
1205
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
27088 tejbeer 1206
			Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25721 tejbeer 1207
 
27088 tejbeer 1208
			LOGGER.info("regionMap" + regionMap);
25736 tejbeer 1209
			model.addAttribute("focusedModels", focusedModels);
1210
			model.addAttribute("itemMap", itemMap);
27088 tejbeer 1211
			model.addAttribute("regionMap", regionMap);
25736 tejbeer 1212
			model.addAttribute("start", offset + 1);
1213
			model.addAttribute("size", size);
1214
			model.addAttribute("url", "/getPaginatedFocusedModel");
1215
 
1216
			if (focusedModels.size() < limit) {
1217
				model.addAttribute("end", offset + focusedModels.size());
1218
			} else {
1219
				model.addAttribute("end", offset + limit);
1220
			}
1221
		} else {
1222
 
1223
			model.addAttribute("walletRequest", focusedModels);
1224
			model.addAttribute("size", size);
1225
 
1226
		}
1227
 
27088 tejbeer 1228
		List<Region> regions = regionRepository.selectAll();
27081 tejbeer 1229
 
27088 tejbeer 1230
		model.addAttribute("regions", regions);
1231
 
25721 tejbeer 1232
		return "focused_model";
1233
	}
1234
 
25736 tejbeer 1235
	@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
1236
	public String getPaginatedFocusedModel(HttpServletRequest request,
1237
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1238
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1239
			throws ProfitMandiBusinessException {
1240
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
1241
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
1242
 
1243
		if (!focusedModels.isEmpty()) {
1244
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
27088 tejbeer 1245
			Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25736 tejbeer 1246
			model.addAttribute("focusedModels", focusedModels);
1247
			model.addAttribute("itemMap", itemMap);
27088 tejbeer 1248
			model.addAttribute("regionMap", regionMap);
25736 tejbeer 1249
			model.addAttribute("url", "/getPaginatedFocusedModel");
1250
		} else {
1251
			model.addAttribute("focusedModels", focusedModels);
1252
 
1253
		}
27081 tejbeer 1254
 
27088 tejbeer 1255
		List<Region> regions = regionRepository.selectAll();
1256
 
1257
		model.addAttribute("regions", regions);
25736 tejbeer 1258
		return "focused-model-paginated";
1259
	}
1260
 
25721 tejbeer 1261
	private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
1262
		Map<Integer, Item> itemMap = new HashMap<>();
1263
		for (FocusedModel focusedModel : focusedModels) {
1264
			List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
1265
			itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
1266
		}
1267
 
1268
		return itemMap;
1269
	}
1270
 
27088 tejbeer 1271
	private Map<Integer, Region> getRegionByRegionId(List<FocusedModel> focusedModels) {
1272
		Map<Integer, Region> regionMap = new HashMap<>();
1273
		for (FocusedModel focusedModel : focusedModels) {
1274
			Region region = regionRepository.selectById(focusedModel.getRegionId());
1275
			regionMap.put(region.getId(), region);
1276
		}
1277
 
1278
		return regionMap;
1279
	}
1280
 
25721 tejbeer 1281
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
1282
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int recommended,
27088 tejbeer 1283
			@RequestParam int minimumQty, @RequestParam int regionId, Model model) throws ProfitMandiBusinessException {
25721 tejbeer 1284
 
1285
		FocusedModel fm = new FocusedModel();
1286
		fm.setCatalogId(catalogId);
1287
		fm.setMinimumQty(minimumQty);
1288
		fm.setRecommendedQty(recommended);
27088 tejbeer 1289
		fm.setRegionId(regionId);
25721 tejbeer 1290
		fm.setCreatedTimestamp(LocalDateTime.now());
1291
		focusedModelRepository.persist(fm);
1292
		return "focused_model";
1293
	}
1294
 
1295
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
1296
	public String removeFocusedModelItem(HttpServletRequest request,
27081 tejbeer 1297
			@RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
25721 tejbeer 1298
 
27081 tejbeer 1299
		focusedModelRepository.deleteById(id);
25721 tejbeer 1300
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1301
		return "response";
1302
	}
25736 tejbeer 1303
 
25798 tejbeer 1304
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
1305
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 1306
 
25798 tejbeer 1307
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
1308
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
1309
 
1310
		mobileBrands.stream().forEach(x -> {
1311
			String brand = (String) x.get("name");
1312
			if (brandStockPricesMap.containsKey(brand)) {
1313
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
1314
				brandStockPrice.setBrandUrl((String) x.get("url"));
1315
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
1316
				brandStockPrices.add(brandStockPrice);
1317
			}
1318
		});
1319
 
1320
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
1321
				.collect(Collectors.toList());
1322
	}
1323
 
26721 tejbeer 1324
	@RequestMapping(value = "/getPartnerAllocation")
1325
	public String getPartnerAllocation(HttpServletRequest request, Model model) throws Exception {
1326
 
1327
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1328
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1329
 
1330
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1331
 
1332
		List<Integer> fofoIds = pp.get(authUser.getId());
1333
 
1334
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
1335
		Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
1336
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1337
 
1338
		model.addAttribute("customRetailersMap", customRetailersMap);
1339
		model.addAttribute("fofoStoreMap", fofoStoreMap);
1340
		return "partners_allocation";
1341
 
1342
	}
1343
 
26846 tejbeer 1344
	@RequestMapping(value = "/partnerPendingOrder")
1345
	public String partnerPendingOrder(HttpServletRequest request, Model model) throws Exception {
1346
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1347
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1348
 
1349
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1350
 
1351
		List<Integer> fofoIds = pp.get(authUser.getId());
1352
 
1353
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
1354
 
1355
		model.addAttribute("customRetailersMap", customRetailersMap);
1356
 
1357
		return "partner-po";
1358
 
1359
	}
1360
 
1361
	@RequestMapping(value = "/getPartnerloadContent")
1362
	public String getPartnerloadContent(HttpServletRequest request, Model model,
1363
			@RequestParam(required = false, defaultValue = "0") int fofoId,
1364
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
1365
 
1366
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1367
		Set<Integer> roleIds = loginDetails.getRoleIds();
1368
		LOGGER.info("Counter size is {}", counterSize);
1369
		LOGGER.info("Fofo Id is {}", fofoId);
1370
		boolean isAdmin = roleManager.isAdmin(roleIds);
1371
 
1372
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1373
				.collect(Collectors.toList());
1374
 
1375
		Map<String, Object> equalsMap = new HashMap<>();
1376
		equalsMap.put("categoryId", 10006);
1377
		equalsMap.put("brand", brands);
1378
		Map<String, List<?>> notEqualsMap = new HashMap<>();
1379
 
1380
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1381
		Map<Integer, Integer> currentStockMap;
1382
 
1383
		if (!isAdmin && fofoId == 0) {
1384
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1385
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
1386
			equalsStockJoinMap.put("fofoId", fofoId);
1387
			currentStockMap = itemRepository
1388
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1389
							equalsStockJoinMap, notEqualsJoinMap, "availability")
1390
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1391
			LOGGER.info("currentStock");
1392
		} else {
1393
			if (fofoId == 0) {
1394
 
1395
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1396
				equalsStockJoinMap.put("fofoId", fofoId);
1397
 
1398
				currentStockMap = itemRepository
1399
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1400
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1401
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1402
 
1403
			} else {
1404
 
1405
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1406
				equalsStockJoinMap.put("fofoId", fofoId);
1407
 
1408
				currentStockMap = itemRepository
1409
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1410
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1411
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1412
 
1413
			}
1414
		}
1415
 
27768 tejbeer 1416
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
26846 tejbeer 1417
		LOGGER.info("currentStock" + currentStockMap);
1418
 
1419
		Map<Integer, Integer> itemsInTransit = null;
1420
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
1421
		if (!isAdmin) {
1422
			tagListings = new ArrayList<>(tagListings);
28055 tejbeer 1423
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
1424
					OrderRepository.validOrderStatusList);
26846 tejbeer 1425
			inTransitOrders = this.filterValidOrders(inTransitOrders);
1426
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1427
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1428
		} else {
1429
			itemsInTransit = new HashMap<>();
1430
		}
1431
 
1432
		int totalPcs = 0;
1433
 
1434
		float totalAmount = 0;
1435
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
1436
 
27088 tejbeer 1437
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1438
				.collect(Collectors.toList());
26846 tejbeer 1439
 
27088 tejbeer 1440
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
1441
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
1442
 
26846 tejbeer 1443
		LocalDate currentMonthDate = LocalDate.now();
1444
		MonthlyPlanned monthlyPlanned = null;
1445
		List<Integer> fofoOrderIds = null;
1446
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 1447
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26846 tejbeer 1448
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
1449
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1450
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
1451
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1452
					LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
1453
					.collect(Collectors.toList());
1454
 
1455
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 1456
		} else {
26846 tejbeer 1457
			currentMonthDate = LocalDate.now().withDayOfMonth(1);
1458
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
1459
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1460
			model.addAttribute("planningMonth", currentMonthDate.getMonth());
1461
			model.addAttribute("mtd", true);
1462
			model.addAttribute("freezed", true);
1463
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1464
					curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
1465
					.collect(Collectors.toList());
1466
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
1467
		}
1468
 
1469
		Map<Integer, Integer> plannedDetailMap = null;
1470
		if (monthlyPlanned != null) {
1471
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1472
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
1473
 
1474
		}
1475
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
1476
 
1477
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
1478
		Map<String, Object> equalsJoinMap = new HashMap<>();
1479
 
1480
		equalsJoinMap.put("orderId", fofoOrderIds);
1481
		Map<Integer, Integer> last15daysMap = null;
1482
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
1483
 
1484
			last15daysMap = itemRepository
1485
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1486
							notEqualsJoinMap, "quantity")
1487
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1488
		}
1489
		LOGGER.info("last15daysMap" + last15daysMap);
1490
 
1491
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
1492
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1493
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1494
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1495
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1496
		LOGGER.info("catalogIdItemMap");
1497
 
1498
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
1499
		equalsItemJoinMap.put("active", 1);
28897 amit.gupta 1500
		List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
26846 tejbeer 1501
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
27768 tejbeer 1502
		Map<Integer, Integer> ourStockAvailability = new HashMap<>();
1503
		Map<Integer, List<SaholicCIS>> itemAvailabilityMap = saholicInventoryService.getSaholicStock()
1504
				.get(fofoStore.getWarehouseId());
1505
 
1506
		Map<Integer, List<Integer>> catalogItemIdMap = itemRepository
1507
				.selectAllByCatalogIds(new HashSet<>(
1508
						tagListingCatalogIds.stream().map(x -> x.getCatalogId()).collect(Collectors.toList())))
1509
				.stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1510
						Collectors.mapping(y -> y.getId(), Collectors.toList())));
1511
		for (Entry<Integer, List<Integer>> catalogItem : catalogItemIdMap.entrySet()) {
1512
			List<Integer> itemIds = catalogItem.getValue();
1513
			int availability = 0;
1514
			for (Integer itemId : itemIds) {
1515
				List<SaholicCIS> scis = itemAvailabilityMap.get(itemId);
1516
				if (scis != null) {
1517
					availability += scis.stream().collect(Collectors.summingInt(x -> x.getAvailability()));
1518
				}
1519
			}
1520
			Integer catalogItemId = catalogItem.getKey();
1521
			ourStockAvailability.put(catalogItemId, availability);
1522
		}
1523
		LOGGER.info("ourStockAvailability" + ourStockAvailability);
1524
 
28897 amit.gupta 1525
		for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
26846 tejbeer 1526
			int catalogId = catalogIdAggregateValue.getCatalogId();
1527
			Item item = catalogIdItemMap.get(catalogId).get(0);
1528
			TagListing tagListing = taglistingMap.get(item.getId());
1529
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1530
			if (!catalogListingMap.containsKey(catalogId)) {
1531
				catalogListingModel = new CatalogListingModel();
1532
				catalogListingModel.setCatalogId(catalogId);
1533
				catalogListingModel.setDp(tagListing.getSellingPrice());
1534
				catalogListingModel.setMop(tagListing.getMop());
1535
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1536
				if (plannedDetailMap != null) {
1537
 
1538
					Integer quantity = plannedDetailMap.get(catalogId);
1539
					if (quantity != null) {
1540
						catalogListingModel.setAllocatedQuantity(quantity);
1541
					}
1542
				}
1543
 
1544
				if (last15daysMap != null) {
1545
					Integer last15DaysSale = last15daysMap.get(catalogId);
1546
 
1547
					if (last15DaysSale != null) {
1548
						catalogListingModel.setLast15DaysSale(last15DaysSale);
1549
					} else {
1550
						catalogListingModel.setLast15DaysSale(0);
1551
					}
1552
				} else {
1553
					catalogListingModel.setLast15DaysSale(0);
1554
				}
1555
 
1556
				catalogListingModel.setBrand(item.getBrand());
1557
				if (item.getCategoryId() == 10006) {
1558
					catalogListingModel.setCategoryId(item.getCategoryId());
1559
				}
1560
 
27768 tejbeer 1561
				Integer ourStock = ourStockAvailability.get(catalogId);
1562
				LOGGER.info("catalogId" + catalogId);
1563
 
1564
				LOGGER.info("ourStock" + ourStock);
1565
				if (ourStock != null) {
1566
					catalogListingModel.setOurStockQty(ourStock);
1567
				}
1568
 
26846 tejbeer 1569
				FocusedModel fm = focusedModelMap.get(catalogId);
1570
				if (fm != null) {
1571
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1572
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
1573
 
1574
				} else {
1575
					catalogListingModel.setRecommendedQty(0);
1576
					catalogListingModel.setMinimumQty(0);
1577
				}
1578
 
1579
				catalogListingMap.put(catalogId, catalogListingModel);
1580
 
1581
			}
1582
			int itemAvailability = 0;
1583
			if (currentStockMap != null) {
1584
				Integer qty = currentStockMap.get(catalogId);
1585
				itemAvailability = qty == null ? 0 : qty;
1586
				catalogListingModel.setStockInHand(itemAvailability);
1587
			} else {
1588
				catalogListingModel.setStockInHand(0);
1589
			}
1590
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
1591
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1592
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
1593
			if (plannedDetailMap != null) {
1594
				if (plannedDetailMap.get(catalogId) != null) {
1595
 
1596
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
1597
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
1598
					LOGGER.info("remaning" + remaining);
1599
 
1600
					if (remaining != 0) {
1601
						catalogListingModel.setRemaining(remaining);
1602
					} else {
1603
						catalogListingModel.setRemaining(0);
1604
					}
1605
				}
1606
			}
1607
		}
1608
 
26963 amit.gupta 1609
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26846 tejbeer 1610
		if (fofoId > 0) {
1611
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1612
			model.addAttribute("retailerName",
1613
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1614
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1615
			model.addAttribute("retailerId", customRetailer.getPartnerId());
1616
			model.addAttribute("counterSize", fs.getCounterSize().toString());
1617
		} else {
1618
			model.addAttribute("counterSize", counterSize.toString());
1619
		}
1620
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
1621
 
1622
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
1623
 
1624
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1625
				Comparator.reverseOrder());
1626
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
1627
		model.addAttribute("catalogTagListings",
1628
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1629
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
27768 tejbeer 1630
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
26846 tejbeer 1631
		model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
1632
		model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());
1633
 
1634
		model.addAttribute("customRetailers", customRetailers);
1635
		model.addAttribute("totalAmount", totalAmount);
1636
		model.addAttribute("monthlyPlanned", monthlyPlanned);
1637
		model.addAttribute("totalPcs", totalPcs);
1638
 
1639
		UserWallet userWallet = walletService.getUserWallet(fofoId);
1640
 
1641
		model.addAttribute("userWallet", userWallet);
1642
 
1643
		return "create-partner-po";
1644
 
1645
	}
1646
 
1647
	@RequestMapping(value = "/createPo", method = RequestMethod.POST)
1648
	public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)
1649
			throws Exception {
1650
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1651
		SuggestedPo mp = new SuggestedPo();
1652
		mp.setFofoId(monthlyPoModel.getFofoId());
1653
		mp.setCreateTimestamp(LocalDateTime.now());
1654
		mp.setStatus("open");
1655
		mp.setAuthId(loginDetails.getEmailId());
1656
		monthlyPoRepository.persist(mp);
1657
 
1658
		for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {
1659
			SuggestedPoDetail mpd = new SuggestedPoDetail();
1660
			mpd.setItemId(poId.getItemId());
1661
			mpd.setQuantity(poId.getQty());
1662
			mpd.setUpdatedTimestamp(LocalDateTime.now());
1663
			mpd.setPoId(mp.getId());
1664
			monthlyPoDetailRepository.persist(mpd);
1665
		}
1666
 
1667
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
1668
		sendNotificationModel.setCampaignName("Alert");
1669
		sendNotificationModel.setMessage("Suggested Po");
1670
		sendNotificationModel.setType("url");
1671
		sendNotificationModel.setTitle("Alert");
26951 amit.gupta 1672
		sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
26846 tejbeer 1673
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1674
		sendNotificationModel.setMessageType(MessageType.notification);
1675
		int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());
1676
 
1677
		sendNotificationModel.setUserIds(Arrays.asList(userId));
1678
		notificationService.sendNotification(sendNotificationModel);
1679
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1680
 
1681
		return "response";
1682
	}
1683
 
1684
	@RequestMapping(value = "/selectItemColor", method = RequestMethod.GET)
1685
	public String selectItemColor(HttpServletRequest request, @RequestParam int catalogId, Model model)
1686
			throws Exception {
1687
 
1688
		List<Item> selecteditems = itemRepository.selectAllByCatalogItemId(catalogId);
1689
 
1690
		List<Item> items = new ArrayList<>();
1691
		for (Item item : selecteditems) {
1692
 
1693
			TagListing tagListing = tagListingRepository.selectByItemId(item.getId(), true);
1694
 
1695
			if (tagListing != null) {
1696
				items.add(item);
1697
			}
1698
 
1699
		}
1700
		model.addAttribute("items", items);
1701
		LOGGER.info("itemIdAndColorMap" + items);
1702
		return "select-item-color";
1703
	}
1704
 
25721 tejbeer 1705
}