Subversion Repositories SmartDukaan

Rev

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