Subversion Repositories SmartDukaan

Rev

Rev 30564 | Rev 30668 | 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
 
25736 tejbeer 3
import com.mongodb.DBObject;
30046 tejbeer 4
import com.spice.profitmandi.common.enumuration.ActivationType;
23785 amit.gupta 5
import com.spice.profitmandi.common.enumuration.CounterSize;
26846 tejbeer 6
import com.spice.profitmandi.common.enumuration.MessageType;
23405 amit.gupta 7
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
30017 amit.gupta 8
import com.spice.profitmandi.common.model.*;
24231 amit.gupta 9
import com.spice.profitmandi.common.util.FileUtil;
25721 tejbeer 10
import com.spice.profitmandi.common.util.Utils;
11
import com.spice.profitmandi.common.util.Utils.Attachment;
26721 tejbeer 12
import com.spice.profitmandi.dao.entity.auth.AuthUser;
30003 tejbeer 13
import com.spice.profitmandi.dao.entity.catalog.Category;
25721 tejbeer 14
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
23785 amit.gupta 15
import com.spice.profitmandi.dao.entity.catalog.Item;
23405 amit.gupta 16
import com.spice.profitmandi.dao.entity.catalog.TagListing;
27088 tejbeer 17
import com.spice.profitmandi.dao.entity.cs.Region;
30017 amit.gupta 18
import com.spice.profitmandi.dao.entity.fofo.*;
30664 amit.gupta 19
import com.spice.profitmandi.dao.entity.inventory.SaholicCISTable;
30003 tejbeer 20
import com.spice.profitmandi.dao.entity.inventory.SaholicPOItem;
23796 amit.gupta 21
import com.spice.profitmandi.dao.entity.transaction.Order;
26846 tejbeer 22
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
23796 amit.gupta 23
import com.spice.profitmandi.dao.entity.user.User;
30017 amit.gupta 24
import com.spice.profitmandi.dao.entity.warehouse.BrandRegionMapping;
26978 tejbeer 25
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
30003 tejbeer 26
import com.spice.profitmandi.dao.model.FofoReportingModel;
27
import com.spice.profitmandi.dao.model.InStockAccessoriesTvFofoIdModel;
28
import com.spice.profitmandi.dao.model.InStockBrandFofoIdModel;
26721 tejbeer 29
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
30003 tejbeer 30
import com.spice.profitmandi.dao.repository.catalog.CategoryRepository;
25721 tejbeer 31
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
23405 amit.gupta 32
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
33
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
25721 tejbeer 34
import com.spice.profitmandi.dao.repository.cs.CsService;
27088 tejbeer 35
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
30003 tejbeer 36
import com.spice.profitmandi.dao.repository.cs.PositionRepository;
27088 tejbeer 37
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
30044 tejbeer 38
import com.spice.profitmandi.dao.repository.dtr.BrandLimitRepository;
23779 amit.gupta 39
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25736 tejbeer 40
import com.spice.profitmandi.dao.repository.dtr.Mongo;
26846 tejbeer 41
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
30017 amit.gupta 42
import com.spice.profitmandi.dao.repository.fofo.*;
30664 amit.gupta 43
import com.spice.profitmandi.dao.repository.inventory.SaholicCISTableRepository;
27768 tejbeer 44
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
30017 amit.gupta 45
import com.spice.profitmandi.dao.repository.inventory.WarehouseRepository;
23796 amit.gupta 46
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
47
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
48
import com.spice.profitmandi.dao.repository.user.UserRepository;
30017 amit.gupta 49
import com.spice.profitmandi.dao.repository.warehouse.BrandRegionMappingRepository;
26846 tejbeer 50
import com.spice.profitmandi.service.NotificationService;
23798 amit.gupta 51
import com.spice.profitmandi.service.authentication.RoleManager;
25736 tejbeer 52
import com.spice.profitmandi.service.inventory.InventoryService;
27768 tejbeer 53
import com.spice.profitmandi.service.inventory.SaholicInventoryService;
23779 amit.gupta 54
import com.spice.profitmandi.service.inventory.StockAllocationService;
55
import com.spice.profitmandi.service.user.RetailerService;
25547 amit.gupta 56
import com.spice.profitmandi.service.wallet.WalletService;
23796 amit.gupta 57
import com.spice.profitmandi.thrift.clients.PaymentClient;
58
import com.spice.profitmandi.thrift.clients.TransactionClient;
59
import com.spice.profitmandi.thrift.clients.UserClient;
23405 amit.gupta 60
import com.spice.profitmandi.web.model.LoginDetails;
61
import com.spice.profitmandi.web.util.CookiesProcessor;
62
import com.spice.profitmandi.web.util.MVCResponseSender;
23796 amit.gupta 63
import in.shop2020.logistics.PickUpType;
30017 amit.gupta 64
import in.shop2020.model.v1.order.*;
23796 amit.gupta 65
import in.shop2020.model.v1.user.ItemPriceQuantity;
66
import in.shop2020.model.v1.user.ShoppingCartException;
67
import in.shop2020.model.v1.user.UserContextService.Client;
68
import in.shop2020.payments.Attribute;
69
import in.shop2020.payments.PaymentException;
70
import in.shop2020.payments.PaymentStatus;
30017 amit.gupta 71
import org.apache.commons.io.output.ByteArrayOutputStream;
72
import org.apache.logging.log4j.LogManager;
73
import org.apache.logging.log4j.Logger;
74
import org.apache.thrift.TException;
75
import org.json.JSONArray;
76
import org.json.JSONObject;
77
import org.springframework.beans.factory.annotation.Autowired;
78
import org.springframework.core.io.ByteArrayResource;
79
import org.springframework.http.HttpHeaders;
80
import org.springframework.http.HttpStatus;
81
import org.springframework.http.ResponseEntity;
82
import org.springframework.mail.javamail.JavaMailSender;
83
import org.springframework.stereotype.Controller;
84
import org.springframework.transaction.annotation.Transactional;
85
import org.springframework.ui.Model;
86
import org.springframework.web.bind.annotation.RequestBody;
87
import org.springframework.web.bind.annotation.RequestMapping;
88
import org.springframework.web.bind.annotation.RequestMethod;
89
import org.springframework.web.bind.annotation.RequestParam;
23796 amit.gupta 90
 
30017 amit.gupta 91
import javax.servlet.http.HttpServletRequest;
92
import java.time.LocalDate;
93
import java.time.LocalDateTime;
94
import java.time.LocalTime;
95
import java.util.*;
96
import java.util.Map.Entry;
97
import java.util.function.Function;
98
import java.util.stream.Collectors;
99
 
23405 amit.gupta 100
@Controller
101
@Transactional(rollbackFor = Throwable.class)
102
public class IndentController {
103
 
23568 govind 104
	private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
23796 amit.gupta 105
	private static final int WALLET_GATEWAY_ID = 8;
24406 amit.gupta 106
	private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));
23405 amit.gupta 107
 
24231 amit.gupta 108
	private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,
109
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
110
			OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
111
			OrderStatus.REACHED_DESTINATION_CITY);
25721 tejbeer 112
 
26951 amit.gupta 113
	private static final int PLANNING_OPEN_DAY = 20;
114
	private static final int PLANNING_CLOSE_DAY = 1;
115
 
30017 amit.gupta 116
	private static final String PO_TITLE_STRING = "Alert - Stock Arriving at SD Warehouse";
117
 
25547 amit.gupta 118
	@Autowired
119
	WalletService walletService;
24231 amit.gupta 120
 
23405 amit.gupta 121
	@Autowired
30017 amit.gupta 122
	BrandRegionMappingRepository brandRegionMappingRepository;
123
 
124
	@Autowired
25721 tejbeer 125
	private JavaMailSender googleMailSender;
126
 
127
	@Autowired
23405 amit.gupta 128
	private CookiesProcessor cookiesProcessor;
24231 amit.gupta 129
 
23796 amit.gupta 130
	@Autowired
131
	private UserWalletRepository userWalletRepository;
23785 amit.gupta 132
 
23779 amit.gupta 133
	@Autowired
23796 amit.gupta 134
	private UserRepository userRepository;
135
 
136
	@Autowired
23779 amit.gupta 137
	FofoStoreRepository fofoStoreRepository;
23405 amit.gupta 138
 
139
	@Autowired
23796 amit.gupta 140
	private OrderRepository orderRepository;
141
 
142
	@Autowired
26846 tejbeer 143
	private UserAccountRepository userAccountRepository;
144
 
145
	@Autowired
23405 amit.gupta 146
	private ItemRepository itemRepository;
147
 
148
	@Autowired
23779 amit.gupta 149
	private StockAllocationService stockAllocationService;
150
 
151
	@Autowired
152
	private RetailerService retailerService;
23405 amit.gupta 153
 
154
	@Autowired
155
	private TagListingRepository tagListingRepository;
156
 
157
	@Autowired
158
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
159
 
160
	@Autowired
23796 amit.gupta 161
	private PurchaseRepository purchaseRepository;
162
 
163
	@Autowired
23405 amit.gupta 164
	private MVCResponseSender mvcResponseSender;
165
 
23785 amit.gupta 166
	@Autowired
25721 tejbeer 167
	private FocusedModelRepository focusedModelRepository;
168
 
169
	@Autowired
170
	private MonthlyPlannedRepository monthlyPlannedRepository;
171
 
172
	@Autowired
173
	private FofoOrderRepository fofoOrderRepository;
25732 tejbeer 174
 
25721 tejbeer 175
	@Autowired
25732 tejbeer 176
	private FofoOrderItemRepository fofoOrderItemRepository;
177
 
178
	@Autowired
25721 tejbeer 179
	private PlannedDetailRepository plannedDetailRepository;
25732 tejbeer 180
 
25721 tejbeer 181
	@Autowired
23785 amit.gupta 182
	RoleManager roleManager;
23405 amit.gupta 183
 
25721 tejbeer 184
	@Autowired
27081 tejbeer 185
	PartnerTypeChangeRepository partnerTypeChangeRepository;
186
 
187
	@Autowired
25736 tejbeer 188
	private Mongo mongoClient;
189
 
190
	@Autowired
191
	private InventoryService inventoryService;
192
 
193
	@Autowired
26721 tejbeer 194
	private CsService csService;
25721 tejbeer 195
 
26721 tejbeer 196
	@Autowired
197
	private AuthRepository authRepository;
26846 tejbeer 198
	@Autowired
30017 amit.gupta 199
	WarehouseRepository warehouseRepository;
26846 tejbeer 200
	@Autowired
30017 amit.gupta 201
	private SuggestedPoRepository suggestedPoRepository;
26846 tejbeer 202
 
203
	@Autowired
204
	private NotificationService notificationService;
205
 
27088 tejbeer 206
	@Autowired
207
	private RegionRepository regionRepository;
208
 
209
	@Autowired
210
	private PartnerRegionRepository partnerRegionRepository;
211
 
27768 tejbeer 212
	@Autowired
213
	private SaholicInventoryCISRepository saholicInventoryCISRepository;
214
 
215
	@Autowired
216
	private SaholicInventoryService saholicInventoryService;
217
 
30003 tejbeer 218
	@Autowired
219
	private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
30017 amit.gupta 220
	@Autowired
221
	private SuggestedPoDetailRepository suggestedPoDetailRepository;
30003 tejbeer 222
 
30664 amit.gupta 223
	@Autowired
224
	SaholicCISTableRepository saholicCISTableRepository;
225
 
23779 amit.gupta 226
	@RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
25721 tejbeer 227
	public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,
30664 amit.gupta 228
								 @RequestParam int itemQty, @RequestParam int fofoId) throws Exception {
27088 tejbeer 229
		if (fofoId == 0) {
230
 
231
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
232
			fofoId = loginDetails.getFofoId();
233
 
26990 tejbeer 234
		}
27088 tejbeer 235
 
26082 tejbeer 236
		LocalDate currentMonthDate = LocalDate.now();
237
		MonthlyPlanned monthlyPlanned = null;
25721 tejbeer 238
 
26951 amit.gupta 239
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26082 tejbeer 240
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
26978 tejbeer 241
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
242
			LOGGER.info("monthlyPlanned" + monthlyPlanned);
243
			saveMonthlyPlanned(monthlyPlanned, fofoId, currentMonthDate, catalogId, itemQty);
26082 tejbeer 244
		}
245
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
246
		return "response";
247
	}
248
 
249
	private void saveMonthlyPlanned(MonthlyPlanned monthlyPlanned, int fofoId, LocalDate currentMonthDate,
30664 amit.gupta 250
									int catalogId, int itemQty) {
25721 tejbeer 251
		if (monthlyPlanned == null) {
252
			monthlyPlanned = new MonthlyPlanned();
26082 tejbeer 253
			monthlyPlanned.setFofoId(fofoId);
254
			monthlyPlanned.setYearMonth(currentMonthDate);
25721 tejbeer 255
			monthlyPlannedRepository.persist(monthlyPlanned);
256
			PlannedDetail pd = new PlannedDetail();
257
			pd.setCatalogId(catalogId);
258
			pd.setPlannedId(monthlyPlanned.getId());
259
			pd.setQuantity(itemQty);
260
			pd.setUpdatedTimestamp(LocalDateTime.now());
261
			plannedDetailRepository.persist(pd);
262
 
23786 amit.gupta 263
		} else {
25721 tejbeer 264
			PlannedDetail plannedDetail = plannedDetailRepository.selectByPlannedIdCatalogId(monthlyPlanned.getId(),
265
					catalogId);
266
			if (plannedDetail == null) {
267
				plannedDetail = new PlannedDetail();
268
				plannedDetail.setCatalogId(catalogId);
269
				plannedDetail.setPlannedId(monthlyPlanned.getId());
270
				plannedDetail.setQuantity(itemQty);
271
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
272
				plannedDetailRepository.persist(plannedDetail);
273
			} else if (itemQty == 0) {
274
				plannedDetailRepository.delete(plannedDetail);
275
 
276
			} else {
277
				plannedDetail.setCatalogId(catalogId);
278
				plannedDetail.setQuantity(itemQty);
279
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
280
			}
281
 
23785 amit.gupta 282
		}
25721 tejbeer 283
 
284
	}
285
 
286
	@RequestMapping(value = "/open-indent/confirm", method = RequestMethod.POST)
26748 tejbeer 287
	public String confirmOpenIndent(HttpServletRequest request,
30664 amit.gupta 288
									@RequestParam(required = false, defaultValue = "0") int fofoId, Model model) throws Exception {
26748 tejbeer 289
 
290
		if (fofoId == 0) {
291
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
292
			fofoId = loginDetails.getFofoId();
293
		}
25721 tejbeer 294
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
26748 tejbeer 295
 
26951 amit.gupta 296
		LocalDate currentDate = LocalDate.now();
297
		LocalDate planningMonthDate = null;
26082 tejbeer 298
		MonthlyPlanned monthlyPlanned = null;
26951 amit.gupta 299
		if (currentDate.isAfter(currentDate.withDayOfMonth(PLANNING_OPEN_DAY))) {
300
			planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
301
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
25721 tejbeer 302
 
26082 tejbeer 303
			confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
304
		}
305
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
306
 
307
		return "response";
308
	}
309
 
310
	private void confirmMonthlyPlanned(MonthlyPlanned monthlyPlanned, CustomRetailer customRetailer, int fofoId)
311
			throws Exception {
25721 tejbeer 312
		List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());
313
 
314
		List<PlannedModel> plannedModel = new ArrayList<>();
315
		for (PlannedDetail plannedDetail : plannedDetails) {
316
 
317
			List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());
318
			String itemDesription = items.get(0).getItemDescriptionNoColor();
319
			PlannedModel pm = new PlannedModel();
320
			pm.setItemDescription(itemDesription);
321
			pm.setStoreName(customRetailer.getBusinessName());
322
			pm.setQty(plannedDetail.getQuantity());
26082 tejbeer 323
			pm.setFofoId(fofoId);
25721 tejbeer 324
			plannedModel.add(pm);
325
			LOGGER.info("plannedModel" + plannedModel);
326
 
23785 amit.gupta 327
		}
26978 tejbeer 328
		List<String> ccemails = new ArrayList<>();
329
		LOGGER.info("ccemails" + ccemails);
330
		Map<EscalationType, String> emailEsclationType = csService.getAuthUserAndEsclationTypeByPartnerId(fofoId);
331
		LOGGER.info("emailEsclationType" + emailEsclationType);
332
		ccemails.add(emailEsclationType.get(EscalationType.L1));
333
		ccemails.add(emailEsclationType.get(EscalationType.L2));
334
		LOGGER.info("ccemails" + ccemails);
335
		List<String> bccemails = new ArrayList<>();
336
		bccemails.add(emailEsclationType.get(EscalationType.L3));
337
		LOGGER.info("bccemails" + bccemails);
25721 tejbeer 338
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
339
				Arrays.asList("Partner Id", "Partner Name", "Model Name", "Qty"),
340
				plannedModel.stream()
341
						.map(x -> Arrays.asList(x.getFofoId(), x.getStoreName(), x.getItemDescription(), x.getQty()))
342
						.collect(Collectors.toList()));
343
		LOGGER.info("baos" + baos);
30664 amit.gupta 344
		Utils.sendMailWithAttachments(googleMailSender, new String[]{customRetailer.getEmail()},
26978 tejbeer 345
				ccemails.toArray(new String[ccemails.size()]), bccemails.toArray(new String[bccemails.size()]),
25721 tejbeer 346
				"Planned Indent", "PFA",
30664 amit.gupta 347
				new Attachment[]{new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())),});
25721 tejbeer 348
 
23405 amit.gupta 349
	}
350
 
24231 amit.gupta 351
	@RequestMapping(value = "/indent/download", method = RequestMethod.GET)
352
	public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,
30664 amit.gupta 353
															@RequestParam(required = false, defaultValue = "0") int fofoId,
354
															@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 355
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
356
		Set<Integer> roleIds = loginDetails.getRoleIds();
24231 amit.gupta 357
		LOGGER.info("Counter size is {}", counterSize);
358
		LOGGER.info("Fofo Id is {}", fofoId);
30426 tejbeer 359
 
25721 tejbeer 360
		if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {
24231 amit.gupta 361
			List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
362
					.collect(Collectors.toList());
30426 tejbeer 363
			Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
364
			Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x))
365
					.filter(x -> x != null).collect(Collectors.toList()).stream()
366
					.collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
24232 amit.gupta 367
			List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,
368
					true);
369
			Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream()
370
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
23405 amit.gupta 371
 
24232 amit.gupta 372
			Map<String, Integer> catalogUserQtyMap = new HashMap<>();
25702 amit.gupta 373
			currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {
24232 amit.gupta 374
				int retailerId = x.getFofoId();
375
				int catalogId;
376
				try {
377
					catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();
378
					String key = catalogId + "-" + retailerId;
379
					if (!catalogUserQtyMap.containsKey(key)) {
380
						catalogUserQtyMap.put(key, 0);
381
					}
382
					catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());
383
				} catch (ProfitMandiBusinessException e) {
384
					// TODO Auto-generated catch block
385
					throw new RuntimeException(e);
24231 amit.gupta 386
				}
387
			});
23779 amit.gupta 388
 
24231 amit.gupta 389
			List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);
24232 amit.gupta 390
			Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {
391
				try {
392
					return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"
393
							+ x.getRetailerId();
394
				} catch (ProfitMandiBusinessException e) {
395
					// TODO Auto-generated catch block
396
					return "";
397
				}
398
			}, Collectors.summingInt(x -> x.getLineItem().getQuantity())));
23779 amit.gupta 399
 
24232 amit.gupta 400
			Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();
401
 
402
			List<TagListing> tagListings = tagListingRepository.selectAll(true);
403
			Iterator<TagListing> iterator = tagListings.iterator();
24231 amit.gupta 404
			while (iterator.hasNext()) {
405
				TagListing tagListing = iterator.next();
406
				Item item = itemRepository.selectById(tagListing.getItemId());
24232 amit.gupta 407
				int catalogId = item.getCatalogItemId();
24231 amit.gupta 408
				if (item.getCategoryId() != 10006) {
409
					continue;
410
				}
23779 amit.gupta 411
 
24232 amit.gupta 412
				int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)
413
						? modelStockAllocationMap.get(catalogId)
414
						: 0;
415
				for (int retailerId : fofoIds) {
416
					String key = catalogId + "-" + retailerId;
417
					if (catalogListingMap.containsKey(key)) {
418
						continue;
24231 amit.gupta 419
					}
24232 amit.gupta 420
					int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;
421
					int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;
422
					if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {
423
						continue;
424
					}
425
					CatalogListingModel catalogListingModel = new CatalogListingModel();
426
					catalogListingModel.setFofoId(retailerId);
427
					catalogListingModel.setModelName(item.getModelName());
428
					catalogListingModel.setModelNumber(item.getModelNumber());
429
					catalogListingModel.setCatalogId(catalogId);
430
					catalogListingModel.setDp(tagListing.getSellingPrice());
431
					catalogListingModel.setMop(tagListing.getMop());
432
					catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
433
					catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);
434
					catalogListingModel.setInTransitQuantity(catalogInTransit);
435
					catalogListingModel
436
							.setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);
24233 amit.gupta 437
					catalogListingModel.setStockInHand(catalogInStock);
24232 amit.gupta 438
					catalogListingModel.setBrand(item.getBrand());
439
					catalogListingModel.setModelName(item.getModelName());
440
					catalogListingModel.setModelNumber(item.getModelNumber());
441
					catalogListingModel.setCategoryId(item.getCategoryId());
442
					catalogListingMap.put(key, catalogListingModel);
23405 amit.gupta 443
				}
444
			}
25853 amit.gupta 445
			List<List<?>> listOfRows = new ArrayList<>();
24231 amit.gupta 446
			for (CatalogListingModel clm : catalogListingMap.values()) {
30426 tejbeer 447
				CustomRetailer cr = crm.get(clm.getFofoId());
24349 amit.gupta 448
				listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),
449
						clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),
450
						clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),
451
						clm.getToBeOrdered()));
24231 amit.gupta 452
			}
24349 amit.gupta 453
			ByteArrayOutputStream baos = FileUtil
454
					.getCSVByteStream(
455
							Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number",
456
									"DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
457
							listOfRows);
24231 amit.gupta 458
			HttpHeaders headers = new HttpHeaders();
459
			headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
460
			headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
24232 amit.gupta 461
			return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
462
					HttpStatus.OK);
23405 amit.gupta 463
		}
24231 amit.gupta 464
		return null;
24232 amit.gupta 465
 
23405 amit.gupta 466
	}
467
 
24349 amit.gupta 468
	@RequestMapping(value = "/itemsByCatalogId")
469
	public String getItemsByCatalogId(HttpServletRequest request, Model model,
30664 amit.gupta 470
									  @RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
25378 tejbeer 471
			throws ProfitMandiBusinessException {
24410 amit.gupta 472
		if (catalogId == 0) {
473
			catalogId = itemRepository.selectById(itemId).getCatalogItemId();
474
		}
24349 amit.gupta 475
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
24414 amit.gupta 476
		LOGGER.info("Items {}", items);
25378 tejbeer 477
		Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
478
				.collect(Collectors.toMap(Item::getId, Item::getColor));
24413 amit.gupta 479
		Map<Integer, TagListing> tagsMap = tagListingRepository
480
				.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
25378 tejbeer 481
				.stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
24414 amit.gupta 482
		LOGGER.info("Items color map {}", itemsColorMap);
24349 amit.gupta 483
		JSONArray response = new JSONArray();
24413 amit.gupta 484
		itemsColorMap.keySet().stream().forEach(x -> {
25378 tejbeer 485
			response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",
486
					tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));
24349 amit.gupta 487
		});
488
		model.addAttribute("response", response.toString());
489
		return "response";
24410 amit.gupta 490
 
24349 amit.gupta 491
	}
492
 
28055 tejbeer 493
	@RequestMapping(value = "/hotdealsitemsByCatalogId")
494
	public String getHotdealsitemsByCatalogId(HttpServletRequest request, Model model,
30664 amit.gupta 495
											  @RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
28055 tejbeer 496
			throws ProfitMandiBusinessException {
497
		if (catalogId == 0) {
498
			catalogId = itemRepository.selectById(itemId).getCatalogItemId();
499
		}
500
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
501
		LOGGER.info("Items {}", items);
502
		Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
503
				.collect(Collectors.toMap(Item::getId, Item::getColor));
504
		Map<Integer, TagListing> tagsMap = tagListingRepository
505
				.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
506
				.stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
507
		LOGGER.info("Items color map {}", itemsColorMap);
508
		JSONArray response = new JSONArray();
509
		itemsColorMap.keySet().stream().forEach(x -> {
510
			response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("hotDeals",
511
					tagsMap.get(x) == null ? false : tagsMap.get(x).isHotDeals()));
512
		});
513
		model.addAttribute("response", response.toString());
514
		return "response";
515
 
516
	}
517
 
30664 amit.gupta 518
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
519
		int orderRemovedCount = 0;
520
		Iterator<Order> orderIterator = lastOrdersList.iterator();
521
		while (orderIterator.hasNext()) {
522
			Order o = orderIterator.next();
523
			if (o.getInvoiceNumber() != null) {
524
				try {
525
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
526
					orderIterator.remove();
527
					orderRemovedCount++;
528
				} catch (Exception e) {
529
 
530
				}
531
			}
532
		}
533
		LOGGER.info("Order removed count is {}", orderRemovedCount);
534
		return lastOrdersList;
535
	}
536
 
537
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
538
	public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
539
			throws Exception {
540
		JSONArray jsonArray = new JSONArray(jsonArrayString);
541
		for (int i = 0; i < jsonArray.length(); i++) {
542
			JSONObject obj = jsonArray.getJSONObject(i);
543
 
544
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
545
			if (tl == null) {
546
				continue;
547
			} else {
548
				tl.setActive(obj.getBoolean("active"));
549
				tagListingRepository.persist(tl);
550
			}
551
		}
552
		model.addAttribute("response", true);
553
		return "response";
554
	}
555
 
556
	@RequestMapping(value = "/indent/confirm-hotdeals-pause", method = RequestMethod.POST)
557
	public String hotdealUpdate(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
558
			throws Exception {
559
		JSONArray jsonArray = new JSONArray(jsonArrayString);
560
		for (int i = 0; i < jsonArray.length(); i++) {
561
			JSONObject obj = jsonArray.getJSONObject(i);
562
 
563
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
564
			if (tl == null) {
565
				continue;
566
			} else {
567
				tl.setHotDeals(obj.getBoolean("hotDeals"));
568
				tagListingRepository.persist(tl);
569
			}
570
		}
571
		model.addAttribute("response", true);
572
		return "response";
573
	}
574
 
575
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
576
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
577
		boolean success = false;
578
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
579
		int fofoId = loginDetails.getFofoId();
580
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
581
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
582
		Client userClient = new UserClient().getClient();
583
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
584
 
585
		if (totalAmount > 0) {
586
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
587
			User user = userRepository.selectById(loginDetails.getFofoId());
588
			userClient = new UserClient().getClient();
589
			LOGGER.info("Setting wallet amount in cart");
590
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
591
					7890, OrderSource.WEBSITE.getValue(), true);
592
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
593
			createPayment(user, totalAmount, transactionId);
594
			TransactionService.Client transactionClient = new TransactionClient().getClient();
595
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
596
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
597
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
598
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
599
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
600
			transactionClient = new TransactionClient().getClient();
601
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
602
			try {
603
				transactionClient.enqueueTransactionInfoEmail(transactionId);
604
			} catch (Exception e1) {
605
				e1.printStackTrace();
606
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
607
			}
608
			resetCart(transactionClient.getTransaction(transactionId));
609
		}
610
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
611
		return "response";
612
	}
613
 
614
	private void createPayment(User user, double totalAmount, long transactionId)
615
			throws NumberFormatException, PaymentException, TException {
616
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
617
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
618
		paymentAttributes.add(new Attribute("payMethod", "7890"));
619
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
620
				false);
621
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
622
				PaymentStatus.SUCCESS, null, paymentAttributes);
623
	}
624
 
23405 amit.gupta 625
	@RequestMapping(value = "/indent/loadIndent")
23785 amit.gupta 626
	public String loadOpenIndent(HttpServletRequest request, Model model,
30664 amit.gupta 627
								 @RequestParam(required = false, defaultValue = "0") int fofoId,
628
								 @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 629
 
630
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
631
		Set<Integer> roleIds = loginDetails.getRoleIds();
23785 amit.gupta 632
		LOGGER.info("Counter size is {}", counterSize);
633
		LOGGER.info("Fofo Id is {}", fofoId);
25736 tejbeer 634
		boolean isAdmin = roleManager.isAdmin(roleIds);
25796 tejbeer 635
 
25797 tejbeer 636
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
637
				.collect(Collectors.toList());
638
 
25796 tejbeer 639
		Map<String, Object> equalsMap = new HashMap<>();
640
		equalsMap.put("categoryId", 10006);
25797 tejbeer 641
		equalsMap.put("brand", brands);
25796 tejbeer 642
		Map<String, List<?>> notEqualsMap = new HashMap<>();
643
 
644
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
645
		Map<Integer, Integer> currentStockMap;
646
 
25721 tejbeer 647
		if (!isAdmin && fofoId == 0) {
23786 amit.gupta 648
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
25796 tejbeer 649
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
650
			equalsStockJoinMap.put("fofoId", fofoId);
651
			currentStockMap = itemRepository
25800 tejbeer 652
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
653
							equalsStockJoinMap, notEqualsJoinMap, "availability")
25796 tejbeer 654
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25797 tejbeer 655
			LOGGER.info("currentStock");
23786 amit.gupta 656
		} else {
657
			if (fofoId == 0) {
25796 tejbeer 658
 
659
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
660
				equalsStockJoinMap.put("fofoId", fofoId);
661
 
662
				currentStockMap = itemRepository
25800 tejbeer 663
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 664
								equalsStockJoinMap, notEqualsJoinMap, "availability")
665
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
666
 
23779 amit.gupta 667
			} else {
25796 tejbeer 668
 
669
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
670
				equalsStockJoinMap.put("fofoId", fofoId);
671
 
672
				currentStockMap = itemRepository
25800 tejbeer 673
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 674
								equalsStockJoinMap, notEqualsJoinMap, "availability")
675
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
676
 
23405 amit.gupta 677
			}
23786 amit.gupta 678
		}
25796 tejbeer 679
 
680
		LOGGER.info("currentStock" + currentStockMap);
25797 tejbeer 681
 
23796 amit.gupta 682
		Map<Integer, Integer> itemsInTransit = null;
23855 amit.gupta 683
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
25702 amit.gupta 684
		if (!isAdmin) {
23786 amit.gupta 685
			tagListings = new ArrayList<>(tagListings);
28055 tejbeer 686
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
687
					OrderRepository.validOrderStatusList);
23796 amit.gupta 688
			inTransitOrders = this.filterValidOrders(inTransitOrders);
689
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
690
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
691
		} else {
692
			itemsInTransit = new HashMap<>();
23786 amit.gupta 693
		}
25797 tejbeer 694
 
23796 amit.gupta 695
		int totalPcs = 0;
25797 tejbeer 696
 
23796 amit.gupta 697
		float totalAmount = 0;
24231 amit.gupta 698
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
27088 tejbeer 699
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
700
				.collect(Collectors.toList());
25796 tejbeer 701
 
27088 tejbeer 702
		LOGGER.info("regionIds" + regionIds);
703
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
704
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
705
		LOGGER.info("focusedModelMap" + focusedModelMap);
26956 amit.gupta 706
		LocalDate planningMonthDate = null;
26082 tejbeer 707
		MonthlyPlanned monthlyPlanned = null;
26176 tejbeer 708
		List<Integer> fofoOrderIds = null;
26082 tejbeer 709
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 710
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26956 amit.gupta 711
			planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
712
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
26082 tejbeer 713
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
26176 tejbeer 714
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
30664 amit.gupta 715
							LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
26176 tejbeer 716
					.collect(Collectors.toList());
26082 tejbeer 717
 
718
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 719
		} else {
26956 amit.gupta 720
			planningMonthDate = LocalDate.now().withDayOfMonth(1);
26176 tejbeer 721
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
26956 amit.gupta 722
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
723
			model.addAttribute("planningMonth", planningMonthDate.getMonth());
26176 tejbeer 724
			model.addAttribute("mtd", true);
26131 tejbeer 725
			model.addAttribute("freezed", true);
26176 tejbeer 726
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
30664 amit.gupta 727
							curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
26176 tejbeer 728
					.collect(Collectors.toList());
26082 tejbeer 729
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
26978 tejbeer 730
		}
26082 tejbeer 731
 
25721 tejbeer 732
		Map<Integer, Integer> plannedDetailMap = null;
733
		if (monthlyPlanned != null) {
734
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
735
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
736
 
737
		}
25797 tejbeer 738
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
26176 tejbeer 739
 
25796 tejbeer 740
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
741
		Map<String, Object> equalsJoinMap = new HashMap<>();
26618 tejbeer 742
 
25796 tejbeer 743
		equalsJoinMap.put("orderId", fofoOrderIds);
26618 tejbeer 744
		Map<Integer, Integer> last15daysMap = null;
26748 tejbeer 745
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
24231 amit.gupta 746
 
26618 tejbeer 747
			last15daysMap = itemRepository
748
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
749
							notEqualsJoinMap, "quantity")
750
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
751
		}
25796 tejbeer 752
		LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 753
 
25796 tejbeer 754
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
755
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
756
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
757
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
758
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
25797 tejbeer 759
		LOGGER.info("catalogIdItemMap");
24231 amit.gupta 760
 
25796 tejbeer 761
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
25797 tejbeer 762
		equalsItemJoinMap.put("active", 1);
28897 amit.gupta 763
		List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
25800 tejbeer 764
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
25797 tejbeer 765
		LOGGER.info("tagListingCatalogIds");
28897 amit.gupta 766
		for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
25796 tejbeer 767
			int catalogId = catalogIdAggregateValue.getCatalogId();
768
			Item item = catalogIdItemMap.get(catalogId).get(0);
769
			TagListing tagListing = taglistingMap.get(item.getId());
24231 amit.gupta 770
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
771
			if (!catalogListingMap.containsKey(catalogId)) {
772
				catalogListingModel = new CatalogListingModel();
773
				catalogListingModel.setCatalogId(catalogId);
774
				catalogListingModel.setDp(tagListing.getSellingPrice());
775
				catalogListingModel.setMop(tagListing.getMop());
776
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
25721 tejbeer 777
				if (plannedDetailMap != null) {
778
 
779
					Integer quantity = plannedDetailMap.get(catalogId);
780
					if (quantity != null) {
781
						catalogListingModel.setAllocatedQuantity(quantity);
782
					}
783
				}
784
 
25796 tejbeer 785
				if (last15daysMap != null) {
786
					Integer last15DaysSale = last15daysMap.get(catalogId);
787
 
25721 tejbeer 788
					if (last15DaysSale != null) {
789
						catalogListingModel.setLast15DaysSale(last15DaysSale);
790
					} else {
791
						catalogListingModel.setLast15DaysSale(0);
792
					}
793
				} else {
794
					catalogListingModel.setLast15DaysSale(0);
795
				}
796
 
24231 amit.gupta 797
				catalogListingModel.setBrand(item.getBrand());
798
				if (item.getCategoryId() == 10006) {
799
					catalogListingModel.setCategoryId(item.getCategoryId());
800
				}
25721 tejbeer 801
 
802
				FocusedModel fm = focusedModelMap.get(catalogId);
803
				if (fm != null) {
804
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
805
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
806
 
807
				} else {
808
					catalogListingModel.setRecommendedQty(0);
809
					catalogListingModel.setMinimumQty(0);
810
				}
811
 
24231 amit.gupta 812
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 813
 
24231 amit.gupta 814
			}
25736 tejbeer 815
			int itemAvailability = 0;
25796 tejbeer 816
			if (currentStockMap != null) {
817
				Integer qty = currentStockMap.get(catalogId);
25736 tejbeer 818
				itemAvailability = qty == null ? 0 : qty;
819
				catalogListingModel.setStockInHand(itemAvailability);
820
			} else {
821
				catalogListingModel.setStockInHand(0);
822
			}
24231 amit.gupta 823
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
824
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
825
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
26179 tejbeer 826
			if (plannedDetailMap != null) {
26177 tejbeer 827
				if (plannedDetailMap.get(catalogId) != null) {
24231 amit.gupta 828
 
26177 tejbeer 829
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
830
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
831
					LOGGER.info("remaning" + remaining);
26176 tejbeer 832
 
26177 tejbeer 833
					if (remaining != 0) {
834
						catalogListingModel.setRemaining(remaining);
835
					} else {
836
						catalogListingModel.setRemaining(0);
837
					}
26176 tejbeer 838
				}
839
			}
23786 amit.gupta 840
		}
25721 tejbeer 841
 
26963 amit.gupta 842
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
23786 amit.gupta 843
		if (fofoId > 0) {
844
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
845
			model.addAttribute("retailerName",
846
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
847
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
848
			model.addAttribute("retailerId", customRetailer.getPartnerId());
849
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 850
		} else {
23786 amit.gupta 851
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 852
		}
23786 amit.gupta 853
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 854
 
855
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
856
 
25721 tejbeer 857
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 858
				Comparator.reverseOrder());
25721 tejbeer 859
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25796 tejbeer 860
		model.addAttribute("catalogTagListings",
861
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 862
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
26177 tejbeer 863
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26956 amit.gupta 864
		model.addAttribute("previousPlanningMonth", planningMonthDate.minusMonths(1).getMonth());
865
		model.addAttribute("currentPlanningMonth", planningMonthDate.getMonth());
26131 tejbeer 866
 
23786 amit.gupta 867
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 868
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 869
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 870
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 871
		return "open-indent";
25796 tejbeer 872
 
23405 amit.gupta 873
	}
23796 amit.gupta 874
 
30664 amit.gupta 875
	private long resetCart(Transaction transaction) {
876
		long sum = 0;
877
		Map<Long, Double> items = new HashMap<Long, Double>();
878
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
879
			sum += order.getGvAmount();
880
			for (LineItem lineitem : order.getLineitems()) {
881
				Long itemId = lineitem.getItem_id();
882
				Double quantity = items.get(itemId);
883
				if (quantity == null) {
884
					quantity = lineitem.getQuantity();
885
				} else {
886
					quantity = quantity + lineitem.getQuantity();
30017 amit.gupta 887
				}
30664 amit.gupta 888
				items.put(itemId, quantity);
30017 amit.gupta 889
			}
890
		}
891
 
30664 amit.gupta 892
		LOGGER.debug("Items to reset in cart are: " + items);
30017 amit.gupta 893
 
30664 amit.gupta 894
		try {
895
			Client userClient = new UserClient().getClient();
896
			userClient.resetCart(transaction.getShoppingCartid(), items);
897
		} catch (TException e) {
898
			LOGGER.error("Error while updating information in payment database.", e);
899
		} catch (ShoppingCartException e) {
900
			LOGGER.error("Error while reseting the cart in cart database.", e);
901
		} catch (Exception e) {
902
			LOGGER.error("Unexpected exception", e);
30017 amit.gupta 903
		}
30664 amit.gupta 904
		return sum;
30017 amit.gupta 905
	}
906
 
30664 amit.gupta 907
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
908
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
909
		/*
910
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
911
		 * currentInventorySnapshots = currentInventorySnapshotRepository
912
		 * .selectItemsStock(fofoId); itemCisMap =
913
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
914
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
915
		 * List<StockAllocationModel> stockAllocationList =
916
		 * stockAllocationService.getStockAllocation(fofoId, true);
917
		 *
918
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
919
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
920
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
921
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
922
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
923
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
924
		 * validOrderStatusList); inTransitOrders =
925
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
926
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
927
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
928
		 * x.getLineItem().getQuantity())));
929
		 *
930
		 * Iterator<TagListing> iterator = tagListings.iterator();
931
		 *
932
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
933
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
934
		 * tagListing.getAllocatedQuantity()); if
935
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
936
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
937
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
938
		 * itemCisMap.get(tagListing.getItemId());
939
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
940
		 * itemIdAvailability.getAvailability()); StockAllocationModel
941
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
942
		 *
943
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
944
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
945
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
946
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
947
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
948
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
949
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
950
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
951
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
952
		 */
953
		return itemQuantities;
30017 amit.gupta 954
 
955
	}
956
 
26131 tejbeer 957
	@RequestMapping(value = "/indent/loadIndentPreviousMonth")
958
	public String previousMonthLoadOpenIndent(HttpServletRequest request, Model model,
30664 amit.gupta 959
											  @RequestParam(required = false, defaultValue = "0") int fofoId,
960
											  @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
26956 amit.gupta 961
		LocalDate planMonthStart = null;
962
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
963
			planMonthStart = LocalDate.now().plusMonths(1).withDayOfMonth(1);
964
		} else {
965
			planMonthStart = LocalDate.now().withDayOfMonth(1);
966
		}
26131 tejbeer 967
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
968
		Set<Integer> roleIds = loginDetails.getRoleIds();
969
		LOGGER.info("Counter size is {}", counterSize);
970
		LOGGER.info("Fofo Id is {}", fofoId);
971
		boolean isAdmin = roleManager.isAdmin(roleIds);
972
 
973
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
974
				.collect(Collectors.toList());
975
 
976
		Map<String, Object> equalsMap = new HashMap<>();
977
		equalsMap.put("categoryId", 10006);
978
		equalsMap.put("brand", brands);
979
		Map<String, List<?>> notEqualsMap = new HashMap<>();
980
 
981
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
982
		Map<Integer, Integer> currentStockMap;
983
 
984
		if (!isAdmin && fofoId == 0) {
985
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
986
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
987
			equalsStockJoinMap.put("fofoId", fofoId);
988
			currentStockMap = itemRepository
989
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
990
							equalsStockJoinMap, notEqualsJoinMap, "availability")
991
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
992
			LOGGER.info("currentStock");
993
		} else {
994
			if (fofoId == 0) {
995
 
996
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
997
				equalsStockJoinMap.put("fofoId", fofoId);
998
 
999
				currentStockMap = itemRepository
1000
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1001
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1002
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1003
 
1004
			} else {
1005
 
1006
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1007
				equalsStockJoinMap.put("fofoId", fofoId);
1008
 
1009
				currentStockMap = itemRepository
1010
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1011
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1012
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1013
 
1014
			}
1015
		}
1016
 
1017
		LOGGER.info("currentStock" + currentStockMap);
1018
 
1019
		Map<Integer, Integer> itemsInTransit = null;
1020
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
1021
		if (!isAdmin) {
1022
			tagListings = new ArrayList<>(tagListings);
28055 tejbeer 1023
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
1024
					OrderRepository.validOrderStatusList);
26131 tejbeer 1025
			inTransitOrders = this.filterValidOrders(inTransitOrders);
1026
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1027
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1028
		} else {
1029
			itemsInTransit = new HashMap<>();
1030
		}
1031
 
1032
		int totalPcs = 0;
1033
 
1034
		float totalAmount = 0;
1035
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
1036
 
27088 tejbeer 1037
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1038
				.collect(Collectors.toList());
26131 tejbeer 1039
 
27088 tejbeer 1040
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
1041
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
1042
 
26978 tejbeer 1043
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId,
1044
				planMonthStart.minusMonths(1));
26956 amit.gupta 1045
		model.addAttribute("planningMonth", planMonthStart.minusMonths(1).getMonth());
1046
		model.addAttribute("previousPlanningMonth", planMonthStart.minusMonths(1).getMonth());
1047
		model.addAttribute("currentPlanningMonth", planMonthStart.getMonth());
26131 tejbeer 1048
 
1049
		Map<Integer, Integer> plannedDetailMap = null;
1050
		if (monthlyPlanned != null) {
1051
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1052
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
1053
 
1054
		}
1055
 
1056
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
1057
		List<Integer> fofoOrderIds = fofoOrderRepository
1058
				.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
26978 tejbeer 1059
						planMonthStart.minusMonths(1).atStartOfDay(), planMonthStart.atStartOfDay())
26131 tejbeer 1060
				.stream().map(x -> x.getId()).collect(Collectors.toList());
26721 tejbeer 1061
 
26131 tejbeer 1062
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
1063
		Map<String, Object> equalsJoinMap = new HashMap<>();
1064
		equalsJoinMap.put("orderId", fofoOrderIds);
26721 tejbeer 1065
		Map<Integer, Integer> lastMonthSaleMap = null;
1066
		if (!fofoOrderIds.isEmpty()) {
1067
			lastMonthSaleMap = itemRepository
1068
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1069
							notEqualsJoinMap, "quantity")
1070
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1071
		}
26131 tejbeer 1072
		LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);
1073
 
1074
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
1075
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1076
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1077
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1078
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1079
		LOGGER.info("catalogIdItemMap");
1080
 
1081
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
1082
		equalsItemJoinMap.put("active", 1);
28897 amit.gupta 1083
		List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
26131 tejbeer 1084
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
1085
		LOGGER.info("tagListingCatalogIds");
28897 amit.gupta 1086
		for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
26131 tejbeer 1087
			int catalogId = catalogIdAggregateValue.getCatalogId();
1088
			Item item = catalogIdItemMap.get(catalogId).get(0);
1089
			TagListing tagListing = taglistingMap.get(item.getId());
1090
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1091
			if (!catalogListingMap.containsKey(catalogId)) {
1092
				catalogListingModel = new CatalogListingModel();
1093
				catalogListingModel.setCatalogId(catalogId);
1094
				catalogListingModel.setDp(tagListing.getSellingPrice());
1095
				catalogListingModel.setMop(tagListing.getMop());
1096
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1097
				if (plannedDetailMap != null) {
1098
 
1099
					Integer quantity = plannedDetailMap.get(catalogId);
1100
					if (quantity != null) {
1101
						catalogListingModel.setAllocatedQuantity(quantity);
1102
					}
1103
				}
1104
 
1105
				if (lastMonthSaleMap != null) {
1106
					Integer lastMonthSale = lastMonthSaleMap.get(catalogId);
1107
 
1108
					if (lastMonthSale != null) {
1109
						catalogListingModel.setLastMonthSaleMap(lastMonthSale);
1110
					} else {
1111
						catalogListingModel.setLastMonthSaleMap(0);
1112
					}
1113
				} else {
1114
					catalogListingModel.setLast15DaysSale(0);
1115
				}
1116
 
1117
				catalogListingModel.setBrand(item.getBrand());
1118
				if (item.getCategoryId() == 10006) {
1119
					catalogListingModel.setCategoryId(item.getCategoryId());
1120
				}
1121
 
1122
				FocusedModel fm = focusedModelMap.get(catalogId);
1123
				if (fm != null) {
1124
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1125
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
1126
 
1127
				} else {
1128
					catalogListingModel.setRecommendedQty(0);
1129
					catalogListingModel.setMinimumQty(0);
1130
				}
1131
 
1132
				catalogListingMap.put(catalogId, catalogListingModel);
1133
 
1134
			}
1135
			int itemAvailability = 0;
1136
			if (currentStockMap != null) {
1137
				Integer qty = currentStockMap.get(catalogId);
1138
				itemAvailability = qty == null ? 0 : qty;
1139
				catalogListingModel.setStockInHand(itemAvailability);
1140
			} else {
1141
				catalogListingModel.setStockInHand(0);
1142
			}
1143
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
1144
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1145
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
1146
 
1147
		}
1148
 
26963 amit.gupta 1149
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26131 tejbeer 1150
		if (fofoId > 0) {
1151
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1152
			model.addAttribute("retailerName",
1153
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1154
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1155
			model.addAttribute("retailerId", customRetailer.getPartnerId());
1156
			model.addAttribute("counterSize", fs.getCounterSize().toString());
1157
		} else {
1158
			model.addAttribute("counterSize", counterSize.toString());
1159
		}
1160
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
1161
 
1162
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
1163
 
1164
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1165
				Comparator.reverseOrder());
1166
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
1167
		model.addAttribute("catalogTagListings",
1168
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1169
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
1170
		model.addAttribute("previousMonth", true);
1171
		model.addAttribute("freezed", true);
26177 tejbeer 1172
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26131 tejbeer 1173
		model.addAttribute("customRetailers", customRetailers);
1174
		model.addAttribute("totalAmount", totalAmount);
1175
		model.addAttribute("monthlyPlanned", monthlyPlanned);
1176
		model.addAttribute("totalPcs", totalPcs);
1177
		return "open-indent";
1178
 
1179
	}
1180
 
30664 amit.gupta 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));
23796 amit.gupta 1186
		}
1187
 
30664 amit.gupta 1188
		return itemMap;
1189
	}
25378 tejbeer 1190
 
30664 amit.gupta 1191
	private Map<Integer, Region> getRegionByRegionId(List<FocusedModel> focusedModels) {
1192
		Map<Integer, Region> regionMap = new HashMap<>();
1193
		for (FocusedModel focusedModel : focusedModels) {
1194
			Region region = regionRepository.selectById(focusedModel.getRegionId());
1195
			regionMap.put(region.getId(), region);
24406 amit.gupta 1196
		}
24231 amit.gupta 1197
 
30664 amit.gupta 1198
		return regionMap;
23796 amit.gupta 1199
	}
24231 amit.gupta 1200
 
25721 tejbeer 1201
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
1202
	public String getFocusedModel(HttpServletRequest request,
30664 amit.gupta 1203
								  @RequestParam(name = "offset", defaultValue = "0") int offset,
1204
								  @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
25721 tejbeer 1205
			throws ProfitMandiBusinessException {
25736 tejbeer 1206
 
1207
		long size = 0;
25721 tejbeer 1208
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
27081 tejbeer 1209
 
25736 tejbeer 1210
		size = focusedModelRepository.selectAllCount();
1211
		if (!focusedModels.isEmpty()) {
1212
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
27088 tejbeer 1213
			Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25721 tejbeer 1214
 
27088 tejbeer 1215
			LOGGER.info("regionMap" + regionMap);
25736 tejbeer 1216
			model.addAttribute("focusedModels", focusedModels);
1217
			model.addAttribute("itemMap", itemMap);
27088 tejbeer 1218
			model.addAttribute("regionMap", regionMap);
25736 tejbeer 1219
			model.addAttribute("start", offset + 1);
1220
			model.addAttribute("size", size);
1221
			model.addAttribute("url", "/getPaginatedFocusedModel");
1222
 
1223
			if (focusedModels.size() < limit) {
1224
				model.addAttribute("end", offset + focusedModels.size());
1225
			} else {
1226
				model.addAttribute("end", offset + limit);
1227
			}
1228
		} else {
1229
 
1230
			model.addAttribute("walletRequest", focusedModels);
1231
			model.addAttribute("size", size);
1232
 
1233
		}
1234
 
27088 tejbeer 1235
		List<Region> regions = regionRepository.selectAll();
27081 tejbeer 1236
 
27088 tejbeer 1237
		model.addAttribute("regions", regions);
1238
 
25721 tejbeer 1239
		return "focused_model";
1240
	}
1241
 
25736 tejbeer 1242
	@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
1243
	public String getPaginatedFocusedModel(HttpServletRequest request,
30664 amit.gupta 1244
										   @RequestParam(name = "offset", defaultValue = "0") int offset,
1245
										   @RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
25736 tejbeer 1246
			throws ProfitMandiBusinessException {
1247
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
1248
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
1249
 
1250
		if (!focusedModels.isEmpty()) {
1251
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
27088 tejbeer 1252
			Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25736 tejbeer 1253
			model.addAttribute("focusedModels", focusedModels);
1254
			model.addAttribute("itemMap", itemMap);
27088 tejbeer 1255
			model.addAttribute("regionMap", regionMap);
25736 tejbeer 1256
			model.addAttribute("url", "/getPaginatedFocusedModel");
1257
		} else {
1258
			model.addAttribute("focusedModels", focusedModels);
1259
 
1260
		}
27081 tejbeer 1261
 
27088 tejbeer 1262
		List<Region> regions = regionRepository.selectAll();
1263
 
1264
		model.addAttribute("regions", regions);
25736 tejbeer 1265
		return "focused-model-paginated";
1266
	}
1267
 
25798 tejbeer 1268
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
1269
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 1270
 
25798 tejbeer 1271
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
1272
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
1273
 
1274
		mobileBrands.stream().forEach(x -> {
1275
			String brand = (String) x.get("name");
1276
			if (brandStockPricesMap.containsKey(brand)) {
1277
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
1278
				brandStockPrice.setBrandUrl((String) x.get("url"));
1279
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
1280
				brandStockPrices.add(brandStockPrice);
1281
			}
1282
		});
1283
 
1284
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
1285
				.collect(Collectors.toList());
1286
	}
1287
 
26721 tejbeer 1288
	@RequestMapping(value = "/getPartnerAllocation")
1289
	public String getPartnerAllocation(HttpServletRequest request, Model model) throws Exception {
1290
 
1291
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1292
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1293
 
1294
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1295
 
1296
		List<Integer> fofoIds = pp.get(authUser.getId());
1297
 
30426 tejbeer 1298
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1299
		Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1300
				.collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
26721 tejbeer 1301
		Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
1302
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1303
 
30426 tejbeer 1304
		model.addAttribute("customRetailersMap", crm);
26721 tejbeer 1305
		model.addAttribute("fofoStoreMap", fofoStoreMap);
1306
		return "partners_allocation";
1307
 
1308
	}
1309
 
26846 tejbeer 1310
	@RequestMapping(value = "/partnerPendingOrder")
1311
	public String partnerPendingOrder(HttpServletRequest request, Model model) throws Exception {
1312
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1313
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1314
 
1315
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1316
 
1317
		List<Integer> fofoIds = pp.get(authUser.getId());
30426 tejbeer 1318
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
1319
		Map<Integer, CustomRetailer> crm = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1320
				.collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
26846 tejbeer 1321
 
30426 tejbeer 1322
		model.addAttribute("customRetailersMap", crm);
26846 tejbeer 1323
 
1324
		return "partner-po";
1325
 
1326
	}
1327
 
30664 amit.gupta 1328
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
1329
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId,
1330
							   @RequestParam(name = "recommended", defaultValue = "0") int recommended,
1331
							   @RequestParam(name = "minimumQty", defaultValue = "0") int minimumQty,
1332
							   @RequestParam(name = "obvrecommend", defaultValue = "0") int obvrecommend,
1333
							   @RequestParam(name = "obvminimum", defaultValue = "0") int obvminimum, @RequestParam int regionId,
1334
							   Model model) throws ProfitMandiBusinessException {
1335
 
1336
		FocusedModel fm = new FocusedModel();
1337
		fm.setCatalogId(catalogId);
1338
		fm.setMinimumQty(minimumQty);
1339
		fm.setRecommendedQty(recommended);
1340
		fm.setRegionId(regionId);
1341
		fm.setObsRecommendedQty(obvrecommend);
1342
		fm.setObsMinimumQty(obvminimum);
1343
		fm.setCreatedTimestamp(LocalDateTime.now());
1344
		focusedModelRepository.persist(fm);
1345
		return "focused_model";
1346
	}
1347
 
30017 amit.gupta 1348
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
1349
	public String removeFocusedModelItem(HttpServletRequest request,
30664 amit.gupta 1350
										 @RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
30017 amit.gupta 1351
 
1352
		focusedModelRepository.deleteById(id);
1353
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1354
		return "response";
1355
	}
1356
 
26846 tejbeer 1357
	@RequestMapping(value = "/getPartnerloadContent")
1358
	public String getPartnerloadContent(HttpServletRequest request, Model model,
30664 amit.gupta 1359
										@RequestParam(required = false, defaultValue = "0") int fofoId,
1360
										@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
26846 tejbeer 1361
 
1362
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1363
		Set<Integer> roleIds = loginDetails.getRoleIds();
1364
		LOGGER.info("Counter size is {}", counterSize);
1365
		LOGGER.info("Fofo Id is {}", fofoId);
1366
		boolean isAdmin = roleManager.isAdmin(roleIds);
1367
 
1368
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1369
				.collect(Collectors.toList());
1370
 
1371
		Map<String, Object> equalsMap = new HashMap<>();
1372
		equalsMap.put("categoryId", 10006);
1373
		equalsMap.put("brand", brands);
1374
		Map<String, List<?>> notEqualsMap = new HashMap<>();
1375
 
1376
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1377
		Map<Integer, Integer> currentStockMap;
1378
 
1379
		if (!isAdmin && fofoId == 0) {
1380
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1381
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
1382
			equalsStockJoinMap.put("fofoId", fofoId);
1383
			currentStockMap = itemRepository
1384
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1385
							equalsStockJoinMap, notEqualsJoinMap, "availability")
1386
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1387
			LOGGER.info("currentStock");
1388
		} else {
1389
			if (fofoId == 0) {
1390
 
1391
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1392
				equalsStockJoinMap.put("fofoId", fofoId);
1393
 
1394
				currentStockMap = itemRepository
1395
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1396
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1397
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1398
 
1399
			} else {
1400
 
1401
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1402
				equalsStockJoinMap.put("fofoId", fofoId);
1403
 
1404
				currentStockMap = itemRepository
1405
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1406
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1407
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1408
 
1409
			}
1410
		}
1411
 
27768 tejbeer 1412
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
26846 tejbeer 1413
		LOGGER.info("currentStock" + currentStockMap);
1414
 
1415
		Map<Integer, Integer> itemsInTransit = null;
1416
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
1417
		if (!isAdmin) {
1418
			tagListings = new ArrayList<>(tagListings);
28055 tejbeer 1419
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId,
1420
					OrderRepository.validOrderStatusList);
26846 tejbeer 1421
			inTransitOrders = this.filterValidOrders(inTransitOrders);
1422
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1423
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1424
		} else {
1425
			itemsInTransit = new HashMap<>();
1426
		}
1427
 
1428
		int totalPcs = 0;
1429
 
1430
		float totalAmount = 0;
1431
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
1432
 
27088 tejbeer 1433
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1434
				.collect(Collectors.toList());
26846 tejbeer 1435
 
27088 tejbeer 1436
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
1437
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
1438
 
26846 tejbeer 1439
		LocalDate currentMonthDate = LocalDate.now();
1440
		MonthlyPlanned monthlyPlanned = null;
1441
		List<Integer> fofoOrderIds = null;
1442
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 1443
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26846 tejbeer 1444
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
1445
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1446
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
1447
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
30664 amit.gupta 1448
							LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
26846 tejbeer 1449
					.collect(Collectors.toList());
1450
 
1451
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 1452
		} else {
26846 tejbeer 1453
			currentMonthDate = LocalDate.now().withDayOfMonth(1);
1454
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
1455
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1456
			model.addAttribute("planningMonth", currentMonthDate.getMonth());
1457
			model.addAttribute("mtd", true);
1458
			model.addAttribute("freezed", true);
1459
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
30664 amit.gupta 1460
							curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
26846 tejbeer 1461
					.collect(Collectors.toList());
1462
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
1463
		}
1464
 
1465
		Map<Integer, Integer> plannedDetailMap = null;
1466
		if (monthlyPlanned != null) {
1467
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1468
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
1469
 
1470
		}
1471
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
1472
 
1473
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
1474
		Map<String, Object> equalsJoinMap = new HashMap<>();
1475
 
1476
		equalsJoinMap.put("orderId", fofoOrderIds);
1477
		Map<Integer, Integer> last15daysMap = null;
1478
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
1479
 
1480
			last15daysMap = itemRepository
1481
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1482
							notEqualsJoinMap, "quantity")
1483
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1484
		}
1485
		LOGGER.info("last15daysMap" + last15daysMap);
1486
 
1487
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
1488
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1489
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1490
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1491
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1492
		LOGGER.info("catalogIdItemMap");
1493
 
1494
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
1495
		equalsItemJoinMap.put("active", 1);
28897 amit.gupta 1496
		List<IntegerIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
26846 tejbeer 1497
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
27768 tejbeer 1498
		Map<Integer, Integer> ourStockAvailability = new HashMap<>();
1499
 
1500
		Map<Integer, List<Integer>> catalogItemIdMap = itemRepository
1501
				.selectAllByCatalogIds(new HashSet<>(
1502
						tagListingCatalogIds.stream().map(x -> x.getCatalogId()).collect(Collectors.toList())))
1503
				.stream().collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1504
						Collectors.mapping(y -> y.getId(), Collectors.toList())));
1505
		for (Entry<Integer, List<Integer>> catalogItem : catalogItemIdMap.entrySet()) {
1506
			List<Integer> itemIds = catalogItem.getValue();
1507
			int availability = 0;
1508
			for (Integer itemId : itemIds) {
30664 amit.gupta 1509
				List<SaholicCISTable> saholicCISTableList = saholicCISTableRepository.selectByItemWarehouse(itemId, fofoStore.getWarehouseId());
1510
				if (saholicCISTableList != null) {
1511
					availability += saholicCISTableList.stream().collect(Collectors.summingInt(x -> x.getAvailability()));
27768 tejbeer 1512
				}
1513
			}
1514
			Integer catalogItemId = catalogItem.getKey();
1515
			ourStockAvailability.put(catalogItemId, availability);
1516
		}
1517
		LOGGER.info("ourStockAvailability" + ourStockAvailability);
1518
 
28897 amit.gupta 1519
		for (IntegerIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
26846 tejbeer 1520
			int catalogId = catalogIdAggregateValue.getCatalogId();
1521
			Item item = catalogIdItemMap.get(catalogId).get(0);
1522
			TagListing tagListing = taglistingMap.get(item.getId());
1523
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1524
			if (!catalogListingMap.containsKey(catalogId)) {
1525
				catalogListingModel = new CatalogListingModel();
1526
				catalogListingModel.setCatalogId(catalogId);
1527
				catalogListingModel.setDp(tagListing.getSellingPrice());
1528
				catalogListingModel.setMop(tagListing.getMop());
1529
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1530
				if (plannedDetailMap != null) {
1531
 
1532
					Integer quantity = plannedDetailMap.get(catalogId);
1533
					if (quantity != null) {
1534
						catalogListingModel.setAllocatedQuantity(quantity);
1535
					}
1536
				}
1537
 
1538
				if (last15daysMap != null) {
1539
					Integer last15DaysSale = last15daysMap.get(catalogId);
1540
 
1541
					if (last15DaysSale != null) {
1542
						catalogListingModel.setLast15DaysSale(last15DaysSale);
1543
					} else {
1544
						catalogListingModel.setLast15DaysSale(0);
1545
					}
1546
				} else {
1547
					catalogListingModel.setLast15DaysSale(0);
1548
				}
1549
 
1550
				catalogListingModel.setBrand(item.getBrand());
1551
				if (item.getCategoryId() == 10006) {
1552
					catalogListingModel.setCategoryId(item.getCategoryId());
1553
				}
1554
 
27768 tejbeer 1555
				Integer ourStock = ourStockAvailability.get(catalogId);
1556
				LOGGER.info("catalogId" + catalogId);
1557
 
1558
				LOGGER.info("ourStock" + ourStock);
1559
				if (ourStock != null) {
1560
					catalogListingModel.setOurStockQty(ourStock);
1561
				}
1562
 
26846 tejbeer 1563
				FocusedModel fm = focusedModelMap.get(catalogId);
1564
				if (fm != null) {
1565
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1566
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
29667 tejbeer 1567
					catalogListingModel.setObsRecommendedQty(fm.getObsRecommendedQty());
1568
					catalogListingModel.setObsMinimumQty(fm.getObsMinimumQty());
26846 tejbeer 1569
 
1570
				} else {
1571
					catalogListingModel.setRecommendedQty(0);
1572
					catalogListingModel.setMinimumQty(0);
29667 tejbeer 1573
 
1574
					catalogListingModel.setObsRecommendedQty(0);
1575
					catalogListingModel.setObsMinimumQty(0);
1576
 
26846 tejbeer 1577
				}
1578
 
1579
				catalogListingMap.put(catalogId, catalogListingModel);
1580
 
1581
			}
1582
			int itemAvailability = 0;
1583
			if (currentStockMap != null) {
1584
				Integer qty = currentStockMap.get(catalogId);
1585
				itemAvailability = qty == null ? 0 : qty;
1586
				catalogListingModel.setStockInHand(itemAvailability);
1587
			} else {
1588
				catalogListingModel.setStockInHand(0);
1589
			}
1590
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
1591
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1592
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
1593
			if (plannedDetailMap != null) {
1594
				if (plannedDetailMap.get(catalogId) != null) {
1595
 
1596
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
1597
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
1598
					LOGGER.info("remaning" + remaining);
1599
 
1600
					if (remaining != 0) {
1601
						catalogListingModel.setRemaining(remaining);
1602
					} else {
1603
						catalogListingModel.setRemaining(0);
1604
					}
1605
				}
1606
			}
1607
		}
1608
 
26963 amit.gupta 1609
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26846 tejbeer 1610
		if (fofoId > 0) {
1611
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1612
			model.addAttribute("retailerName",
1613
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1614
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1615
			model.addAttribute("retailerId", customRetailer.getPartnerId());
1616
			model.addAttribute("counterSize", fs.getCounterSize().toString());
1617
		} else {
1618
			model.addAttribute("counterSize", counterSize.toString());
1619
		}
1620
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
1621
 
1622
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
1623
 
1624
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1625
				Comparator.reverseOrder());
1626
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
1627
		model.addAttribute("catalogTagListings",
1628
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1629
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
27768 tejbeer 1630
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(fofoId));
26846 tejbeer 1631
		model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
1632
		model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());
1633
 
1634
		model.addAttribute("customRetailers", customRetailers);
1635
		model.addAttribute("totalAmount", totalAmount);
1636
		model.addAttribute("monthlyPlanned", monthlyPlanned);
1637
		model.addAttribute("totalPcs", totalPcs);
1638
 
1639
		UserWallet userWallet = walletService.getUserWallet(fofoId);
1640
 
1641
		model.addAttribute("userWallet", userWallet);
1642
 
1643
		return "create-partner-po";
1644
 
1645
	}
1646
 
1647
	@RequestMapping(value = "/selectItemColor", method = RequestMethod.GET)
1648
	public String selectItemColor(HttpServletRequest request, @RequestParam int catalogId, Model model)
1649
			throws Exception {
1650
 
1651
		List<Item> selecteditems = itemRepository.selectAllByCatalogItemId(catalogId);
1652
 
1653
		List<Item> items = new ArrayList<>();
1654
		for (Item item : selecteditems) {
1655
 
1656
			TagListing tagListing = tagListingRepository.selectByItemId(item.getId(), true);
1657
 
1658
			if (tagListing != null) {
1659
				items.add(item);
1660
			}
1661
 
1662
		}
1663
		model.addAttribute("items", items);
1664
		LOGGER.info("itemIdAndColorMap" + items);
1665
		return "select-item-color";
1666
	}
1667
 
30003 tejbeer 1668
	List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com",
30564 tejbeer 1669
			"niranjan.kala@smartdukaan.com", "amit.gupta@smartdukaan.com", "tejbeer.kaur@smartdukaan.com");
30003 tejbeer 1670
 
1671
	@Autowired
1672
	private PositionRepository positionRepository;
1673
 
1674
	@Autowired
1675
	private PartnerTypeChangeService partnerTypeChangeService;
1676
 
1677
	@Autowired
1678
	private com.spice.profitmandi.service.transaction.TransactionService transactionService;
1679
 
1680
	@Autowired
1681
	private CategoryRepository categoryRepository;
1682
 
30044 tejbeer 1683
	@Autowired
1684
	private BrandLimitRepository brandLimitRepository;
1685
 
30003 tejbeer 1686
	private List<OrderStatus> orderStatusList = Arrays.asList(OrderStatus.SUBMITTED_FOR_PROCESSING,
1687
			OrderStatus.ACCEPTED);
1688
 
1689
	public static final Map<String, Double> Brand_Amount_Limit = new HashMap<>();
1690
 
1691
	static {
30044 tejbeer 1692
 
30003 tejbeer 1693
		Brand_Amount_Limit.put("accessories", 10000.00);
1694
		Brand_Amount_Limit.put("TV", 27000.00);
1695
	}
1696
 
1697
	@RequestMapping(value = "/getPartnersBrandWiseDetail", method = RequestMethod.GET)
1698
	public String getPartnersBrandWiseDetail(HttpServletRequest request, Model model) throws Exception {
1699
 
1700
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1701
		String email = loginDetails.getEmailId();
1702
 
1703
		List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Tecno", "Itel", "OnePlus", "Lava", "Realme",
1704
				"Xiaomi", "Nokia");
1705
 
1706
		AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1707
		Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1708
 
1709
		Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
1710
 
1711
		if (emails.contains(authUser.getEmailId())) {
1712
			fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
1713
			LOGGER.info("fofoIds" + fofoIds);
1714
		}
1715
 
1716
		Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
1717
 
30024 tejbeer 1718
		Map<Integer, Map<String, Double>> fofoIdBrandAmountMap = new HashMap<>();
30003 tejbeer 1719
 
1720
		Map<Integer, InStockAccessoriesTvFofoIdModel> inStockAccessTv = new HashMap<>();
1721
		Map<Integer, InStockAccessoriesTvFofoIdModel> pendingIndentAccessTv = new HashMap<>();
1722
		Map<Integer, InStockAccessoriesTvFofoIdModel> grnPendingAccessTvOrders = new HashMap<>();
30426 tejbeer 1723
		Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
30003 tejbeer 1724
		Map<Integer, CustomRetailer> customRetailers = new HashMap<>();
1725
		Map<Integer, PartnerType> fofoIdPartnerTypeMap = new HashMap<>();
1726
 
1727
		if (fofoIds.size() > 0 && fofoIds != null) {
1728
			List<Integer> fofoIdList = new ArrayList<>(fofoIds);
1729
 
30046 tejbeer 1730
			Map<Integer, ActivationType> partnerActivationType = fofoStoreRepository.selectByRetailerIds(fofoIdList)
1731
					.stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getActivationType()));
1732
 
1733
			model.addAttribute("partnerActivationType", partnerActivationType);
1734
			model.addAttribute("activationTypes", ActivationType.values());
1735
 
30003 tejbeer 1736
			Map<Integer, FofoReportingModel> partnerSalesHeadersMap = csService.getPartnerIdSalesHeaders();
1737
 
1738
			model.addAttribute("partnerSalesHeadersMap", partnerSalesHeadersMap);
30044 tejbeer 1739
 
1740
			Map<Integer, Map<String, Float>> partnerBrandLimitMap = brandLimitRepository.selectAllPartnerBrandLimit()
1741
					.stream().collect(Collectors.groupingBy(x -> x.getFofoId(),
1742
							Collectors.toMap(x -> x.getBrand(), x -> x.getBrandLimit())));
1743
 
1744
			model.addAttribute("partnerBrandLimitMap", partnerBrandLimitMap);
30426 tejbeer 1745
			customRetailers = fofoIds.stream().map(x -> customRetailerMap.get(x)).filter(x -> x != null)
1746
					.collect(Collectors.toList()).stream().collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
30024 tejbeer 1747
			Map<Integer, Map<String, Double>> inStockBrandModel = new HashMap<>();
1748
			Map<Integer, Map<String, Double>> pendingIndent = new HashMap<>();
1749
			Map<Integer, Map<String, Double>> grnPendingOrders = new HashMap<>();
30003 tejbeer 1750
 
30024 tejbeer 1751
			// mobile
30003 tejbeer 1752
			inStockBrandModel = currentInventorySnapshotRepository.selectSumInStockMobiletabletGroupByBrand(fofoIdList)
1753
					.stream()
1754
					.collect(Collectors.groupingBy(InStockBrandFofoIdModel::getFofoId,
1755
							Collectors.groupingBy(InStockBrandFofoIdModel::getBrand,
1756
									Collectors.summingDouble(InStockBrandFofoIdModel::getAmount))));
1757
 
1758
			pendingIndent = transactionService.getInTransitOrders(fofoIdList).stream()
30024 tejbeer 1759
					.filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
30003 tejbeer 1760
					.collect(Collectors.groupingBy(x -> x.getRetailerId(),
1761
							Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1762
									Collectors.summingDouble(y -> (double) y.getTotalAmount()))));
1763
 
1764
			grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoIdList).stream()
30024 tejbeer 1765
					.filter(x -> x.getLineItem().getItem().getCategoryId() == ProfitMandiConstants.MOBILE_CATEGORY_ID)
30003 tejbeer 1766
					.collect(Collectors.groupingBy(x -> x.getRetailerId(),
1767
							Collectors.groupingBy(y -> y.getLineItem().getBrand(),
1768
									Collectors.summingDouble(y -> (double) y.getTotalAmount()))));
1769
 
30024 tejbeer 1770
			// accessories
30003 tejbeer 1771
			inStockAccessTv = currentInventorySnapshotRepository.selectSumInStockAccessoriesAndTv(fofoIdList).stream()
1772
					.collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1773
 
1774
			pendingIndentAccessTv = orderRepository.selectAllPendingIndentAccessoriesTvGroupByFofoId(fofoIdList)
1775
					.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1776
 
1777
			grnPendingAccessTvOrders = orderRepository.selectAllGrnPendingAccessoriesTvGroupByFofoId(fofoIdList)
1778
					.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1779
 
30024 tejbeer 1780
			for (Entry<Integer, CustomRetailer> customRetailer : customRetailers.entrySet()) {
1781
				PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(customRetailer.getKey(),
1782
						LocalDate.now());
1783
				fofoIdPartnerTypeMap.put(customRetailer.getKey(), partnerType);
1784
 
1785
				Map<String, Double> stockBrand = inStockBrandModel.get(customRetailer.getKey());
1786
				Map<String, Double> pendingIndentBrand = pendingIndent.get(customRetailer.getKey());
1787
				Map<String, Double> grnBrand = grnPendingOrders.get(customRetailer.getKey());
1788
				double totalAmount = 0;
1789
 
1790
				Map<String, Double> brandAmountMap = new HashMap<>();
1791
				for (String brand : brands) {
1792
 
1793
					double stockValue = 0;
1794
					double pendingValue = 0;
1795
					double grnValue = 0;
1796
					if (stockBrand != null) {
1797
 
1798
						if (stockBrand.get(brand) != null) {
1799
							stockValue = stockBrand.get(brand);
1800
						}
1801
					}
1802
 
1803
					if (pendingIndentBrand != null) {
1804
						if (pendingIndentBrand.get(brand) != null) {
1805
							pendingValue = pendingIndentBrand.get(brand);
1806
						}
1807
					}
1808
 
1809
					if (grnBrand != null) {
1810
						if (grnBrand.get(brand) != null) {
1811
							grnValue = grnBrand.get(brand);
1812
						}
1813
					}
1814
 
1815
					totalAmount = stockValue + pendingValue + grnValue;
1816
 
1817
					brandAmountMap.put(brand, totalAmount);
1818
 
1819
				}
1820
 
1821
				fofoIdBrandAmountMap.put(customRetailer.getKey(), brandAmountMap);
1822
 
1823
			}
1824
 
1825
			List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository
1826
					.selectAll(new ArrayList<>(fofoIdList), LocalDate.now().minusDays(1));
1827
			if (!partnerDailyInvestments.isEmpty()) {
1828
				partnerDailyInvestmentMap = partnerDailyInvestments.stream()
1829
						.collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1830
			}
1831
 
30003 tejbeer 1832
		}
1833
 
1834
		model.addAttribute("customRetailers", customRetailers);
1835
 
30024 tejbeer 1836
		LOGGER.info("fofoIdBrandAmountMap" + fofoIdBrandAmountMap);
30003 tejbeer 1837
 
1838
		model.addAttribute("partnerDailyInvestmentMap", partnerDailyInvestmentMap);
1839
 
1840
		model.addAttribute("brands", brands);
1841
 
1842
		model.addAttribute("brandAmountLimit", Brand_Amount_Limit);
30024 tejbeer 1843
		model.addAttribute("fofoIdBrandAmountMap", fofoIdBrandAmountMap);
30003 tejbeer 1844
 
1845
		model.addAttribute("inStockAccessTv", inStockAccessTv);
1846
		model.addAttribute("pendingIndentAccessTv", pendingIndentAccessTv);
1847
		model.addAttribute("grnPendingAccessTvOrders", grnPendingAccessTvOrders);
1848
		model.addAttribute("fofoIdPartnerTypeMap", fofoIdPartnerTypeMap);
1849
		return "partner-brandwise-detail";
1850
	}
1851
 
30046 tejbeer 1852
	@RequestMapping(value = "/changeActivationType", method = RequestMethod.POST)
1853
	public String changeActivationType(HttpServletRequest request, @RequestParam String code,
30664 amit.gupta 1854
									   @RequestParam ActivationType activationType, Model model) throws Exception {
30046 tejbeer 1855
 
1856
		FofoStore fofoStore = fofoStoreRepository.selectByStoreCode(code);
1857
 
1858
		fofoStore.setActivationType(activationType);
1859
 
1860
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1861
		return "response";
1862
 
1863
	}
1864
 
30017 amit.gupta 1865
	@RequestMapping(value = "/createPo", method = RequestMethod.POST)
1866
	public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)
1867
			throws Exception {
1868
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1869
		SuggestedPo mp = new SuggestedPo();
1870
		mp.setFofoId(monthlyPoModel.getFofoId());
1871
		mp.setCreateTimestamp(LocalDateTime.now());
1872
		mp.setStatus("open");
1873
		mp.setAuthId(loginDetails.getEmailId());
1874
		suggestedPoRepository.persist(mp);
1875
 
1876
		for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {
1877
			SuggestedPoDetail mpd = new SuggestedPoDetail();
1878
			mpd.setItemId(poId.getItemId());
1879
			mpd.setQuantity(poId.getQty());
1880
			mpd.setUpdatedTimestamp(LocalDateTime.now());
1881
			mpd.setPoId(mp.getId());
1882
			suggestedPoDetailRepository.persist(mpd);
1883
		}
1884
 
1885
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
1886
		sendNotificationModel.setCampaignName("Alert");
1887
		sendNotificationModel.setMessage("Suggested Po");
1888
		sendNotificationModel.setType("url");
1889
		sendNotificationModel.setTitle("Alert");
1890
		sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
1891
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1892
		sendNotificationModel.setMessageType(MessageType.notification);
1893
		int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());
1894
 
1895
		sendNotificationModel.setUserIds(Arrays.asList(userId));
1896
		notificationService.sendNotification(sendNotificationModel);
1897
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1898
 
1899
		return "response";
1900
	}
1901
 
30003 tejbeer 1902
	@RequestMapping(value = "/getPartnerShortageStock", method = RequestMethod.GET)
1903
	public String getPartnerShortageStock(HttpServletRequest request,
30664 amit.gupta 1904
										  @RequestParam(required = false, defaultValue = "") String brand, @RequestParam int fofoId, Model model)
30003 tejbeer 1905
			throws Exception {
1906
 
1907
 
1908
		Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap = saholicInventoryService
1909
				.getSaholicPOItems();
1910
 
1911
		List<FocusedModelShortageModel> focusedModelShortageList = new ArrayList<>();
1912
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1913
		Map<Integer, Integer> processingOrderMap = null;
1914
		Map<Integer, Integer> catalogIdAndQtyMap = null;
1915
		Map<Integer, Integer> grnPendingOrdersMap = null;
1916
 
30044 tejbeer 1917
		List<PartnerStockDescriptionModel> inStocks = new ArrayList<>();
1918
 
1919
		List<PartnerStockDescriptionModel> grnPendings = new ArrayList<>();
1920
 
1921
		List<PartnerStockDescriptionModel> pendingIndents = new ArrayList<>();
1922
 
30003 tejbeer 1923
		Map<Integer, Integer> currentInventorySnapshot = currentInventorySnapshotRepository.selectByFofoId(fofoId)
1924
				.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getAvailability()));
1925
 
1926
		if (!currentInventorySnapshot.isEmpty()) {
30044 tejbeer 1927
			if (!brand.equals("undefined") && !brand.equals("accessories") && !brand.equals("TV")) {
1928
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1929
						.filter(x -> x.getBrand().equals(brand))
1930
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1931
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
30003 tejbeer 1932
 
30044 tejbeer 1933
			} else {
1934
				catalogIdAndQtyMap = itemRepository.selectByIds(currentInventorySnapshot.keySet()).stream()
1935
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1936
								Collectors.summingInt(x -> currentInventorySnapshot.get(x.getId()))));
1937
			}
1938
			inStocks.addAll(getBrandItemwiseDescription(brand, catalogIdAndQtyMap));
30003 tejbeer 1939
		}
1940
 
1941
		Map<Integer, Integer> grnPendingOrders = orderRepository.selectPendingGrnOrders(fofoId).stream()
1942
				.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1943
						Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1944
		if (!grnPendingOrders.isEmpty()) {
1945
 
30044 tejbeer 1946
			if (!brand.equals("undefined") && !brand.equals("accessories") && !brand.equals("TV")) {
1947
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1948
						.filter(x -> x.getBrand().equals(brand))
1949
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1950
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1951
 
1952
			} else {
1953
				grnPendingOrdersMap = itemRepository.selectByIds(grnPendingOrders.keySet()).stream()
1954
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1955
								Collectors.summingInt(x -> grnPendingOrders.get(x.getId()))));
1956
			}
1957
			grnPendings.addAll(getBrandItemwiseDescription(brand, grnPendingOrdersMap));
1958
 
30003 tejbeer 1959
		}
1960
 
1961
		Map<Integer, Integer> processingOrder = orderRepository.selectOrders(fofoId, orderStatusList).stream()
1962
				.collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1963
						Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1964
		if (!processingOrder.isEmpty()) {
30044 tejbeer 1965
			if (!brand.equals("undefined") && !brand.equals("accessories") && !brand.equals("TV")) {
1966
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1967
						.filter(x -> x.getBrand().equals(brand)).collect(Collectors.groupingBy(
1968
								x -> x.getCatalogItemId(), Collectors.summingInt(x -> processingOrder.get(x.getId()))));
30003 tejbeer 1969
 
30044 tejbeer 1970
			} else {
1971
				processingOrderMap = itemRepository.selectByIds(processingOrder.keySet()).stream()
1972
						.collect(Collectors.groupingBy(x -> x.getCatalogItemId(),
1973
								Collectors.summingInt(x -> processingOrder.get(x.getId()))));
1974
			}
1975
			pendingIndents.addAll(getBrandItemwiseDescription(brand, processingOrderMap));
1976
 
30003 tejbeer 1977
		}
1978
 
1979
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1980
				.collect(Collectors.toList());
1981
		LOGGER.info("regionIds" + regionIds);
1982
		if (regionIds.size() == 0) {
1983
			LOGGER.info("No region found for partner {}", fofoId);
1984
 
1985
		}
1986
		Map<Integer, Optional<Integer>> focusedCatalogIdAndQtyMap = focusedModelRepository
1987
				.selectAllByRegionIds(regionIds).stream().collect(Collectors.groupingBy(FocusedModel::getCatalogId,
1988
						Collectors.mapping(FocusedModel::getObsMinimumQty, Collectors.maxBy(Integer::compareTo))));
1989
 
1990
		for (Map.Entry<Integer, Optional<Integer>> entry : focusedCatalogIdAndQtyMap.entrySet()) {
1991
			List<Item> items = itemRepository.selectAllByCatalogItemId(entry.getKey());
1992
 
1993
			if (brand.equals("undefined") || items.get(0).getBrand().equals(brand)) {
1994
 
1995
				FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(), entry.getKey(),
30664 amit.gupta 1996
						processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId, warehousePoItemAvailabilityMap, items, customRetailer);
30003 tejbeer 1997
 
1998
				focusedModelShortageList.add(fm);
1999
			} else if (brand.equals("accessories")) {
2000
 
2001
				if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2002
					if (items.get(0).getCategoryId() != 0) {
2003
						Category category = categoryRepository.selectById(items.get(0).getCategoryId());
2004
 
2005
						if (category.getParentCategoryId() == 10011) {
2006
							FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
30664 amit.gupta 2007
									entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId
2008
									, warehousePoItemAvailabilityMap, items,
30003 tejbeer 2009
									customRetailer);
2010
 
2011
							focusedModelShortageList.add(fm);
2012
 
2013
						}
2014
					}
2015
 
2016
				}
2017
 
2018
			} else if (brand.equals("TV")) {
2019
 
2020
				if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2021
					LOGGER.info("items.get(0).getCategoryId()" + items.get(0).getCategoryId());
2022
					if (items.get(0).getCategoryId() != 0) {
2023
 
2024
						Category category = categoryRepository.selectById(items.get(0).getCategoryId());
2025
 
2026
						if (category.getParentCategoryId() == 14200) {
2027
							FocusedModelShortageModel fm = this.getFocusedModelShortage(entry.getValue().get(),
2028
									entry.getKey(), processingOrderMap, grnPendingOrdersMap, catalogIdAndQtyMap, fofoId,
30664 amit.gupta 2029
									warehousePoItemAvailabilityMap, items,
30003 tejbeer 2030
									customRetailer);
2031
 
2032
							focusedModelShortageList.add(fm);
2033
 
2034
						}
2035
					}
2036
 
2037
				}
2038
 
2039
			}
2040
 
2041
		}
2042
 
2043
		LOGGER.info("focusedModelShortageList" + focusedModelShortageList);
2044
 
2045
		model.addAttribute("focusedModelShortageList", focusedModelShortageList);
2046
 
30044 tejbeer 2047
		model.addAttribute("inStocks", inStocks);
2048
 
2049
		model.addAttribute("grnPendings", grnPendings);
2050
 
2051
		model.addAttribute("pendingIndents", pendingIndents);
2052
 
30003 tejbeer 2053
		model.addAttribute("customRetailer", customRetailer);
30044 tejbeer 2054
 
2055
		model.addAttribute("brand", brand);
2056
 
2057
		if (brand.equals("undefined")) {
2058
 
2059
			Map<String, List<FocusedModelShortageModel>> focusedModelShortageBrandMap = focusedModelShortageList
2060
					.stream().collect(Collectors.groupingBy(x -> x.getBrandName()));
2061
 
2062
			Map<String, List<PartnerStockDescriptionModel>> inStockBrandMap = inStocks.stream()
2063
					.collect(Collectors.groupingBy(x -> x.getBrand()));
2064
 
2065
			LOGGER.info("inStockBrandMap" + inStockBrandMap);
2066
 
2067
			Map<String, List<PartnerStockDescriptionModel>> grnPendingBrandMap = grnPendings.stream()
2068
					.collect(Collectors.groupingBy(x -> x.getBrand()));
2069
 
2070
			LOGGER.info("grnPendingBrandMap" + grnPendingBrandMap);
2071
 
2072
			Map<String, List<PartnerStockDescriptionModel>> pendingIndentBrandMap = pendingIndents.stream()
2073
					.collect(Collectors.groupingBy(x -> x.getBrand()));
2074
 
2075
			LOGGER.info("pendingIndentBrandMap" + pendingIndentBrandMap);
2076
 
2077
			model.addAttribute("inStockBrandMap", inStockBrandMap);
2078
 
2079
			model.addAttribute("grnPendingBrandMap", grnPendingBrandMap);
2080
 
2081
			model.addAttribute("focusedModelShortageBrandMap", focusedModelShortageBrandMap);
2082
 
2083
			model.addAttribute("pendingIndentBrandMap", pendingIndentBrandMap);
2084
 
2085
		}
30003 tejbeer 2086
		return "partner-stock";
2087
 
2088
	}
2089
 
30044 tejbeer 2090
	private List<PartnerStockDescriptionModel> getBrandItemwiseDescription(String brand,
30664 amit.gupta 2091
																		   Map<Integer, Integer> catalogIdAndQtyMap) throws ProfitMandiBusinessException {
30044 tejbeer 2092
		List<PartnerStockDescriptionModel> inStocks = new ArrayList<>();
2093
 
2094
		for (Entry<Integer, Integer> inStock : catalogIdAndQtyMap.entrySet()) {
2095
			List<Item> items = itemRepository.selectAllByCatalogItemId(inStock.getKey());
2096
 
2097
			if (brand.equals("accessories")) {
2098
				if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2099
 
2100
					if (items.get(0).getCategoryId() != 0) {
2101
						Category category = categoryRepository.selectById(items.get(0).getCategoryId());
2102
 
2103
						if (category.getParentCategoryId() == 10011) {
2104
							PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2105
							psdp.setBrand(items.get(0).getBrand());
2106
							psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2107
									+ items.get(0).getModelNumber());
2108
							psdp.setQty(inStock.getValue());
2109
							inStocks.add(psdp);
2110
						}
2111
					}
2112
 
2113
				}
2114
 
2115
			} else if (brand.equals("TV")) {
2116
				if (items.get(0).getCategoryId() != ProfitMandiConstants.MOBILE_CATEGORY_ID) {
2117
 
2118
					if (items.get(0).getCategoryId() != 0) {
2119
						Category category = categoryRepository.selectById(items.get(0).getCategoryId());
2120
 
2121
						if (category.getParentCategoryId() == 14200) {
2122
							PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2123
							psdp.setBrand(items.get(0).getBrand());
2124
							psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2125
									+ items.get(0).getModelNumber());
2126
							psdp.setQty(inStock.getValue());
2127
							inStocks.add(psdp);
2128
						}
2129
					}
2130
 
2131
				}
2132
 
2133
			} else {
2134
				PartnerStockDescriptionModel psdp = new PartnerStockDescriptionModel();
2135
				psdp.setBrand(items.get(0).getBrand());
2136
				psdp.setItemDescription(items.get(0).getBrand() + " " + items.get(0).getModelName() + " "
2137
						+ items.get(0).getModelNumber());
2138
				psdp.setQty(inStock.getValue());
2139
				inStocks.add(psdp);
2140
			}
2141
 
2142
		}
2143
 
2144
		return inStocks;
2145
	}
2146
 
30003 tejbeer 2147
	private FocusedModelShortageModel getFocusedModelShortage(int qty, int catalogId,
30664 amit.gupta 2148
															  Map<Integer, Integer> processingOrderMap, Map<Integer, Integer> grnPendingOrdersMap,
2149
															  Map<Integer, Integer> catalogIdAndQtyMap, int fofoId,
2150
															  Map<Integer, Map<Integer, List<SaholicPOItem>>> warehousePoItemAvailabilityMap, List<Item> items,
2151
															  CustomRetailer customRetailer) throws ProfitMandiBusinessException {
30003 tejbeer 2152
 
2153
		int minQty = qty;
2154
		int inStockQty = 0;
2155
		int processingQty = 0;
2156
		int grnPendingQty = 0;
2157
		int allColorNetAvailability = 0;
2158
		int allColorPoAvailability = 0;
2159
		if (processingOrderMap != null) {
2160
			processingQty = (processingOrderMap.get(catalogId) == null) ? 0 : processingOrderMap.get(catalogId);
2161
 
2162
		}
2163
		if (grnPendingOrdersMap != null) {
2164
			grnPendingQty = (grnPendingOrdersMap.get(catalogId) == null) ? 0 : grnPendingOrdersMap.get(catalogId);
2165
 
2166
		}
2167
		if (catalogIdAndQtyMap != null) {
2168
			inStockQty = (catalogIdAndQtyMap.get(catalogId) == null) ? 0 : catalogIdAndQtyMap.get(catalogId);
2169
 
2170
		}
2171
 
2172
		int grnStockQty = grnPendingQty + inStockQty;
2173
		int totalQty = processingQty + grnPendingQty + inStockQty;
2174
 
2175
		int shortageQty = minQty - totalQty;
2176
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
2177
 
2178
 
2179
		Map<Integer, List<SaholicPOItem>> poItemAvailabilityMap = warehousePoItemAvailabilityMap
2180
				.get(fofoStore.getWarehouseId());
2181
 
2182
		for (Item it : items) {
30664 amit.gupta 2183
			List<SaholicCISTable> currentAvailability = saholicCISTableRepository.selectByItemWarehouse(it.getId(), fofoStore.getWarehouseId());
30003 tejbeer 2184
			List<SaholicPOItem> poItemAvailability = null;
2185
 
2186
			if (poItemAvailabilityMap != null) {
2187
				poItemAvailability = poItemAvailabilityMap.get(it.getId());
2188
			}
2189
			if (currentAvailability != null) {
2190
				allColorNetAvailability += currentAvailability.stream()
30664 amit.gupta 2191
						.collect(Collectors.summingInt(SaholicCISTable::getNetAvailability));
30003 tejbeer 2192
			}
2193
 
2194
			if (poItemAvailability != null) {
2195
				allColorPoAvailability += poItemAvailability.stream()
2196
						.collect(Collectors.summingInt(SaholicPOItem::getUnfulfilledQty));
2197
			}
2198
 
2199
		}
2200
 
2201
		FocusedModelShortageModel fm = new FocusedModelShortageModel();
2202
		fm.setFofoId(fofoId);
2203
		fm.setStoreCode(fofoStore.getCode());
2204
		fm.setStoreName(customRetailer.getBusinessName());
2205
		fm.setBrandName(items.get(0).getBrand());
2206
		fm.setModelName(items.get(0).getModelName());
2207
		fm.setModelNumber(items.get(0).getModelNumber());
2208
		fm.setGrnStockQty(grnStockQty);
2209
		fm.setPendingIndentQty(processingQty);
2210
		fm.setShortageQty(shortageQty);
2211
		fm.setPoAvailabitiy(allColorPoAvailability);
2212
		fm.setItemName(items.get(0).getBrand() + items.get(0).getModelNumber() + items.get(0).getModelName());
2213
		fm.setAvailabitiy(allColorNetAvailability);
2214
		return fm;
2215
 
2216
	}
2217
 
30017 amit.gupta 2218
	@RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.GET)
2219
	public String SendPONotification(HttpServletRequest request, Model model) {
2220
		model.addAttribute("warehouses", ProfitMandiConstants.WAREHOUSE_MAP);
2221
		return "send-po-notification";
2222
	}
2223
 
2224
	@RequestMapping(value = "/indent/send-po-notification", method = RequestMethod.POST)
30044 tejbeer 2225
	public String sendPONotification(HttpServletRequest request, @RequestBody POItemWarehouseModel poItemWarehouseModel,
30664 amit.gupta 2226
									 Model model) throws Exception {
30017 amit.gupta 2227
 
30426 tejbeer 2228
		Map<Integer, Item> selectedCatalogItemMap = itemRepository
2229
				.selectAllByCatalogIds(new HashSet<>(poItemWarehouseModel.getCatalogIds())).stream()
2230
				.collect(Collectors.toMap(x -> x.getCatalogItemId(), x -> x, (existing, replacement) -> existing));
30017 amit.gupta 2231
 
30080 amit.gupta 2232
		Set<String> brands = selectedCatalogItemMap.values().stream().map(x -> x.getBrand().toLowerCase())
30044 tejbeer 2233
				.collect(Collectors.toSet());
30080 amit.gupta 2234
 
30017 amit.gupta 2235
		int warehouseId = poItemWarehouseModel.getWarehouseId();
30080 amit.gupta 2236
		for (String brand : brands) {
30096 amit.gupta 2237
			List<String> modelNames = selectedCatalogItemMap.entrySet().stream()
30426 tejbeer 2238
					.filter(x -> x.getValue().getBrand().toLowerCase().equals(brand))
2239
					.map(x -> x.getValue().getItemDescriptionNoColor()).collect(Collectors.toList());
30080 amit.gupta 2240
			SendNotificationModel sendNotificationModel = new SendNotificationModel();
2241
			sendNotificationModel.setCampaignName("SendPo");
2242
			sendNotificationModel.setTitle(String.format(PO_TITLE_STRING));
30096 amit.gupta 2243
			sendNotificationModel.setMessage(String.join(", ", modelNames));
30080 amit.gupta 2244
			sendNotificationModel.setType("url");
2245
			sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
2246
			sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
2247
			sendNotificationModel.setMessageType(MessageType.notification);
30017 amit.gupta 2248
 
30426 tejbeer 2249
			List<BrandRegionMapping> brandRegionMappings = brandRegionMappingRepository.selectAll().stream()
2250
					.filter(x -> brand.equals(x.getBrand().toLowerCase()) && x.getFromWarehouseId() == warehouseId
2251
							&& !x.isAccessory())
30080 amit.gupta 2252
					.collect(Collectors.toList());
2253
			List<Integer> toWarehouseIds = brandRegionMappings.stream().map(x -> x.getToWarehouseId())
2254
					.collect(Collectors.toList());
30017 amit.gupta 2255
 
30080 amit.gupta 2256
			List<Integer> fofoIds = fofoStoreRepository.selectByWarehouseIds(toWarehouseIds).stream()
2257
					.filter(x -> !x.isInternal() && x.isActive()).map(x -> x.getId()).collect(Collectors.toList());
30017 amit.gupta 2258
 
30080 amit.gupta 2259
			List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(fofoIds);
2260
			sendNotificationModel.setUserIds(userIds);
2261
			notificationService.sendNotification(sendNotificationModel);
2262
		}
30017 amit.gupta 2263
		model.addAttribute("response", true);
2264
		return "response";
2265
	}
2266
 
25721 tejbeer 2267
}