Subversion Repositories SmartDukaan

Rev

Rev 27081 | Rev 27768 | 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
 
25721 tejbeer 3
import java.time.LocalDate;
4
import java.time.LocalDateTime;
26131 tejbeer 5
import java.time.LocalTime;
23785 amit.gupta 6
import java.util.ArrayList;
23405 amit.gupta 7
import java.util.Arrays;
23796 amit.gupta 8
import java.util.Collections;
9
import java.util.Comparator;
10
import java.util.HashMap;
24406 amit.gupta 11
import java.util.HashSet;
23785 amit.gupta 12
import java.util.Iterator;
23405 amit.gupta 13
import java.util.List;
14
import java.util.Map;
23785 amit.gupta 15
import java.util.Set;
25721 tejbeer 16
import java.util.function.Function;
23405 amit.gupta 17
import java.util.stream.Collectors;
18
 
19
import javax.servlet.http.HttpServletRequest;
20
 
24231 amit.gupta 21
import org.apache.commons.io.output.ByteArrayOutputStream;
23717 amit.gupta 22
import org.apache.logging.log4j.LogManager;
23568 govind 23
import org.apache.logging.log4j.Logger;
23796 amit.gupta 24
import org.apache.thrift.TException;
24349 amit.gupta 25
import org.json.JSONArray;
23779 amit.gupta 26
import org.json.JSONObject;
23405 amit.gupta 27
import org.springframework.beans.factory.annotation.Autowired;
24231 amit.gupta 28
import org.springframework.core.io.ByteArrayResource;
29
import org.springframework.http.HttpHeaders;
30
import org.springframework.http.HttpStatus;
31
import org.springframework.http.ResponseEntity;
25721 tejbeer 32
import org.springframework.mail.javamail.JavaMailSender;
23405 amit.gupta 33
import org.springframework.stereotype.Controller;
34
import org.springframework.transaction.annotation.Transactional;
35
import org.springframework.ui.Model;
36
import org.springframework.web.bind.annotation.RequestBody;
37
import org.springframework.web.bind.annotation.RequestMapping;
38
import org.springframework.web.bind.annotation.RequestMethod;
23779 amit.gupta 39
import org.springframework.web.bind.annotation.RequestParam;
23405 amit.gupta 40
 
25736 tejbeer 41
import com.mongodb.DBObject;
23785 amit.gupta 42
import com.spice.profitmandi.common.enumuration.CounterSize;
26846 tejbeer 43
import com.spice.profitmandi.common.enumuration.MessageType;
23405 amit.gupta 44
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
25798 tejbeer 45
import com.spice.profitmandi.common.model.BrandStockPrice;
25796 tejbeer 46
import com.spice.profitmandi.common.model.CatalogIdAggregateValue;
24231 amit.gupta 47
import com.spice.profitmandi.common.model.CatalogListingModel;
23785 amit.gupta 48
import com.spice.profitmandi.common.model.CustomRetailer;
25721 tejbeer 49
import com.spice.profitmandi.common.model.PlannedModel;
26846 tejbeer 50
import com.spice.profitmandi.common.model.SendNotificationModel;
23779 amit.gupta 51
import com.spice.profitmandi.common.model.StockAllocationModel;
26951 amit.gupta 52
import com.spice.profitmandi.common.model.SuggestedPoIdModel;
53
import com.spice.profitmandi.common.model.SuggestedPoModel;
24231 amit.gupta 54
import com.spice.profitmandi.common.util.FileUtil;
25721 tejbeer 55
import com.spice.profitmandi.common.util.Utils;
56
import com.spice.profitmandi.common.util.Utils.Attachment;
26721 tejbeer 57
import com.spice.profitmandi.dao.entity.auth.AuthUser;
25721 tejbeer 58
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
23785 amit.gupta 59
import com.spice.profitmandi.dao.entity.catalog.Item;
23405 amit.gupta 60
import com.spice.profitmandi.dao.entity.catalog.TagListing;
27088 tejbeer 61
import com.spice.profitmandi.dao.entity.cs.PartnerRegion;
62
import com.spice.profitmandi.dao.entity.cs.Region;
25796 tejbeer 63
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
64
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23785 amit.gupta 65
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
25721 tejbeer 66
import com.spice.profitmandi.dao.entity.fofo.MonthlyPlanned;
27081 tejbeer 67
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
68
import com.spice.profitmandi.dao.entity.fofo.PartnerTypeChange;
26951 amit.gupta 69
import com.spice.profitmandi.dao.entity.fofo.PlannedDetail;
26846 tejbeer 70
import com.spice.profitmandi.dao.entity.fofo.SuggestedPo;
71
import com.spice.profitmandi.dao.entity.fofo.SuggestedPoDetail;
23796 amit.gupta 72
import com.spice.profitmandi.dao.entity.transaction.Order;
26846 tejbeer 73
import com.spice.profitmandi.dao.entity.transaction.UserWallet;
23796 amit.gupta 74
import com.spice.profitmandi.dao.entity.user.User;
26978 tejbeer 75
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
26721 tejbeer 76
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
25721 tejbeer 77
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
23405 amit.gupta 78
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
79
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
25721 tejbeer 80
import com.spice.profitmandi.dao.repository.cs.CsService;
27088 tejbeer 81
import com.spice.profitmandi.dao.repository.cs.PartnerRegionRepository;
82
import com.spice.profitmandi.dao.repository.cs.RegionRepository;
23779 amit.gupta 83
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25736 tejbeer 84
import com.spice.profitmandi.dao.repository.dtr.Mongo;
26846 tejbeer 85
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
23405 amit.gupta 86
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
25732 tejbeer 87
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
25721 tejbeer 88
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
89
import com.spice.profitmandi.dao.repository.fofo.MonthlyPlannedRepository;
27081 tejbeer 90
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeRepository;
26951 amit.gupta 91
import com.spice.profitmandi.dao.repository.fofo.PlannedDetailRepository;
92
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
26846 tejbeer 93
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoDetailRepository;
94
import com.spice.profitmandi.dao.repository.fofo.SuggestedPoRepository;
23796 amit.gupta 95
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
96
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
97
import com.spice.profitmandi.dao.repository.user.UserRepository;
26846 tejbeer 98
import com.spice.profitmandi.service.NotificationService;
23798 amit.gupta 99
import com.spice.profitmandi.service.authentication.RoleManager;
25736 tejbeer 100
import com.spice.profitmandi.service.inventory.InventoryService;
23779 amit.gupta 101
import com.spice.profitmandi.service.inventory.StockAllocationService;
102
import com.spice.profitmandi.service.user.RetailerService;
25547 amit.gupta 103
import com.spice.profitmandi.service.wallet.WalletService;
23796 amit.gupta 104
import com.spice.profitmandi.thrift.clients.PaymentClient;
105
import com.spice.profitmandi.thrift.clients.TransactionClient;
106
import com.spice.profitmandi.thrift.clients.UserClient;
23405 amit.gupta 107
import com.spice.profitmandi.web.model.LoginDetails;
108
import com.spice.profitmandi.web.util.CookiesProcessor;
109
import com.spice.profitmandi.web.util.MVCResponseSender;
110
 
23796 amit.gupta 111
import in.shop2020.logistics.PickUpType;
112
import in.shop2020.model.v1.order.LineItem;
113
import in.shop2020.model.v1.order.OrderSource;
114
import in.shop2020.model.v1.order.OrderStatus;
115
import in.shop2020.model.v1.order.OrderType;
116
import in.shop2020.model.v1.order.Transaction;
117
import in.shop2020.model.v1.order.TransactionService;
118
import in.shop2020.model.v1.order.TransactionStatus;
119
import in.shop2020.model.v1.user.ItemPriceQuantity;
120
import in.shop2020.model.v1.user.ShoppingCartException;
121
import in.shop2020.model.v1.user.UserContextService.Client;
122
import in.shop2020.payments.Attribute;
123
import in.shop2020.payments.PaymentException;
124
import in.shop2020.payments.PaymentStatus;
125
 
23405 amit.gupta 126
@Controller
127
@Transactional(rollbackFor = Throwable.class)
128
public class IndentController {
129
 
23568 govind 130
	private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
23796 amit.gupta 131
	private static final int WALLET_GATEWAY_ID = 8;
24406 amit.gupta 132
	private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));
23405 amit.gupta 133
 
23796 amit.gupta 134
	private final List<OrderStatus> validOrderStatusList = Arrays.asList(OrderStatus.ACCEPTED,
135
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
136
			OrderStatus.DELIVERY_SUCCESS, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
137
			OrderStatus.REACHED_DESTINATION_CITY);
138
 
24231 amit.gupta 139
	private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,
140
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
141
			OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
142
			OrderStatus.REACHED_DESTINATION_CITY);
25721 tejbeer 143
 
26951 amit.gupta 144
	private static final int PLANNING_OPEN_DAY = 20;
145
	private static final int PLANNING_CLOSE_DAY = 1;
146
 
25547 amit.gupta 147
	@Autowired
148
	WalletService walletService;
24231 amit.gupta 149
 
23405 amit.gupta 150
	@Autowired
25721 tejbeer 151
	private JavaMailSender googleMailSender;
152
 
153
	@Autowired
23405 amit.gupta 154
	private CookiesProcessor cookiesProcessor;
24231 amit.gupta 155
 
23796 amit.gupta 156
	@Autowired
157
	private UserWalletRepository userWalletRepository;
23785 amit.gupta 158
 
23779 amit.gupta 159
	@Autowired
23796 amit.gupta 160
	private UserRepository userRepository;
161
 
162
	@Autowired
23779 amit.gupta 163
	FofoStoreRepository fofoStoreRepository;
23405 amit.gupta 164
 
165
	@Autowired
23796 amit.gupta 166
	private OrderRepository orderRepository;
167
 
168
	@Autowired
26846 tejbeer 169
	private UserAccountRepository userAccountRepository;
170
 
171
	@Autowired
23405 amit.gupta 172
	private ItemRepository itemRepository;
173
 
174
	@Autowired
23779 amit.gupta 175
	private StockAllocationService stockAllocationService;
176
 
177
	@Autowired
178
	private RetailerService retailerService;
23405 amit.gupta 179
 
180
	@Autowired
181
	private TagListingRepository tagListingRepository;
182
 
183
	@Autowired
184
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
185
 
186
	@Autowired
23796 amit.gupta 187
	private PurchaseRepository purchaseRepository;
188
 
189
	@Autowired
23405 amit.gupta 190
	private MVCResponseSender mvcResponseSender;
191
 
23785 amit.gupta 192
	@Autowired
25721 tejbeer 193
	private FocusedModelRepository focusedModelRepository;
194
 
195
	@Autowired
196
	private MonthlyPlannedRepository monthlyPlannedRepository;
197
 
198
	@Autowired
199
	private FofoOrderRepository fofoOrderRepository;
25732 tejbeer 200
 
25721 tejbeer 201
	@Autowired
25732 tejbeer 202
	private FofoOrderItemRepository fofoOrderItemRepository;
203
 
204
	@Autowired
25721 tejbeer 205
	private PlannedDetailRepository plannedDetailRepository;
25732 tejbeer 206
 
25721 tejbeer 207
	@Autowired
23785 amit.gupta 208
	RoleManager roleManager;
23405 amit.gupta 209
 
25721 tejbeer 210
	@Autowired
27081 tejbeer 211
	PartnerTypeChangeRepository partnerTypeChangeRepository;
212
 
213
	@Autowired
25736 tejbeer 214
	private Mongo mongoClient;
215
 
216
	@Autowired
217
	private InventoryService inventoryService;
218
 
219
	@Autowired
26721 tejbeer 220
	private CsService csService;
25721 tejbeer 221
 
26721 tejbeer 222
	@Autowired
223
	private AuthRepository authRepository;
224
 
26846 tejbeer 225
	@Autowired
226
	private SuggestedPoRepository monthlyPoRepository;
227
 
228
	@Autowired
229
	private SuggestedPoDetailRepository monthlyPoDetailRepository;
230
 
231
	@Autowired
232
	private NotificationService notificationService;
233
 
27088 tejbeer 234
	@Autowired
235
	private RegionRepository regionRepository;
236
 
237
	@Autowired
238
	private PartnerRegionRepository partnerRegionRepository;
239
 
23779 amit.gupta 240
	@RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
25721 tejbeer 241
	public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,
26978 tejbeer 242
			@RequestParam int itemQty, @RequestParam int fofoId) throws Exception {
27088 tejbeer 243
		if (fofoId == 0) {
244
 
245
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
246
			fofoId = loginDetails.getFofoId();
247
 
26990 tejbeer 248
		}
27088 tejbeer 249
 
26082 tejbeer 250
		LocalDate currentMonthDate = LocalDate.now();
251
		MonthlyPlanned monthlyPlanned = null;
25721 tejbeer 252
 
26951 amit.gupta 253
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26082 tejbeer 254
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
26978 tejbeer 255
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
256
			LOGGER.info("monthlyPlanned" + monthlyPlanned);
257
			saveMonthlyPlanned(monthlyPlanned, fofoId, currentMonthDate, catalogId, itemQty);
26082 tejbeer 258
		}
259
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
260
		return "response";
261
	}
262
 
263
	private void saveMonthlyPlanned(MonthlyPlanned monthlyPlanned, int fofoId, LocalDate currentMonthDate,
264
			int catalogId, int itemQty) {
25721 tejbeer 265
		if (monthlyPlanned == null) {
266
			monthlyPlanned = new MonthlyPlanned();
26082 tejbeer 267
			monthlyPlanned.setFofoId(fofoId);
268
			monthlyPlanned.setYearMonth(currentMonthDate);
25721 tejbeer 269
			monthlyPlannedRepository.persist(monthlyPlanned);
270
			PlannedDetail pd = new PlannedDetail();
271
			pd.setCatalogId(catalogId);
272
			pd.setPlannedId(monthlyPlanned.getId());
273
			pd.setQuantity(itemQty);
274
			pd.setUpdatedTimestamp(LocalDateTime.now());
275
			plannedDetailRepository.persist(pd);
276
 
23786 amit.gupta 277
		} else {
25721 tejbeer 278
			PlannedDetail plannedDetail = plannedDetailRepository.selectByPlannedIdCatalogId(monthlyPlanned.getId(),
279
					catalogId);
280
			if (plannedDetail == null) {
281
				plannedDetail = new PlannedDetail();
282
				plannedDetail.setCatalogId(catalogId);
283
				plannedDetail.setPlannedId(monthlyPlanned.getId());
284
				plannedDetail.setQuantity(itemQty);
285
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
286
				plannedDetailRepository.persist(plannedDetail);
287
			} else if (itemQty == 0) {
288
				plannedDetailRepository.delete(plannedDetail);
289
 
290
			} else {
291
				plannedDetail.setCatalogId(catalogId);
292
				plannedDetail.setQuantity(itemQty);
293
				plannedDetail.setUpdatedTimestamp(LocalDateTime.now());
294
			}
295
 
23785 amit.gupta 296
		}
25721 tejbeer 297
 
298
	}
299
 
300
	@RequestMapping(value = "/open-indent/confirm", method = RequestMethod.POST)
26748 tejbeer 301
	public String confirmOpenIndent(HttpServletRequest request,
302
			@RequestParam(required = false, defaultValue = "0") int fofoId, Model model) throws Exception {
303
 
304
		if (fofoId == 0) {
305
			LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
306
			fofoId = loginDetails.getFofoId();
307
		}
25721 tejbeer 308
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
26748 tejbeer 309
 
26951 amit.gupta 310
		LocalDate currentDate = LocalDate.now();
311
		LocalDate planningMonthDate = null;
26082 tejbeer 312
		MonthlyPlanned monthlyPlanned = null;
26951 amit.gupta 313
		if (currentDate.isAfter(currentDate.withDayOfMonth(PLANNING_OPEN_DAY))) {
314
			planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
315
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
25721 tejbeer 316
 
26082 tejbeer 317
			confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
318
		}
319
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
320
 
321
		return "response";
322
	}
323
 
324
	private void confirmMonthlyPlanned(MonthlyPlanned monthlyPlanned, CustomRetailer customRetailer, int fofoId)
325
			throws Exception {
25721 tejbeer 326
		List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());
327
 
328
		List<PlannedModel> plannedModel = new ArrayList<>();
329
		for (PlannedDetail plannedDetail : plannedDetails) {
330
 
331
			List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());
332
			String itemDesription = items.get(0).getItemDescriptionNoColor();
333
			PlannedModel pm = new PlannedModel();
334
			pm.setItemDescription(itemDesription);
335
			pm.setStoreName(customRetailer.getBusinessName());
336
			pm.setQty(plannedDetail.getQuantity());
26082 tejbeer 337
			pm.setFofoId(fofoId);
25721 tejbeer 338
			plannedModel.add(pm);
339
			LOGGER.info("plannedModel" + plannedModel);
340
 
23785 amit.gupta 341
		}
26978 tejbeer 342
		List<String> ccemails = new ArrayList<>();
343
		LOGGER.info("ccemails" + ccemails);
344
		Map<EscalationType, String> emailEsclationType = csService.getAuthUserAndEsclationTypeByPartnerId(fofoId);
345
		LOGGER.info("emailEsclationType" + emailEsclationType);
346
		ccemails.add(emailEsclationType.get(EscalationType.L1));
347
		ccemails.add(emailEsclationType.get(EscalationType.L2));
348
		LOGGER.info("ccemails" + ccemails);
349
		List<String> bccemails = new ArrayList<>();
350
		bccemails.add(emailEsclationType.get(EscalationType.L3));
351
		LOGGER.info("bccemails" + bccemails);
25721 tejbeer 352
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
353
				Arrays.asList("Partner Id", "Partner Name", "Model Name", "Qty"),
354
				plannedModel.stream()
355
						.map(x -> Arrays.asList(x.getFofoId(), x.getStoreName(), x.getItemDescription(), x.getQty()))
356
						.collect(Collectors.toList()));
357
		LOGGER.info("baos" + baos);
26978 tejbeer 358
		Utils.sendMailWithAttachments(googleMailSender, new String[] { customRetailer.getEmail() },
359
				ccemails.toArray(new String[ccemails.size()]), bccemails.toArray(new String[bccemails.size()]),
25721 tejbeer 360
				"Planned Indent", "PFA",
361
				new Attachment[] { new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())), });
362
 
23405 amit.gupta 363
	}
364
 
24231 amit.gupta 365
	@RequestMapping(value = "/indent/download", method = RequestMethod.GET)
366
	public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,
367
			@RequestParam(required = false, defaultValue = "0") int fofoId,
368
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 369
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
370
		Set<Integer> roleIds = loginDetails.getRoleIds();
24231 amit.gupta 371
		LOGGER.info("Counter size is {}", counterSize);
372
		LOGGER.info("Fofo Id is {}", fofoId);
25721 tejbeer 373
		if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {
24231 amit.gupta 374
			List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
375
					.collect(Collectors.toList());
376
			Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
23415 amit.gupta 377
 
24232 amit.gupta 378
			List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,
379
					true);
380
			Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream()
381
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
23405 amit.gupta 382
 
24232 amit.gupta 383
			Map<String, Integer> catalogUserQtyMap = new HashMap<>();
25702 amit.gupta 384
			currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {
24232 amit.gupta 385
				int retailerId = x.getFofoId();
386
				int catalogId;
387
				try {
388
					catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();
389
					String key = catalogId + "-" + retailerId;
390
					if (!catalogUserQtyMap.containsKey(key)) {
391
						catalogUserQtyMap.put(key, 0);
392
					}
393
					catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());
394
				} catch (ProfitMandiBusinessException e) {
395
					// TODO Auto-generated catch block
396
					throw new RuntimeException(e);
24231 amit.gupta 397
				}
398
			});
23779 amit.gupta 399
 
24231 amit.gupta 400
			List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);
24232 amit.gupta 401
			Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {
402
				try {
403
					return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"
404
							+ x.getRetailerId();
405
				} catch (ProfitMandiBusinessException e) {
406
					// TODO Auto-generated catch block
407
					return "";
408
				}
409
			}, Collectors.summingInt(x -> x.getLineItem().getQuantity())));
23779 amit.gupta 410
 
24232 amit.gupta 411
			Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();
412
 
413
			List<TagListing> tagListings = tagListingRepository.selectAll(true);
414
			Iterator<TagListing> iterator = tagListings.iterator();
24231 amit.gupta 415
			while (iterator.hasNext()) {
416
				TagListing tagListing = iterator.next();
417
				Item item = itemRepository.selectById(tagListing.getItemId());
24232 amit.gupta 418
				int catalogId = item.getCatalogItemId();
24231 amit.gupta 419
				if (item.getCategoryId() != 10006) {
420
					continue;
421
				}
23779 amit.gupta 422
 
24232 amit.gupta 423
				int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)
424
						? modelStockAllocationMap.get(catalogId)
425
						: 0;
426
				for (int retailerId : fofoIds) {
427
					String key = catalogId + "-" + retailerId;
428
					if (catalogListingMap.containsKey(key)) {
429
						continue;
24231 amit.gupta 430
					}
24232 amit.gupta 431
					int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;
432
					int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;
433
					if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {
434
						continue;
435
					}
436
					CatalogListingModel catalogListingModel = new CatalogListingModel();
437
					catalogListingModel.setFofoId(retailerId);
438
					catalogListingModel.setModelName(item.getModelName());
439
					catalogListingModel.setModelNumber(item.getModelNumber());
440
					catalogListingModel.setCatalogId(catalogId);
441
					catalogListingModel.setDp(tagListing.getSellingPrice());
442
					catalogListingModel.setMop(tagListing.getMop());
443
					catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
444
					catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);
445
					catalogListingModel.setInTransitQuantity(catalogInTransit);
446
					catalogListingModel
447
							.setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);
24233 amit.gupta 448
					catalogListingModel.setStockInHand(catalogInStock);
24232 amit.gupta 449
					catalogListingModel.setBrand(item.getBrand());
450
					catalogListingModel.setModelName(item.getModelName());
451
					catalogListingModel.setModelNumber(item.getModelNumber());
452
					catalogListingModel.setCategoryId(item.getCategoryId());
453
					catalogListingMap.put(key, catalogListingModel);
23405 amit.gupta 454
				}
455
			}
25853 amit.gupta 456
			List<List<?>> listOfRows = new ArrayList<>();
24231 amit.gupta 457
			for (CatalogListingModel clm : catalogListingMap.values()) {
458
				CustomRetailer cr = customRetailersMap.get(clm.getFofoId());
24349 amit.gupta 459
				listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),
460
						clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),
461
						clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),
462
						clm.getToBeOrdered()));
24231 amit.gupta 463
			}
24349 amit.gupta 464
			ByteArrayOutputStream baos = FileUtil
465
					.getCSVByteStream(
466
							Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number",
467
									"DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
468
							listOfRows);
24231 amit.gupta 469
			HttpHeaders headers = new HttpHeaders();
470
			headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
471
			headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
24232 amit.gupta 472
			return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
473
					HttpStatus.OK);
23405 amit.gupta 474
		}
24231 amit.gupta 475
		return null;
24232 amit.gupta 476
 
23405 amit.gupta 477
	}
478
 
24349 amit.gupta 479
	@RequestMapping(value = "/itemsByCatalogId")
480
	public String getItemsByCatalogId(HttpServletRequest request, Model model,
24410 amit.gupta 481
			@RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
25378 tejbeer 482
			throws ProfitMandiBusinessException {
24410 amit.gupta 483
		if (catalogId == 0) {
484
			catalogId = itemRepository.selectById(itemId).getCatalogItemId();
485
		}
24349 amit.gupta 486
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
24414 amit.gupta 487
		LOGGER.info("Items {}", items);
25378 tejbeer 488
		Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
489
				.collect(Collectors.toMap(Item::getId, Item::getColor));
24413 amit.gupta 490
		Map<Integer, TagListing> tagsMap = tagListingRepository
491
				.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
25378 tejbeer 492
				.stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
24414 amit.gupta 493
		LOGGER.info("Items color map {}", itemsColorMap);
24349 amit.gupta 494
		JSONArray response = new JSONArray();
24413 amit.gupta 495
		itemsColorMap.keySet().stream().forEach(x -> {
25378 tejbeer 496
			response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",
497
					tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));
24349 amit.gupta 498
		});
499
		model.addAttribute("response", response.toString());
500
		return "response";
24410 amit.gupta 501
 
24349 amit.gupta 502
	}
503
 
23405 amit.gupta 504
	@RequestMapping(value = "/indent/loadIndent")
23785 amit.gupta 505
	public String loadOpenIndent(HttpServletRequest request, Model model,
506
			@RequestParam(required = false, defaultValue = "0") int fofoId,
25736 tejbeer 507
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 508
 
509
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
510
		Set<Integer> roleIds = loginDetails.getRoleIds();
23785 amit.gupta 511
		LOGGER.info("Counter size is {}", counterSize);
512
		LOGGER.info("Fofo Id is {}", fofoId);
25736 tejbeer 513
		boolean isAdmin = roleManager.isAdmin(roleIds);
25796 tejbeer 514
 
25797 tejbeer 515
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
516
				.collect(Collectors.toList());
517
 
25796 tejbeer 518
		Map<String, Object> equalsMap = new HashMap<>();
519
		equalsMap.put("categoryId", 10006);
25797 tejbeer 520
		equalsMap.put("brand", brands);
25796 tejbeer 521
		Map<String, List<?>> notEqualsMap = new HashMap<>();
522
 
523
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
524
		Map<Integer, Integer> currentStockMap;
525
 
25721 tejbeer 526
		if (!isAdmin && fofoId == 0) {
23786 amit.gupta 527
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
25796 tejbeer 528
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
529
			equalsStockJoinMap.put("fofoId", fofoId);
530
			currentStockMap = itemRepository
25800 tejbeer 531
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
532
							equalsStockJoinMap, notEqualsJoinMap, "availability")
25796 tejbeer 533
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25797 tejbeer 534
			LOGGER.info("currentStock");
23786 amit.gupta 535
		} else {
536
			if (fofoId == 0) {
25796 tejbeer 537
 
538
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
539
				equalsStockJoinMap.put("fofoId", fofoId);
540
 
541
				currentStockMap = itemRepository
25800 tejbeer 542
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 543
								equalsStockJoinMap, notEqualsJoinMap, "availability")
544
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
545
 
23779 amit.gupta 546
			} else {
25796 tejbeer 547
 
548
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
549
				equalsStockJoinMap.put("fofoId", fofoId);
550
 
551
				currentStockMap = itemRepository
25800 tejbeer 552
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 553
								equalsStockJoinMap, notEqualsJoinMap, "availability")
554
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
555
 
23405 amit.gupta 556
			}
23786 amit.gupta 557
		}
25796 tejbeer 558
 
559
		LOGGER.info("currentStock" + currentStockMap);
25797 tejbeer 560
 
23796 amit.gupta 561
		Map<Integer, Integer> itemsInTransit = null;
23855 amit.gupta 562
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
25702 amit.gupta 563
		if (!isAdmin) {
23786 amit.gupta 564
			tagListings = new ArrayList<>(tagListings);
25797 tejbeer 565
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
23796 amit.gupta 566
			inTransitOrders = this.filterValidOrders(inTransitOrders);
567
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
568
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
569
		} else {
570
			itemsInTransit = new HashMap<>();
23786 amit.gupta 571
		}
25797 tejbeer 572
 
23796 amit.gupta 573
		int totalPcs = 0;
25797 tejbeer 574
 
23796 amit.gupta 575
		float totalAmount = 0;
24231 amit.gupta 576
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
27088 tejbeer 577
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
578
				.collect(Collectors.toList());
25796 tejbeer 579
 
27088 tejbeer 580
		LOGGER.info("regionIds" + regionIds);
581
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
582
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
583
		LOGGER.info("focusedModelMap" + focusedModelMap);
26956 amit.gupta 584
		LocalDate planningMonthDate = null;
26082 tejbeer 585
		MonthlyPlanned monthlyPlanned = null;
26176 tejbeer 586
		List<Integer> fofoOrderIds = null;
26082 tejbeer 587
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 588
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26956 amit.gupta 589
			planningMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
590
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
26082 tejbeer 591
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
26176 tejbeer 592
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
593
					LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
594
					.collect(Collectors.toList());
26082 tejbeer 595
 
596
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 597
		} else {
26956 amit.gupta 598
			planningMonthDate = LocalDate.now().withDayOfMonth(1);
26176 tejbeer 599
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
26956 amit.gupta 600
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, planningMonthDate);
601
			model.addAttribute("planningMonth", planningMonthDate.getMonth());
26176 tejbeer 602
			model.addAttribute("mtd", true);
26131 tejbeer 603
			model.addAttribute("freezed", true);
26176 tejbeer 604
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
605
					curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
606
					.collect(Collectors.toList());
26082 tejbeer 607
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
26978 tejbeer 608
		}
26082 tejbeer 609
 
25721 tejbeer 610
		Map<Integer, Integer> plannedDetailMap = null;
611
		if (monthlyPlanned != null) {
612
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
613
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
614
 
615
		}
25797 tejbeer 616
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
26176 tejbeer 617
 
25796 tejbeer 618
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
619
		Map<String, Object> equalsJoinMap = new HashMap<>();
26618 tejbeer 620
 
25796 tejbeer 621
		equalsJoinMap.put("orderId", fofoOrderIds);
26618 tejbeer 622
		Map<Integer, Integer> last15daysMap = null;
26748 tejbeer 623
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
24231 amit.gupta 624
 
26618 tejbeer 625
			last15daysMap = itemRepository
626
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
627
							notEqualsJoinMap, "quantity")
628
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
629
		}
25796 tejbeer 630
		LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 631
 
25796 tejbeer 632
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
633
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
634
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
635
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
636
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
25797 tejbeer 637
		LOGGER.info("catalogIdItemMap");
24231 amit.gupta 638
 
25796 tejbeer 639
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
25797 tejbeer 640
		equalsItemJoinMap.put("active", 1);
25800 tejbeer 641
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
642
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
25797 tejbeer 643
		LOGGER.info("tagListingCatalogIds");
25796 tejbeer 644
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
645
			int catalogId = catalogIdAggregateValue.getCatalogId();
646
			Item item = catalogIdItemMap.get(catalogId).get(0);
647
			TagListing tagListing = taglistingMap.get(item.getId());
24231 amit.gupta 648
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
649
			if (!catalogListingMap.containsKey(catalogId)) {
650
				catalogListingModel = new CatalogListingModel();
651
				catalogListingModel.setCatalogId(catalogId);
652
				catalogListingModel.setDp(tagListing.getSellingPrice());
653
				catalogListingModel.setMop(tagListing.getMop());
654
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
25721 tejbeer 655
				if (plannedDetailMap != null) {
656
 
657
					Integer quantity = plannedDetailMap.get(catalogId);
658
					if (quantity != null) {
659
						catalogListingModel.setAllocatedQuantity(quantity);
660
					}
661
				}
662
 
25796 tejbeer 663
				if (last15daysMap != null) {
664
					Integer last15DaysSale = last15daysMap.get(catalogId);
665
 
25721 tejbeer 666
					if (last15DaysSale != null) {
667
						catalogListingModel.setLast15DaysSale(last15DaysSale);
668
					} else {
669
						catalogListingModel.setLast15DaysSale(0);
670
					}
671
				} else {
672
					catalogListingModel.setLast15DaysSale(0);
673
				}
674
 
24231 amit.gupta 675
				catalogListingModel.setBrand(item.getBrand());
676
				if (item.getCategoryId() == 10006) {
677
					catalogListingModel.setCategoryId(item.getCategoryId());
678
				}
25721 tejbeer 679
 
680
				FocusedModel fm = focusedModelMap.get(catalogId);
681
				if (fm != null) {
682
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
683
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
684
 
685
				} else {
686
					catalogListingModel.setRecommendedQty(0);
687
					catalogListingModel.setMinimumQty(0);
688
				}
689
 
24231 amit.gupta 690
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 691
 
24231 amit.gupta 692
			}
25736 tejbeer 693
			int itemAvailability = 0;
25796 tejbeer 694
			if (currentStockMap != null) {
695
				Integer qty = currentStockMap.get(catalogId);
25736 tejbeer 696
				itemAvailability = qty == null ? 0 : qty;
697
				catalogListingModel.setStockInHand(itemAvailability);
698
			} else {
699
				catalogListingModel.setStockInHand(0);
700
			}
24231 amit.gupta 701
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
702
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
703
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
26179 tejbeer 704
			if (plannedDetailMap != null) {
26177 tejbeer 705
				if (plannedDetailMap.get(catalogId) != null) {
24231 amit.gupta 706
 
26177 tejbeer 707
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
708
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
709
					LOGGER.info("remaning" + remaining);
26176 tejbeer 710
 
26177 tejbeer 711
					if (remaining != 0) {
712
						catalogListingModel.setRemaining(remaining);
713
					} else {
714
						catalogListingModel.setRemaining(0);
715
					}
26176 tejbeer 716
				}
717
			}
23786 amit.gupta 718
		}
25721 tejbeer 719
 
26963 amit.gupta 720
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
23786 amit.gupta 721
		if (fofoId > 0) {
722
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
723
			model.addAttribute("retailerName",
724
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
725
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
726
			model.addAttribute("retailerId", customRetailer.getPartnerId());
727
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 728
		} else {
23786 amit.gupta 729
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 730
		}
23786 amit.gupta 731
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 732
 
733
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
734
 
25721 tejbeer 735
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 736
				Comparator.reverseOrder());
25721 tejbeer 737
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25796 tejbeer 738
		model.addAttribute("catalogTagListings",
739
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 740
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
26177 tejbeer 741
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26956 amit.gupta 742
		model.addAttribute("previousPlanningMonth", planningMonthDate.minusMonths(1).getMonth());
743
		model.addAttribute("currentPlanningMonth", planningMonthDate.getMonth());
26131 tejbeer 744
 
23786 amit.gupta 745
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 746
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 747
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 748
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 749
		return "open-indent";
25796 tejbeer 750
 
23405 amit.gupta 751
	}
23796 amit.gupta 752
 
26131 tejbeer 753
	@RequestMapping(value = "/indent/loadIndentPreviousMonth")
754
	public String previousMonthLoadOpenIndent(HttpServletRequest request, Model model,
755
			@RequestParam(required = false, defaultValue = "0") int fofoId,
756
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
26956 amit.gupta 757
		LocalDate planMonthStart = null;
758
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
759
			planMonthStart = LocalDate.now().plusMonths(1).withDayOfMonth(1);
760
		} else {
761
			planMonthStart = LocalDate.now().withDayOfMonth(1);
762
		}
26131 tejbeer 763
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
764
		Set<Integer> roleIds = loginDetails.getRoleIds();
765
		LOGGER.info("Counter size is {}", counterSize);
766
		LOGGER.info("Fofo Id is {}", fofoId);
767
		boolean isAdmin = roleManager.isAdmin(roleIds);
768
 
769
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
770
				.collect(Collectors.toList());
771
 
772
		Map<String, Object> equalsMap = new HashMap<>();
773
		equalsMap.put("categoryId", 10006);
774
		equalsMap.put("brand", brands);
775
		Map<String, List<?>> notEqualsMap = new HashMap<>();
776
 
777
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
778
		Map<Integer, Integer> currentStockMap;
779
 
780
		if (!isAdmin && fofoId == 0) {
781
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
782
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
783
			equalsStockJoinMap.put("fofoId", fofoId);
784
			currentStockMap = itemRepository
785
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
786
							equalsStockJoinMap, notEqualsJoinMap, "availability")
787
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
788
			LOGGER.info("currentStock");
789
		} else {
790
			if (fofoId == 0) {
791
 
792
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
793
				equalsStockJoinMap.put("fofoId", fofoId);
794
 
795
				currentStockMap = itemRepository
796
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
797
								equalsStockJoinMap, notEqualsJoinMap, "availability")
798
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
799
 
800
			} else {
801
 
802
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
803
				equalsStockJoinMap.put("fofoId", fofoId);
804
 
805
				currentStockMap = itemRepository
806
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
807
								equalsStockJoinMap, notEqualsJoinMap, "availability")
808
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
809
 
810
			}
811
		}
812
 
813
		LOGGER.info("currentStock" + currentStockMap);
814
 
815
		Map<Integer, Integer> itemsInTransit = null;
816
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
817
		if (!isAdmin) {
818
			tagListings = new ArrayList<>(tagListings);
819
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
820
			inTransitOrders = this.filterValidOrders(inTransitOrders);
821
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
822
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
823
		} else {
824
			itemsInTransit = new HashMap<>();
825
		}
826
 
827
		int totalPcs = 0;
828
 
829
		float totalAmount = 0;
830
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
831
 
27088 tejbeer 832
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
833
				.collect(Collectors.toList());
26131 tejbeer 834
 
27088 tejbeer 835
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
836
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
837
 
26978 tejbeer 838
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId,
839
				planMonthStart.minusMonths(1));
26956 amit.gupta 840
		model.addAttribute("planningMonth", planMonthStart.minusMonths(1).getMonth());
841
		model.addAttribute("previousPlanningMonth", planMonthStart.minusMonths(1).getMonth());
842
		model.addAttribute("currentPlanningMonth", planMonthStart.getMonth());
26131 tejbeer 843
 
844
		Map<Integer, Integer> plannedDetailMap = null;
845
		if (monthlyPlanned != null) {
846
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
847
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
848
 
849
		}
850
 
851
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
852
		List<Integer> fofoOrderIds = fofoOrderRepository
853
				.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
26978 tejbeer 854
						planMonthStart.minusMonths(1).atStartOfDay(), planMonthStart.atStartOfDay())
26131 tejbeer 855
				.stream().map(x -> x.getId()).collect(Collectors.toList());
26721 tejbeer 856
 
26131 tejbeer 857
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
858
		Map<String, Object> equalsJoinMap = new HashMap<>();
859
		equalsJoinMap.put("orderId", fofoOrderIds);
26721 tejbeer 860
		Map<Integer, Integer> lastMonthSaleMap = null;
861
		if (!fofoOrderIds.isEmpty()) {
862
			lastMonthSaleMap = itemRepository
863
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
864
							notEqualsJoinMap, "quantity")
865
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
866
		}
26131 tejbeer 867
		LOGGER.info("lastMonthSaleMap" + lastMonthSaleMap);
868
 
869
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
870
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
871
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
872
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
873
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
874
		LOGGER.info("catalogIdItemMap");
875
 
876
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
877
		equalsItemJoinMap.put("active", 1);
878
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
879
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
880
		LOGGER.info("tagListingCatalogIds");
881
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
882
			int catalogId = catalogIdAggregateValue.getCatalogId();
883
			Item item = catalogIdItemMap.get(catalogId).get(0);
884
			TagListing tagListing = taglistingMap.get(item.getId());
885
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
886
			if (!catalogListingMap.containsKey(catalogId)) {
887
				catalogListingModel = new CatalogListingModel();
888
				catalogListingModel.setCatalogId(catalogId);
889
				catalogListingModel.setDp(tagListing.getSellingPrice());
890
				catalogListingModel.setMop(tagListing.getMop());
891
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
892
				if (plannedDetailMap != null) {
893
 
894
					Integer quantity = plannedDetailMap.get(catalogId);
895
					if (quantity != null) {
896
						catalogListingModel.setAllocatedQuantity(quantity);
897
					}
898
				}
899
 
900
				if (lastMonthSaleMap != null) {
901
					Integer lastMonthSale = lastMonthSaleMap.get(catalogId);
902
 
903
					if (lastMonthSale != null) {
904
						catalogListingModel.setLastMonthSaleMap(lastMonthSale);
905
					} else {
906
						catalogListingModel.setLastMonthSaleMap(0);
907
					}
908
				} else {
909
					catalogListingModel.setLast15DaysSale(0);
910
				}
911
 
912
				catalogListingModel.setBrand(item.getBrand());
913
				if (item.getCategoryId() == 10006) {
914
					catalogListingModel.setCategoryId(item.getCategoryId());
915
				}
916
 
917
				FocusedModel fm = focusedModelMap.get(catalogId);
918
				if (fm != null) {
919
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
920
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
921
 
922
				} else {
923
					catalogListingModel.setRecommendedQty(0);
924
					catalogListingModel.setMinimumQty(0);
925
				}
926
 
927
				catalogListingMap.put(catalogId, catalogListingModel);
928
 
929
			}
930
			int itemAvailability = 0;
931
			if (currentStockMap != null) {
932
				Integer qty = currentStockMap.get(catalogId);
933
				itemAvailability = qty == null ? 0 : qty;
934
				catalogListingModel.setStockInHand(itemAvailability);
935
			} else {
936
				catalogListingModel.setStockInHand(0);
937
			}
938
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
939
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
940
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
941
 
942
		}
943
 
26963 amit.gupta 944
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26131 tejbeer 945
		if (fofoId > 0) {
946
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
947
			model.addAttribute("retailerName",
948
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
949
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
950
			model.addAttribute("retailerId", customRetailer.getPartnerId());
951
			model.addAttribute("counterSize", fs.getCounterSize().toString());
952
		} else {
953
			model.addAttribute("counterSize", counterSize.toString());
954
		}
955
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
956
 
957
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
958
 
959
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
960
				Comparator.reverseOrder());
961
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
962
		model.addAttribute("catalogTagListings",
963
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
964
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
965
		model.addAttribute("previousMonth", true);
966
		model.addAttribute("freezed", true);
26177 tejbeer 967
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
26131 tejbeer 968
		model.addAttribute("customRetailers", customRetailers);
969
		model.addAttribute("totalAmount", totalAmount);
970
		model.addAttribute("monthlyPlanned", monthlyPlanned);
971
		model.addAttribute("totalPcs", totalPcs);
972
		return "open-indent";
973
 
974
	}
975
 
23796 amit.gupta 976
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
25812 amit.gupta 977
		int orderRemovedCount = 0;
23796 amit.gupta 978
		Iterator<Order> orderIterator = lastOrdersList.iterator();
979
		while (orderIterator.hasNext()) {
980
			Order o = orderIterator.next();
981
			if (o.getInvoiceNumber() != null) {
982
				try {
983
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
984
					orderIterator.remove();
25812 amit.gupta 985
					orderRemovedCount++;
23796 amit.gupta 986
				} catch (Exception e) {
987
 
988
				}
989
			}
990
		}
25812 amit.gupta 991
		LOGGER.info("Order removed count is {}", orderRemovedCount);
23796 amit.gupta 992
		return lastOrdersList;
993
	}
994
 
24406 amit.gupta 995
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
24410 amit.gupta 996
	public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
997
			throws Exception {
24406 amit.gupta 998
		JSONArray jsonArray = new JSONArray(jsonArrayString);
24410 amit.gupta 999
		for (int i = 0; i < jsonArray.length(); i++) {
24406 amit.gupta 1000
			JSONObject obj = jsonArray.getJSONObject(i);
25378 tejbeer 1001
 
24406 amit.gupta 1002
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
25378 tejbeer 1003
			if (tl == null) {
1004
				continue;
1005
			} else {
1006
				tl.setActive(obj.getBoolean("active"));
1007
				tagListingRepository.persist(tl);
1008
			}
24406 amit.gupta 1009
		}
24410 amit.gupta 1010
		model.addAttribute("response", true);
23855 amit.gupta 1011
		return "response";
1012
	}
24231 amit.gupta 1013
 
1014
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
23796 amit.gupta 1015
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
1016
		boolean success = false;
1017
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1018
		int fofoId = loginDetails.getFofoId();
1019
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
1020
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
1021
		Client userClient = new UserClient().getClient();
24231 amit.gupta 1022
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
23796 amit.gupta 1023
 
24231 amit.gupta 1024
		if (totalAmount > 0) {
23796 amit.gupta 1025
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
1026
			User user = userRepository.selectById(loginDetails.getFofoId());
1027
			userClient = new UserClient().getClient();
1028
			LOGGER.info("Setting wallet amount in cart");
24231 amit.gupta 1029
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
1030
					7890, OrderSource.WEBSITE.getValue(), true);
23796 amit.gupta 1031
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
1032
			createPayment(user, totalAmount, transactionId);
24231 amit.gupta 1033
			TransactionService.Client transactionClient = new TransactionClient().getClient();
23796 amit.gupta 1034
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
24231 amit.gupta 1035
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 1036
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
24231 amit.gupta 1037
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 1038
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
1039
			transactionClient = new TransactionClient().getClient();
1040
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
1041
			try {
1042
				transactionClient.enqueueTransactionInfoEmail(transactionId);
1043
			} catch (Exception e1) {
1044
				e1.printStackTrace();
1045
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
1046
			}
1047
			resetCart(transactionClient.getTransaction(transactionId));
1048
		}
1049
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
1050
		return "response";
1051
	}
24231 amit.gupta 1052
 
1053
	private void createPayment(User user, double totalAmount, long transactionId)
1054
			throws NumberFormatException, PaymentException, TException {
23796 amit.gupta 1055
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
1056
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
1057
		paymentAttributes.add(new Attribute("payMethod", "7890"));
24231 amit.gupta 1058
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
1059
				false);
1060
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
1061
				PaymentStatus.SUCCESS, null, paymentAttributes);
23796 amit.gupta 1062
	}
24231 amit.gupta 1063
 
23796 amit.gupta 1064
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
1065
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
24231 amit.gupta 1066
		/*
1067
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
1068
		 * currentInventorySnapshots = currentInventorySnapshotRepository
1069
		 * .selectItemsStock(fofoId); itemCisMap =
1070
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
1071
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1072
		 * List<StockAllocationModel> stockAllocationList =
1073
		 * stockAllocationService.getStockAllocation(fofoId, true);
1074
		 * 
1075
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
1076
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
1077
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
1078
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
1079
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
1080
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
1081
		 * validOrderStatusList); inTransitOrders =
1082
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
1083
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
1084
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
1085
		 * x.getLineItem().getQuantity())));
1086
		 * 
1087
		 * Iterator<TagListing> iterator = tagListings.iterator();
1088
		 * 
1089
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
1090
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
1091
		 * tagListing.getAllocatedQuantity()); if
1092
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
1093
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
1094
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
1095
		 * itemCisMap.get(tagListing.getItemId());
1096
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
1097
		 * itemIdAvailability.getAvailability()); StockAllocationModel
1098
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
1099
		 * 
1100
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
1101
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
1102
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
1103
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
1104
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
1105
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
1106
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
1107
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
1108
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
1109
		 */
23796 amit.gupta 1110
		return itemQuantities;
1111
 
1112
	}
24231 amit.gupta 1113
 
23796 amit.gupta 1114
	private long resetCart(Transaction transaction) {
1115
		long sum = 0;
1116
		Map<Long, Double> items = new HashMap<Long, Double>();
1117
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
1118
			sum += order.getGvAmount();
1119
			for (LineItem lineitem : order.getLineitems()) {
1120
				Long itemId = lineitem.getItem_id();
1121
				Double quantity = items.get(itemId);
1122
				if (quantity == null) {
1123
					quantity = lineitem.getQuantity();
1124
				} else {
1125
					quantity = quantity + lineitem.getQuantity();
1126
				}
1127
				items.put(itemId, quantity);
1128
			}
1129
		}
1130
 
1131
		LOGGER.debug("Items to reset in cart are: " + items);
1132
 
1133
		try {
1134
			Client userClient = new UserClient().getClient();
1135
			userClient.resetCart(transaction.getShoppingCartid(), items);
1136
		} catch (TException e) {
1137
			LOGGER.error("Error while updating information in payment database.", e);
1138
		} catch (ShoppingCartException e) {
1139
			LOGGER.error("Error while reseting the cart in cart database.", e);
1140
		} catch (Exception e) {
1141
			LOGGER.error("Unexpected exception", e);
1142
		}
1143
		return sum;
1144
	}
1145
 
25721 tejbeer 1146
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
1147
	public String getFocusedModel(HttpServletRequest request,
1148
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1149
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1150
			throws ProfitMandiBusinessException {
25736 tejbeer 1151
 
1152
		long size = 0;
25721 tejbeer 1153
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
27081 tejbeer 1154
 
25736 tejbeer 1155
		size = focusedModelRepository.selectAllCount();
1156
		if (!focusedModels.isEmpty()) {
1157
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
27088 tejbeer 1158
			Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25721 tejbeer 1159
 
27088 tejbeer 1160
			LOGGER.info("regionMap" + regionMap);
25736 tejbeer 1161
			model.addAttribute("focusedModels", focusedModels);
1162
			model.addAttribute("itemMap", itemMap);
27088 tejbeer 1163
			model.addAttribute("regionMap", regionMap);
25736 tejbeer 1164
			model.addAttribute("start", offset + 1);
1165
			model.addAttribute("size", size);
1166
			model.addAttribute("url", "/getPaginatedFocusedModel");
1167
 
1168
			if (focusedModels.size() < limit) {
1169
				model.addAttribute("end", offset + focusedModels.size());
1170
			} else {
1171
				model.addAttribute("end", offset + limit);
1172
			}
1173
		} else {
1174
 
1175
			model.addAttribute("walletRequest", focusedModels);
1176
			model.addAttribute("size", size);
1177
 
1178
		}
1179
 
27088 tejbeer 1180
		List<Region> regions = regionRepository.selectAll();
27081 tejbeer 1181
 
27088 tejbeer 1182
		model.addAttribute("regions", regions);
1183
 
25721 tejbeer 1184
		return "focused_model";
1185
	}
1186
 
25736 tejbeer 1187
	@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
1188
	public String getPaginatedFocusedModel(HttpServletRequest request,
1189
			@RequestParam(name = "offset", defaultValue = "0") int offset,
1190
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
1191
			throws ProfitMandiBusinessException {
1192
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
1193
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
1194
 
1195
		if (!focusedModels.isEmpty()) {
1196
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
27088 tejbeer 1197
			Map<Integer, Region> regionMap = this.getRegionByRegionId(focusedModels);
25736 tejbeer 1198
			model.addAttribute("focusedModels", focusedModels);
1199
			model.addAttribute("itemMap", itemMap);
27088 tejbeer 1200
			model.addAttribute("regionMap", regionMap);
25736 tejbeer 1201
			model.addAttribute("url", "/getPaginatedFocusedModel");
1202
		} else {
1203
			model.addAttribute("focusedModels", focusedModels);
1204
 
1205
		}
27081 tejbeer 1206
 
27088 tejbeer 1207
		List<Region> regions = regionRepository.selectAll();
1208
 
1209
		model.addAttribute("regions", regions);
25736 tejbeer 1210
		return "focused-model-paginated";
1211
	}
1212
 
25721 tejbeer 1213
	private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
1214
		Map<Integer, Item> itemMap = new HashMap<>();
1215
		for (FocusedModel focusedModel : focusedModels) {
1216
			List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
1217
			itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
1218
		}
1219
 
1220
		return itemMap;
1221
	}
1222
 
27088 tejbeer 1223
	private Map<Integer, Region> getRegionByRegionId(List<FocusedModel> focusedModels) {
1224
		Map<Integer, Region> regionMap = new HashMap<>();
1225
		for (FocusedModel focusedModel : focusedModels) {
1226
			Region region = regionRepository.selectById(focusedModel.getRegionId());
1227
			regionMap.put(region.getId(), region);
1228
		}
1229
 
1230
		return regionMap;
1231
	}
1232
 
25721 tejbeer 1233
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
1234
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int recommended,
27088 tejbeer 1235
			@RequestParam int minimumQty, @RequestParam int regionId, Model model) throws ProfitMandiBusinessException {
25721 tejbeer 1236
 
1237
		FocusedModel fm = new FocusedModel();
1238
		fm.setCatalogId(catalogId);
1239
		fm.setMinimumQty(minimumQty);
1240
		fm.setRecommendedQty(recommended);
27088 tejbeer 1241
		fm.setRegionId(regionId);
25721 tejbeer 1242
		fm.setCreatedTimestamp(LocalDateTime.now());
1243
		focusedModelRepository.persist(fm);
1244
		return "focused_model";
1245
	}
1246
 
1247
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
1248
	public String removeFocusedModelItem(HttpServletRequest request,
27081 tejbeer 1249
			@RequestParam(name = "id", defaultValue = "0") int id, Model model) throws Exception {
25721 tejbeer 1250
 
27081 tejbeer 1251
		focusedModelRepository.deleteById(id);
25721 tejbeer 1252
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1253
		return "response";
1254
	}
25736 tejbeer 1255
 
25798 tejbeer 1256
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
1257
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 1258
 
25798 tejbeer 1259
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
1260
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
1261
 
1262
		mobileBrands.stream().forEach(x -> {
1263
			String brand = (String) x.get("name");
1264
			if (brandStockPricesMap.containsKey(brand)) {
1265
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
1266
				brandStockPrice.setBrandUrl((String) x.get("url"));
1267
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
1268
				brandStockPrices.add(brandStockPrice);
1269
			}
1270
		});
1271
 
1272
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
1273
				.collect(Collectors.toList());
1274
	}
1275
 
26721 tejbeer 1276
	@RequestMapping(value = "/getPartnerAllocation")
1277
	public String getPartnerAllocation(HttpServletRequest request, Model model) throws Exception {
1278
 
1279
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1280
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1281
 
1282
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1283
 
1284
		List<Integer> fofoIds = pp.get(authUser.getId());
1285
 
1286
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
1287
		Map<Integer, FofoStore> fofoStoreMap = fofoStoreRepository.selectByRetailerIds(fofoIds).stream()
1288
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1289
 
1290
		model.addAttribute("customRetailersMap", customRetailersMap);
1291
		model.addAttribute("fofoStoreMap", fofoStoreMap);
1292
		return "partners_allocation";
1293
 
1294
	}
1295
 
26846 tejbeer 1296
	@RequestMapping(value = "/partnerPendingOrder")
1297
	public String partnerPendingOrder(HttpServletRequest request, Model model) throws Exception {
1298
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1299
		AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
1300
 
1301
		Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1302
 
1303
		List<Integer> fofoIds = pp.get(authUser.getId());
1304
 
1305
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
1306
 
1307
		model.addAttribute("customRetailersMap", customRetailersMap);
1308
 
1309
		return "partner-po";
1310
 
1311
	}
1312
 
1313
	@RequestMapping(value = "/getPartnerloadContent")
1314
	public String getPartnerloadContent(HttpServletRequest request, Model model,
1315
			@RequestParam(required = false, defaultValue = "0") int fofoId,
1316
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
1317
 
1318
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1319
		Set<Integer> roleIds = loginDetails.getRoleIds();
1320
		LOGGER.info("Counter size is {}", counterSize);
1321
		LOGGER.info("Fofo Id is {}", fofoId);
1322
		boolean isAdmin = roleManager.isAdmin(roleIds);
1323
 
1324
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
1325
				.collect(Collectors.toList());
1326
 
1327
		Map<String, Object> equalsMap = new HashMap<>();
1328
		equalsMap.put("categoryId", 10006);
1329
		equalsMap.put("brand", brands);
1330
		Map<String, List<?>> notEqualsMap = new HashMap<>();
1331
 
1332
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
1333
		Map<Integer, Integer> currentStockMap;
1334
 
1335
		if (!isAdmin && fofoId == 0) {
1336
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
1337
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
1338
			equalsStockJoinMap.put("fofoId", fofoId);
1339
			currentStockMap = itemRepository
1340
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1341
							equalsStockJoinMap, notEqualsJoinMap, "availability")
1342
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1343
			LOGGER.info("currentStock");
1344
		} else {
1345
			if (fofoId == 0) {
1346
 
1347
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1348
				equalsStockJoinMap.put("fofoId", fofoId);
1349
 
1350
				currentStockMap = itemRepository
1351
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1352
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1353
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1354
 
1355
			} else {
1356
 
1357
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
1358
				equalsStockJoinMap.put("fofoId", fofoId);
1359
 
1360
				currentStockMap = itemRepository
1361
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
1362
								equalsStockJoinMap, notEqualsJoinMap, "availability")
1363
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1364
 
1365
			}
1366
		}
1367
 
1368
		LOGGER.info("currentStock" + currentStockMap);
1369
 
1370
		Map<Integer, Integer> itemsInTransit = null;
1371
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
1372
		if (!isAdmin) {
1373
			tagListings = new ArrayList<>(tagListings);
1374
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
1375
			inTransitOrders = this.filterValidOrders(inTransitOrders);
1376
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
1377
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
1378
		} else {
1379
			itemsInTransit = new HashMap<>();
1380
		}
1381
 
1382
		int totalPcs = 0;
1383
 
1384
		float totalAmount = 0;
1385
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
1386
 
27088 tejbeer 1387
		List<Integer> regionIds = partnerRegionRepository.selectByfofoId(fofoId).stream().map(x -> x.getRegionId())
1388
				.collect(Collectors.toList());
26846 tejbeer 1389
 
27088 tejbeer 1390
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAllByRegionIds(regionIds).stream()
1391
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
1392
 
26846 tejbeer 1393
		LocalDate currentMonthDate = LocalDate.now();
1394
		MonthlyPlanned monthlyPlanned = null;
1395
		List<Integer> fofoOrderIds = null;
1396
		LOGGER.info("localDate" + LocalDate.now());
26951 amit.gupta 1397
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(PLANNING_OPEN_DAY))) {
26846 tejbeer 1398
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
1399
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1400
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
1401
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1402
					LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
1403
					.collect(Collectors.toList());
1404
 
1405
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
26951 amit.gupta 1406
		} else {
26846 tejbeer 1407
			currentMonthDate = LocalDate.now().withDayOfMonth(1);
1408
			LocalDateTime curDate = LocalDate.now().atStartOfDay();
1409
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
1410
			model.addAttribute("planningMonth", currentMonthDate.getMonth());
1411
			model.addAttribute("mtd", true);
1412
			model.addAttribute("freezed", true);
1413
			fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
1414
					curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX)).stream().map(x -> x.getId())
1415
					.collect(Collectors.toList());
1416
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
1417
		}
1418
 
1419
		Map<Integer, Integer> plannedDetailMap = null;
1420
		if (monthlyPlanned != null) {
1421
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
1422
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
1423
 
1424
		}
1425
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
1426
 
1427
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
1428
		Map<String, Object> equalsJoinMap = new HashMap<>();
1429
 
1430
		equalsJoinMap.put("orderId", fofoOrderIds);
1431
		Map<Integer, Integer> last15daysMap = null;
1432
		if (fofoOrderIds != null && !fofoOrderIds.isEmpty()) {
1433
 
1434
			last15daysMap = itemRepository
1435
					.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
1436
							notEqualsJoinMap, "quantity")
1437
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
1438
		}
1439
		LOGGER.info("last15daysMap" + last15daysMap);
1440
 
1441
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
1442
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
1443
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
1444
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
1445
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
1446
		LOGGER.info("catalogIdItemMap");
1447
 
1448
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
1449
		equalsItemJoinMap.put("active", 1);
1450
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
1451
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
1452
		LOGGER.info("tagListingCatalogIds");
1453
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
1454
			int catalogId = catalogIdAggregateValue.getCatalogId();
1455
			Item item = catalogIdItemMap.get(catalogId).get(0);
1456
			TagListing tagListing = taglistingMap.get(item.getId());
1457
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
1458
			if (!catalogListingMap.containsKey(catalogId)) {
1459
				catalogListingModel = new CatalogListingModel();
1460
				catalogListingModel.setCatalogId(catalogId);
1461
				catalogListingModel.setDp(tagListing.getSellingPrice());
1462
				catalogListingModel.setMop(tagListing.getMop());
1463
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
1464
				if (plannedDetailMap != null) {
1465
 
1466
					Integer quantity = plannedDetailMap.get(catalogId);
1467
					if (quantity != null) {
1468
						catalogListingModel.setAllocatedQuantity(quantity);
1469
					}
1470
				}
1471
 
1472
				if (last15daysMap != null) {
1473
					Integer last15DaysSale = last15daysMap.get(catalogId);
1474
 
1475
					if (last15DaysSale != null) {
1476
						catalogListingModel.setLast15DaysSale(last15DaysSale);
1477
					} else {
1478
						catalogListingModel.setLast15DaysSale(0);
1479
					}
1480
				} else {
1481
					catalogListingModel.setLast15DaysSale(0);
1482
				}
1483
 
1484
				catalogListingModel.setBrand(item.getBrand());
1485
				if (item.getCategoryId() == 10006) {
1486
					catalogListingModel.setCategoryId(item.getCategoryId());
1487
				}
1488
 
1489
				FocusedModel fm = focusedModelMap.get(catalogId);
1490
				if (fm != null) {
1491
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
1492
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
1493
 
1494
				} else {
1495
					catalogListingModel.setRecommendedQty(0);
1496
					catalogListingModel.setMinimumQty(0);
1497
				}
1498
 
1499
				catalogListingMap.put(catalogId, catalogListingModel);
1500
 
1501
			}
1502
			int itemAvailability = 0;
1503
			if (currentStockMap != null) {
1504
				Integer qty = currentStockMap.get(catalogId);
1505
				itemAvailability = qty == null ? 0 : qty;
1506
				catalogListingModel.setStockInHand(itemAvailability);
1507
			} else {
1508
				catalogListingModel.setStockInHand(0);
1509
			}
1510
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
1511
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
1512
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
1513
			if (plannedDetailMap != null) {
1514
				if (plannedDetailMap.get(catalogId) != null) {
1515
 
1516
					int remaining = plannedDetailMap.get(catalogId) - catalogListingModel.getLast15DaysSale()
1517
							+ catalogListingModel.getStockInHand() + catalogListingModel.getInTransitQuantity();
1518
					LOGGER.info("remaning" + remaining);
1519
 
1520
					if (remaining != 0) {
1521
						catalogListingModel.setRemaining(remaining);
1522
					} else {
1523
						catalogListingModel.setRemaining(0);
1524
					}
1525
				}
1526
			}
1527
		}
1528
 
26963 amit.gupta 1529
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(false);
26846 tejbeer 1530
		if (fofoId > 0) {
1531
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
1532
			model.addAttribute("retailerName",
1533
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
1534
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
1535
			model.addAttribute("retailerId", customRetailer.getPartnerId());
1536
			model.addAttribute("counterSize", fs.getCounterSize().toString());
1537
		} else {
1538
			model.addAttribute("counterSize", counterSize.toString());
1539
		}
1540
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
1541
 
1542
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
1543
 
1544
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
1545
				Comparator.reverseOrder());
1546
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
1547
		model.addAttribute("catalogTagListings",
1548
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
1549
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
1550
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
1551
		model.addAttribute("previousPlanningMonth", LocalDate.now().minusMonths(1).getMonth());
1552
		model.addAttribute("currentPlanningMonth", LocalDate.now().getMonth());
1553
 
1554
		model.addAttribute("customRetailers", customRetailers);
1555
		model.addAttribute("totalAmount", totalAmount);
1556
		model.addAttribute("monthlyPlanned", monthlyPlanned);
1557
		model.addAttribute("totalPcs", totalPcs);
1558
 
1559
		UserWallet userWallet = walletService.getUserWallet(fofoId);
1560
 
1561
		model.addAttribute("userWallet", userWallet);
1562
 
1563
		return "create-partner-po";
1564
 
1565
	}
1566
 
1567
	@RequestMapping(value = "/createPo", method = RequestMethod.POST)
1568
	public String createPo(HttpServletRequest request, @RequestBody SuggestedPoModel monthlyPoModel, Model model)
1569
			throws Exception {
1570
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1571
		SuggestedPo mp = new SuggestedPo();
1572
		mp.setFofoId(monthlyPoModel.getFofoId());
1573
		mp.setCreateTimestamp(LocalDateTime.now());
1574
		mp.setStatus("open");
1575
		mp.setAuthId(loginDetails.getEmailId());
1576
		monthlyPoRepository.persist(mp);
1577
 
1578
		for (SuggestedPoIdModel poId : monthlyPoModel.getPoIds()) {
1579
			SuggestedPoDetail mpd = new SuggestedPoDetail();
1580
			mpd.setItemId(poId.getItemId());
1581
			mpd.setQuantity(poId.getQty());
1582
			mpd.setUpdatedTimestamp(LocalDateTime.now());
1583
			mpd.setPoId(mp.getId());
1584
			monthlyPoDetailRepository.persist(mpd);
1585
		}
1586
 
1587
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
1588
		sendNotificationModel.setCampaignName("Alert");
1589
		sendNotificationModel.setMessage("Suggested Po");
1590
		sendNotificationModel.setType("url");
1591
		sendNotificationModel.setTitle("Alert");
26951 amit.gupta 1592
		sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/partnerPo/" + mp.getId());
26846 tejbeer 1593
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(2));
1594
		sendNotificationModel.setMessageType(MessageType.notification);
1595
		int userId = userAccountRepository.selectUserIdByRetailerId(monthlyPoModel.getFofoId());
1596
 
1597
		sendNotificationModel.setUserIds(Arrays.asList(userId));
1598
		notificationService.sendNotification(sendNotificationModel);
1599
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
1600
 
1601
		return "response";
1602
	}
1603
 
1604
	@RequestMapping(value = "/selectItemColor", method = RequestMethod.GET)
1605
	public String selectItemColor(HttpServletRequest request, @RequestParam int catalogId, Model model)
1606
			throws Exception {
1607
 
1608
		List<Item> selecteditems = itemRepository.selectAllByCatalogItemId(catalogId);
1609
 
1610
		List<Item> items = new ArrayList<>();
1611
		for (Item item : selecteditems) {
1612
 
1613
			TagListing tagListing = tagListingRepository.selectByItemId(item.getId(), true);
1614
 
1615
			if (tagListing != null) {
1616
				items.add(item);
1617
			}
1618
 
1619
		}
1620
		model.addAttribute("items", items);
1621
		LOGGER.info("itemIdAndColorMap" + items);
1622
		return "select-item-color";
1623
	}
1624
 
25721 tejbeer 1625
}