Subversion Repositories SmartDukaan

Rev

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