Subversion Repositories SmartDukaan

Rev

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