Subversion Repositories SmartDukaan

Rev

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

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