Subversion Repositories SmartDukaan

Rev

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