Subversion Repositories SmartDukaan

Rev

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