Subversion Repositories SmartDukaan

Rev

Rev 26978 | Rev 27081 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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