Subversion Repositories SmartDukaan

Rev

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