Subversion Repositories SmartDukaan

Rev

Rev 26956 | Rev 26978 | 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
 
26956 amit.gupta 553
		LocalDate planningMonthDate = null;
26082 tejbeer 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))) {
26956 amit.gupta 558
			planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
559
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
26082 tejbeer 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 {
26956 amit.gupta 567
			planningMonthDate = LocalDate.now().withDayOfMonth(1);
26176 tejbeer 568
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
26956 amit.gupta 569
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
570
			model.addAttribute("planningMonth", planningMonthDate.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
 
26963 amit.gupta 689
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
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()));
26956 amit.gupta 711
		model.addAttribute("previousPlanningMonth", planningMonthDate.minusMonths(1).getMonth());
712
		model.addAttribute("currentPlanningMonth", planningMonthDate.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 {
26956 amit.gupta 726
		LocalDate planMonthStart = null;
727
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
728
			planMonthStart = LocalDate.now().plusMonths(1).withDayOfMonth(1);
729
		} else {
730
			planMonthStart = LocalDate.now().withDayOfMonth(1);
731
		}
26131 tejbeer 732
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
733
		Set<Integer> roleIds = loginDetails.getRoleIds();
734
		LOGGER.info("Counter size is {}", counterSize);
735
		LOGGER.info("Fofo Id is {}", fofoId);
736
		boolean isAdmin = roleManager.isAdmin(roleIds);
737
 
738
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
739
				.collect(Collectors.toList());
740
 
741
		Map<String, Object> equalsMap = new HashMap<>();
742
		equalsMap.put("categoryId", 10006);
743
		equalsMap.put("brand", brands);
744
		Map<String, List<?>> notEqualsMap = new HashMap<>();
745
 
746
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
747
		Map<Integer, Integer> currentStockMap;
748
 
749
		if (!isAdmin && fofoId == 0) {
750
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
751
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
752
			equalsStockJoinMap.put("fofoId", fofoId);
753
			currentStockMap = itemRepository
754
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
755
							equalsStockJoinMap, notEqualsJoinMap, "availability")
756
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
757
			LOGGER.info("currentStock");
758
		} else {
759
			if (fofoId == 0) {
760
 
761
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
762
				equalsStockJoinMap.put("fofoId", fofoId);
763
 
764
				currentStockMap = itemRepository
765
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
766
								equalsStockJoinMap, notEqualsJoinMap, "availability")
767
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
768
 
769
			} else {
770
 
771
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
772
				equalsStockJoinMap.put("fofoId", fofoId);
773
 
774
				currentStockMap = itemRepository
775
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
776
								equalsStockJoinMap, notEqualsJoinMap, "availability")
777
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
778
 
779
			}
780
		}
781
 
782
		LOGGER.info("currentStock" + currentStockMap);
783
 
784
		Map<Integer, Integer> itemsInTransit = null;
785
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
786
		if (!isAdmin) {
787
			tagListings = new ArrayList<>(tagListings);
788
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
789
			inTransitOrders = this.filterValidOrders(inTransitOrders);
790
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
791
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
792
		} else {
793
			itemsInTransit = new HashMap<>();
794
		}
795
 
796
		int totalPcs = 0;
797
 
798
		float totalAmount = 0;
799
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
800
 
801
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAll().stream()
802
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
803
 
26956 amit.gupta 804
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planMonthStart.minusMonths(1));
805
		model.addAttribute("planningMonth", planMonthStart.minusMonths(1).getMonth());
806
		model.addAttribute("previousPlanningMonth", planMonthStart.minusMonths(1).getMonth());
807
		model.addAttribute("currentPlanningMonth", planMonthStart.getMonth());
26131 tejbeer 808
 
809
		Map<Integer, Integer> plannedDetailMap = null;
810
		if (monthlyPlanned != null) {
811
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
812
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
813
 
814
		}
815
 
816
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
817
		List<Integer> fofoOrderIds = fofoOrderRepository
818
				.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
26956 amit.gupta 819
						planMonthStart.minusMonths(1).atStartOfDay(),
820
						planMonthStart.atStartOfDay())
26131 tejbeer 821
				.stream().map(x -> x.getId()).collect(Collectors.toList());
26721 tejbeer 822
 
26131 tejbeer 823
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
824
		Map<String, Object> equalsJoinMap = new HashMap<>();
825
		equalsJoinMap.put("orderId", fofoOrderIds);
26721 tejbeer 826
		Map<Integer, Integer> lastMonthSaleMap = null;
827
		if (!fofoOrderIds.isEmpty()) {
828
			lastMonthSaleMap = itemRepository
829
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
830
							notEqualsJoinMap, "quantity")
831
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
832
		}
26131 tejbeer 833
		LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);
834
 
835
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
836
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
837
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
838
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
839
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
840
		LOGGER.info("catalogIdItemMap");
841
 
842
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
843
		equalsItemJoinMap.put("active", 1);
844
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
845
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
846
		LOGGER.info("tagListingCatalogIds");
847
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
848
			int catalogId = catalogIdAggregateValue.getCatalogId();
849
			Item item = catalogIdItemMap.get(catalogId).get(0);
850
			TagListing tagListing = taglistingMap.get(item.getId());
851
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
852
			if (!catalogListingMap.containsKey(catalogId)) {
853
				catalogListingModel = new CatalogListingModel();
854
				catalogListingModel.setCatalogId(catalogId);
855
				catalogListingModel.setDp(tagListing.getSellingPrice());
856
				catalogListingModel.setMop(tagListing.getMop());
857
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
858
				if (plannedDetailMap != null) {
859
 
860
					Integer quantity = plannedDetailMap.get(catalogId);
861
					if (quantity != null) {
862
						catalogListingModel.setAllocatedQuantity(quantity);
863
					}
864
				}
865
 
866
				if (lastMonthSaleMap != null) {
867
					Integer lastMonthSale = lastMonthSaleMap.get(catalogId);
868
 
869
					if (lastMonthSale != null) {
870
						catalogListingModel.setLastMonthSaleMap(lastMonthSale);
871
					} else {
872
						catalogListingModel.setLastMonthSaleMap(0);
873
					}
874
				} else {
875
					catalogListingModel.setLast15DaysSale(0);
876
				}
877
 
878
				catalogListingModel.setBrand(item.getBrand());
879
				if (item.getCategoryId() == 10006) {
880
					catalogListingModel.setCategoryId(item.getCategoryId());
881
				}
882
 
883
				FocusedModel fm = focusedModelMap.get(catalogId);
884
				if (fm != null) {
885
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
886
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
887
 
888
				} else {
889
					catalogListingModel.setRecommendedQty(0);
890
					catalogListingModel.setMinimumQty(0);
891
				}
892
 
893
				catalogListingMap.put(catalogId, catalogListingModel);
894
 
895
			}
896
			int itemAvailability = 0;
897
			if (currentStockMap != null) {
898
				Integer qty = currentStockMap.get(catalogId);
899
				itemAvailability = qty == null ? 0 : qty;
900
				catalogListingModel.setStockInHand(itemAvailability);
901
			} else {
902
				catalogListingModel.setStockInHand(0);
903
			}
904
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
905
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
906
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
907
 
908
		}
909
 
26963 amit.gupta 910
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26131 tejbeer 911
		if (fofoId > 0) {
912
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
913
			model.addAttribute("retailerName",
914
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
915
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
916
			model.addAttribute("retailerId", customRetailer.getPartnerId());
917
			model.addAttribute("counterSize", fs.getCounterSize().toString());
918
		} else {
919
			model.addAttribute("counterSize", counterSize.toString());
920
		}
921
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
922
 
923
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
924
 
925
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
926
				Comparator.reverseOrder());
927
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
928
		model.addAttribute("catalogTagListings",
929
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
930
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
931
		model.addAttribute("previousMonth", true);
932
		model.addAttribute("freezed", true);
26177 tejbeer 933
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26131 tejbeer 934
		model.addAttribute("customRetailers", customRetailers);
935
		model.addAttribute("totalAmount", totalAmount);
936
		model.addAttribute("monthlyPlanned", monthlyPlanned);
937
		model.addAttribute("totalPcs", totalPcs);
938
		return "open-indent";
939
 
940
	}
941
 
23796 amit.gupta 942
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
25812 amit.gupta 943
		int orderRemovedCount = 0;
23796 amit.gupta 944
		Iterator<Order> orderIterator = lastOrdersList.iterator();
945
		while (orderIterator.hasNext()) {
946
			Order o = orderIterator.next();
947
			if (o.getInvoiceNumber() != null) {
948
				try {
949
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
950
					orderIterator.remove();
25812 amit.gupta 951
					orderRemovedCount++;
23796 amit.gupta 952
				} catch (Exception e) {
953
 
954
				}
955
			}
956
		}
25812 amit.gupta 957
		LOGGER.info("Order removed count is {}", orderRemovedCount);
23796 amit.gupta 958
		return lastOrdersList;
959
	}
960
 
24406 amit.gupta 961
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
24410 amit.gupta 962
	public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
963
			throws Exception {
24406 amit.gupta 964
		JSONArray jsonArray = new JSONArray(jsonArrayString);
24410 amit.gupta 965
		for (int i = 0; i < jsonArray.length(); i++) {
24406 amit.gupta 966
			JSONObject obj = jsonArray.getJSONObject(i);
25378 tejbeer 967
 
24406 amit.gupta 968
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
25378 tejbeer 969
			if (tl == null) {
970
				continue;
971
			} else {
972
				tl.setActive(obj.getBoolean("active"));
973
				tagListingRepository.persist(tl);
974
			}
24406 amit.gupta 975
		}
24410 amit.gupta 976
		model.addAttribute("response", true);
23855 amit.gupta 977
		return "response";
978
	}
24231 amit.gupta 979
 
980
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
23796 amit.gupta 981
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
982
		boolean success = false;
983
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
984
		int fofoId = loginDetails.getFofoId();
985
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
986
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
987
		Client userClient = new UserClient().getClient();
24231 amit.gupta 988
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
23796 amit.gupta 989
 
24231 amit.gupta 990
		if (totalAmount > 0) {
23796 amit.gupta 991
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
992
			User user = userRepository.selectById(loginDetails.getFofoId());
993
			userClient = new UserClient().getClient();
994
			LOGGER.info("Setting wallet amount in cart");
24231 amit.gupta 995
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
996
					7890, OrderSource.WEBSITE.getValue(), true);
23796 amit.gupta 997
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
998
			createPayment(user, totalAmount, transactionId);
24231 amit.gupta 999
			TransactionService.Client transactionClient = new TransactionClient().getClient();
23796 amit.gupta 1000
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
24231 amit.gupta 1001
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 1002
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
24231 amit.gupta 1003
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 1004
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
1005
			transactionClient = new TransactionClient().getClient();
1006
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
1007
			try {
1008
				transactionClient.enqueueTransactionInfoEmail(transactionId);
1009
			} catch (Exception e1) {
1010
				e1.printStackTrace();
1011
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
1012
			}
1013
			resetCart(transactionClient.getTransaction(transactionId));
1014
		}
1015
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
1016
		return "response";
1017
	}
24231 amit.gupta 1018
 
1019
	private void createPayment(User user, double totalAmount, long transactionId)
1020
			throws NumberFormatException, PaymentException, TException {
23796 amit.gupta 1021
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
1022
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
1023
		paymentAttributes.add(new Attribute("payMethod", "7890"));
24231 amit.gupta 1024
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
1025
				false);
1026
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
1027
				PaymentStatus.SUCCESS, null, paymentAttributes);
23796 amit.gupta 1028
	}
24231 amit.gupta 1029
 
23796 amit.gupta 1030
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
1031
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
24231 amit.gupta 1032
		/*
1033
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
1034
		 * currentInventorySnapshots = currentInventorySnapshotRepository
1035
		 * .selectItemsStock(fofoId); itemCisMap =
1036
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
1037
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1038
		 * List<StockAllocationModel> stockAllocationList =
1039
		 * stockAllocationService.getStockAllocation(fofoId, true);
1040
		 * 
1041
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
1042
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
1043
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
1044
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
1045
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
1046
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
1047
		 * validOrderStatusList); inTransitOrders =
1048
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
1049
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
1050
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
1051
		 * x.getLineItem().getQuantity())));
1052
		 * 
1053
		 * Iterator<TagListing> iterator = tagListings.iterator();
1054
		 * 
1055
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
1056
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
1057
		 * tagListing.getAllocatedQuantity()); if
1058
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
1059
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
1060
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
1061
		 * itemCisMap.get(tagListing.getItemId());
1062
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
1063
		 * itemIdAvailability.getAvailability()); StockAllocationModel
1064
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
1065
		 * 
1066
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
1067
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
1068
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
1069
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
1070
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
1071
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
1072
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
1073
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
1074
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
1075
		 */
23796 amit.gupta 1076
		return itemQuantities;
1077
 
1078
	}
24231 amit.gupta 1079
 
23796 amit.gupta 1080
	private long resetCart(Transaction transaction) {
1081
		long sum = 0;
1082
		Map<Long, Double> items = new HashMap<Long, Double>();
1083
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
1084
			sum += order.getGvAmount();
1085
			for (LineItem lineitem : order.getLineitems()) {
1086
				Long itemId = lineitem.getItem_id();
1087
				Double quantity = items.get(itemId);
1088
				if (quantity == null) {
1089
					quantity = lineitem.getQuantity();
1090
				} else {
1091
					quantity = quantity + lineitem.getQuantity();
1092
				}
1093
				items.put(itemId, quantity);
1094
			}
1095
		}
1096
 
1097
		LOGGER.debug("Items to reset in cart are: " + items);
1098
 
1099
		try {
1100
			Client userClient = new UserClient().getClient();
1101
			userClient.resetCart(transaction.getShoppingCartid(), items);
1102
		} catch (TException e) {
1103
			LOGGER.error("Error while updating information in payment database.", e);
1104
		} catch (ShoppingCartException e) {
1105
			LOGGER.error("Error while reseting the cart in cart database.", e);
1106
		} catch (Exception e) {
1107
			LOGGER.error("Unexpected exception", e);
1108
		}
1109
		return sum;
1110
	}
1111
 
25721 tejbeer 1112
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
1113
	public String getFocusedModel(HttpServletRequest request,
1114
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1115
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1116
			throws ProfitMandiBusinessException {
25736 tejbeer 1117
 
1118
		long size = 0;
25721 tejbeer 1119
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
25736 tejbeer 1120
		size = focusedModelRepository.selectAllCount();
25721 tejbeer 1121
 
25736 tejbeer 1122
		if (!focusedModels.isEmpty()) {
1123
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
25721 tejbeer 1124
 
25736 tejbeer 1125
			model.addAttribute("focusedModels", focusedModels);
1126
			model.addAttribute("itemMap", itemMap);
25721 tejbeer 1127
 
25736 tejbeer 1128
			model.addAttribute("start", offset + 1);
1129
			model.addAttribute("size", size);
1130
			model.addAttribute("url", "/getPaginatedFocusedModel");
1131
 
1132
			if (focusedModels.size() < limit) {
1133
				model.addAttribute("end", offset + focusedModels.size());
1134
			} else {
1135
				model.addAttribute("end", offset + limit);
1136
			}
1137
		} else {
1138
 
1139
			model.addAttribute("walletRequest", focusedModels);
1140
			model.addAttribute("size", size);
1141
 
1142
		}
1143
 
25721 tejbeer 1144
		return "focused_model";
1145
	}
1146
 
25736 tejbeer 1147
	@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
1148
	public String getPaginatedFocusedModel(HttpServletRequest request,
1149
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1150
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1151
			throws ProfitMandiBusinessException {
1152
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
1153
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
1154
 
1155
		if (!focusedModels.isEmpty()) {
1156
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
1157
 
1158
			model.addAttribute("focusedModels", focusedModels);
1159
			model.addAttribute("itemMap", itemMap);
1160
 
1161
			model.addAttribute("url", "/getPaginatedFocusedModel");
1162
		} else {
1163
			model.addAttribute("focusedModels", focusedModels);
1164
 
1165
		}
1166
		return "focused-model-paginated";
1167
	}
1168
 
25721 tejbeer 1169
	private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
1170
		Map<Integer, Item> itemMap = new HashMap<>();
1171
		for (FocusedModel focusedModel : focusedModels) {
1172
			List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
1173
			itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
1174
		}
1175
 
1176
		return itemMap;
1177
	}
1178
 
1179
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
1180
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int recommended,
1181
			@RequestParam int minimumQty, Model model) throws ProfitMandiBusinessException {
1182
 
1183
		FocusedModel fm = new FocusedModel();
1184
		fm.setCatalogId(catalogId);
1185
		fm.setMinimumQty(minimumQty);
1186
		fm.setRecommendedQty(recommended);
1187
		fm.setCreatedTimestamp(LocalDateTime.now());
1188
		focusedModelRepository.persist(fm);
1189
		return "focused_model";
1190
	}
1191
 
1192
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
1193
	public String removeFocusedModelItem(HttpServletRequest request,
1194
			@RequestParam(name = "catalogId", defaultValue = "0") int catalogId, Model model) throws Exception {
1195
 
1196
		focusedModelRepository.deleteById(catalogId);
1197
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1198
		return "response";
1199
	}
25736 tejbeer 1200
 
25798 tejbeer 1201
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
1202
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 1203
 
25798 tejbeer 1204
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
1205
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
1206
 
1207
		mobileBrands.stream().forEach(x -> {
1208
			String brand = (String) x.get("name");
1209
			if (brandStockPricesMap.containsKey(brand)) {
1210
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
1211
				brandStockPrice.setBrandUrl((String) x.get("url"));
1212
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
1213
				brandStockPrices.add(brandStockPrice);
1214
			}
1215
		});
1216
 
1217
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
1218
				.collect(Collectors.toList());
1219
	}
1220
 
26721 tejbeer 1221
	@RequestMapping(value = "/getPartnerAllocation")
1222
	public String getPartnerAllocation(HttpServletRequest request, Model model) throws Exception {
1223
 
1224
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1225
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1226
 
1227
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1228
 
1229
		List<Integer> fofoIds = pp.get(authUser.getId());
1230
 
1231
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
1232
		Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
1233
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1234
 
1235
		model.addAttribute("customRetailersMap", customRetailersMap);
1236
		model.addAttribute("fofoStoreMap", fofoStoreMap);
1237
		return "partners_allocation";
1238
 
1239
	}
1240
 
26846 tejbeer 1241
	@RequestMapping(value = "/partnerPendingOrder")
1242
	public String partnerPendingOrder(HttpServletRequest request, Model model) throws Exception {
1243
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1244
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1245
 
1246
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1247
 
1248
		List<Integer> fofoIds = pp.get(authUser.getId());
1249
 
1250
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
1251
 
1252
		model.addAttribute("customRetailersMap", customRetailersMap);
1253
 
1254
		return "partner-po";
1255
 
1256
	}
1257
 
1258
	@RequestMapping(value = "/getPartnerloadContent")
1259
	public String getPartnerloadContent(HttpServletRequest request, Model model,
1260
			@RequestParam(required = false, defaultValue = "0") int fofoId,
1261
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
1262
 
1263
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1264
		Set<Integer> roleIds = loginDetails.getRoleIds();
1265
		LOGGER.info("Counter size is {}", counterSize);
1266
		LOGGER.info("Fofo Id is {}", fofoId);
1267
		boolean isAdmin = roleManager.isAdmin(roleIds);
1268
 
1269
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1270
				.collect(Collectors.toList());
1271
 
1272
		Map<String, Object> equalsMap = new HashMap<>();
1273
		equalsMap.put("categoryId", 10006);
1274
		equalsMap.put("brand", brands);
1275
		Map<String, List<?>> notEqualsMap = new HashMap<>();
1276
 
1277
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1278
		Map<Integer, Integer> currentStockMap;
1279
 
1280
		if (!isAdmin && fofoId == 0) {
1281
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1282
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
1283
			equalsStockJoinMap.put("fofoId", fofoId);
1284
			currentStockMap = itemRepository
1285
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1286
							equalsStockJoinMap, notEqualsJoinMap, "availability")
1287
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1288
			LOGGER.info("currentStock");
1289
		} else {
1290
			if (fofoId == 0) {
1291
 
1292
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1293
				equalsStockJoinMap.put("fofoId", fofoId);
1294
 
1295
				currentStockMap = itemRepository
1296
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1297
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1298
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1299
 
1300
			} else {
1301
 
1302
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1303
				equalsStockJoinMap.put("fofoId", fofoId);
1304
 
1305
				currentStockMap = itemRepository
1306
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1307
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1308
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1309
 
1310
			}
1311
		}
1312
 
1313
		LOGGER.info("currentStock" + currentStockMap);
1314
 
1315
		Map<Integer, Integer> itemsInTransit = null;
1316
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
1317
		if (!isAdmin) {
1318
			tagListings = new ArrayList<>(tagListings);
1319
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
1320
			inTransitOrders = this.filterValidOrders(inTransitOrders);
1321
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1322
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1323
		} else {
1324
			itemsInTransit = new HashMap<>();
1325
		}
1326
 
1327
		int totalPcs = 0;
1328
 
1329
		float totalAmount = 0;
1330
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
1331
 
1332
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAll().stream()
1333
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
1334
 
1335
		LocalDate currentMonthDate = LocalDate.now();
1336
		MonthlyPlanned monthlyPlanned = null;
1337
		List<Integer> fofoOrderIds = null;
1338
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 1339
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26846 tejbeer 1340
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
1341
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1342
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
1343
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1344
					LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
1345
					.collect(Collectors.toList());
1346
 
1347
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 1348
		} else {
26846 tejbeer 1349
			currentMonthDate = LocalDate.now().withDayOfMonth(1);
1350
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
1351
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1352
			model.addAttribute("planningMonth", currentMonthDate.getMonth());
1353
			model.addAttribute("mtd", true);
1354
			model.addAttribute("freezed", true);
1355
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1356
					curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
1357
					.collect(Collectors.toList());
1358
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
1359
		}
1360
 
1361
		Map<Integer, Integer> plannedDetailMap = null;
1362
		if (monthlyPlanned != null) {
1363
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1364
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
1365
 
1366
		}
1367
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
1368
 
1369
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
1370
		Map<String, Object> equalsJoinMap = new HashMap<>();
1371
 
1372
		equalsJoinMap.put("orderId", fofoOrderIds);
1373
		Map<Integer, Integer> last15daysMap = null;
1374
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
1375
 
1376
			last15daysMap = itemRepository
1377
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1378
							notEqualsJoinMap, "quantity")
1379
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1380
		}
1381
		LOGGER.info("last15daysMap" + last15daysMap);
1382
 
1383
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
1384
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1385
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1386
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1387
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1388
		LOGGER.info("catalogIdItemMap");
1389
 
1390
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
1391
		equalsItemJoinMap.put("active", 1);
1392
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
1393
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
1394
		LOGGER.info("tagListingCatalogIds");
1395
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
1396
			int catalogId = catalogIdAggregateValue.getCatalogId();
1397
			Item item = catalogIdItemMap.get(catalogId).get(0);
1398
			TagListing tagListing = taglistingMap.get(item.getId());
1399
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1400
			if (!catalogListingMap.containsKey(catalogId)) {
1401
				catalogListingModel = new CatalogListingModel();
1402
				catalogListingModel.setCatalogId(catalogId);
1403
				catalogListingModel.setDp(tagListing.getSellingPrice());
1404
				catalogListingModel.setMop(tagListing.getMop());
1405
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1406
				if (plannedDetailMap != null) {
1407
 
1408
					Integer quantity = plannedDetailMap.get(catalogId);
1409
					if (quantity != null) {
1410
						catalogListingModel.setAllocatedQuantity(quantity);
1411
					}
1412
				}
1413
 
1414
				if (last15daysMap != null) {
1415
					Integer last15DaysSale = last15daysMap.get(catalogId);
1416
 
1417
					if (last15DaysSale != null) {
1418
						catalogListingModel.setLast15DaysSale(last15DaysSale);
1419
					} else {
1420
						catalogListingModel.setLast15DaysSale(0);
1421
					}
1422
				} else {
1423
					catalogListingModel.setLast15DaysSale(0);
1424
				}
1425
 
1426
				catalogListingModel.setBrand(item.getBrand());
1427
				if (item.getCategoryId() == 10006) {
1428
					catalogListingModel.setCategoryId(item.getCategoryId());
1429
				}
1430
 
1431
				FocusedModel fm = focusedModelMap.get(catalogId);
1432
				if (fm != null) {
1433
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1434
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
1435
 
1436
				} else {
1437
					catalogListingModel.setRecommendedQty(0);
1438
					catalogListingModel.setMinimumQty(0);
1439
				}
1440
 
1441
				catalogListingMap.put(catalogId, catalogListingModel);
1442
 
1443
			}
1444
			int itemAvailability = 0;
1445
			if (currentStockMap != null) {
1446
				Integer qty = currentStockMap.get(catalogId);
1447
				itemAvailability = qty == null ? 0 : qty;
1448
				catalogListingModel.setStockInHand(itemAvailability);
1449
			} else {
1450
				catalogListingModel.setStockInHand(0);
1451
			}
1452
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
1453
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1454
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
1455
			if (plannedDetailMap != null) {
1456
				if (plannedDetailMap.get(catalogId) != null) {
1457
 
1458
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
1459
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
1460
					LOGGER.info("remaning" + remaining);
1461
 
1462
					if (remaining != 0) {
1463
						catalogListingModel.setRemaining(remaining);
1464
					} else {
1465
						catalogListingModel.setRemaining(0);
1466
					}
1467
				}
1468
			}
1469
		}
1470
 
26963 amit.gupta 1471
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26846 tejbeer 1472
		if (fofoId > 0) {
1473
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1474
			model.addAttribute("retailerName",
1475
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1476
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1477
			model.addAttribute("retailerId", customRetailer.getPartnerId());
1478
			model.addAttribute("counterSize", fs.getCounterSize().toString());
1479
		} else {
1480
			model.addAttribute("counterSize", counterSize.toString());
1481
		}
1482
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
1483
 
1484
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
1485
 
1486
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1487
				Comparator.reverseOrder());
1488
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
1489
		model.addAttribute("catalogTagListings",
1490
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1491
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
1492
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
1493
		model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
1494
		model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());
1495
 
1496
		model.addAttribute("customRetailers", customRetailers);
1497
		model.addAttribute("totalAmount", totalAmount);
1498
		model.addAttribute("monthlyPlanned", monthlyPlanned);
1499
		model.addAttribute("totalPcs", totalPcs);
1500
 
1501
		UserWallet userWallet = walletService.getUserWallet(fofoId);
1502
 
1503
		model.addAttribute("userWallet", userWallet);
1504
 
1505
		return "create-partner-po";
1506
 
1507
	}
1508
 
1509
	@RequestMapping(value = "/createPo", method = RequestMethod.POST)
1510
	public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)
1511
			throws Exception {
1512
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1513
		SuggestedPo mp = new SuggestedPo();
1514
		mp.setFofoId(monthlyPoModel.getFofoId());
1515
		mp.setCreateTimestamp(LocalDateTime.now());
1516
		mp.setStatus("open");
1517
		mp.setAuthId(loginDetails.getEmailId());
1518
		monthlyPoRepository.persist(mp);
1519
 
1520
		for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {
1521
			SuggestedPoDetail mpd = new SuggestedPoDetail();
1522
			mpd.setItemId(poId.getItemId());
1523
			mpd.setQuantity(poId.getQty());
1524
			mpd.setUpdatedTimestamp(LocalDateTime.now());
1525
			mpd.setPoId(mp.getId());
1526
			monthlyPoDetailRepository.persist(mpd);
1527
		}
1528
 
1529
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
1530
		sendNotificationModel.setCampaignName("Alert");
1531
		sendNotificationModel.setMessage("Suggested Po");
1532
		sendNotificationModel.setType("url");
1533
		sendNotificationModel.setTitle("Alert");
26951 amit.gupta 1534
		sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
26846 tejbeer 1535
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1536
		sendNotificationModel.setMessageType(MessageType.notification);
1537
		int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());
1538
 
1539
		sendNotificationModel.setUserIds(Arrays.asList(userId));
1540
		notificationService.sendNotification(sendNotificationModel);
1541
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1542
 
1543
		return "response";
1544
	}
1545
 
1546
	@RequestMapping(value = "/selectItemColor", method = RequestMethod.GET)
1547
	public String selectItemColor(HttpServletRequest request, @RequestParam int catalogId, Model model)
1548
			throws Exception {
1549
 
1550
		List<Item> selecteditems = itemRepository.selectAllByCatalogItemId(catalogId);
1551
 
1552
		List<Item> items = new ArrayList<>();
1553
		for (Item item : selecteditems) {
1554
 
1555
			TagListing tagListing = tagListingRepository.selectByItemId(item.getId(), true);
1556
 
1557
			if (tagListing != null) {
1558
				items.add(item);
1559
			}
1560
 
1561
		}
1562
		model.addAttribute("items", items);
1563
		LOGGER.info("itemIdAndColorMap" + items);
1564
		return "select-item-color";
1565
	}
1566
 
25721 tejbeer 1567
}