Subversion Repositories SmartDukaan

Rev

Rev 25853 | Rev 26131 | 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
 
24824 govind 3
import java.io.Serializable;
25721 tejbeer 4
import java.time.LocalDate;
5
import java.time.LocalDateTime;
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;
23405 amit.gupta 43
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
25798 tejbeer 44
import com.spice.profitmandi.common.model.BrandStockPrice;
25796 tejbeer 45
import com.spice.profitmandi.common.model.CatalogIdAggregateValue;
24231 amit.gupta 46
import com.spice.profitmandi.common.model.CatalogListingModel;
23785 amit.gupta 47
import com.spice.profitmandi.common.model.CustomRetailer;
25721 tejbeer 48
import com.spice.profitmandi.common.model.PlannedModel;
23779 amit.gupta 49
import com.spice.profitmandi.common.model.StockAllocationModel;
24231 amit.gupta 50
import com.spice.profitmandi.common.util.FileUtil;
25721 tejbeer 51
import com.spice.profitmandi.common.util.Utils;
52
import com.spice.profitmandi.common.util.Utils.Attachment;
53
import com.spice.profitmandi.dao.entity.catalog.FocusedModel;
23785 amit.gupta 54
import com.spice.profitmandi.dao.entity.catalog.Item;
23405 amit.gupta 55
import com.spice.profitmandi.dao.entity.catalog.TagListing;
25796 tejbeer 56
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
57
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
23785 amit.gupta 58
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
25721 tejbeer 59
import com.spice.profitmandi.dao.entity.fofo.MonthlyPlanned;
60
import com.spice.profitmandi.dao.entity.fofo.PlannedDetail;
23796 amit.gupta 61
import com.spice.profitmandi.dao.entity.transaction.Order;
62
import com.spice.profitmandi.dao.entity.user.User;
25721 tejbeer 63
import com.spice.profitmandi.dao.repository.catalog.FocusedModelRepository;
23405 amit.gupta 64
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
65
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
25721 tejbeer 66
import com.spice.profitmandi.dao.repository.cs.CsService;
23779 amit.gupta 67
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
25736 tejbeer 68
import com.spice.profitmandi.dao.repository.dtr.Mongo;
23405 amit.gupta 69
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
25732 tejbeer 70
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
25721 tejbeer 71
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
72
import com.spice.profitmandi.dao.repository.fofo.MonthlyPlannedRepository;
73
import com.spice.profitmandi.dao.repository.fofo.PlannedDetailRepository;
23796 amit.gupta 74
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
75
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
76
import com.spice.profitmandi.dao.repository.transaction.UserWalletRepository;
77
import com.spice.profitmandi.dao.repository.user.UserRepository;
23798 amit.gupta 78
import com.spice.profitmandi.service.authentication.RoleManager;
25736 tejbeer 79
import com.spice.profitmandi.service.inventory.InventoryService;
23779 amit.gupta 80
import com.spice.profitmandi.service.inventory.StockAllocationService;
81
import com.spice.profitmandi.service.user.RetailerService;
25547 amit.gupta 82
import com.spice.profitmandi.service.wallet.WalletService;
23796 amit.gupta 83
import com.spice.profitmandi.thrift.clients.PaymentClient;
84
import com.spice.profitmandi.thrift.clients.TransactionClient;
85
import com.spice.profitmandi.thrift.clients.UserClient;
23405 amit.gupta 86
import com.spice.profitmandi.web.model.LoginDetails;
87
import com.spice.profitmandi.web.util.CookiesProcessor;
88
import com.spice.profitmandi.web.util.MVCResponseSender;
89
 
23796 amit.gupta 90
import in.shop2020.logistics.PickUpType;
91
import in.shop2020.model.v1.order.LineItem;
92
import in.shop2020.model.v1.order.OrderSource;
93
import in.shop2020.model.v1.order.OrderStatus;
94
import in.shop2020.model.v1.order.OrderType;
95
import in.shop2020.model.v1.order.Transaction;
96
import in.shop2020.model.v1.order.TransactionService;
97
import in.shop2020.model.v1.order.TransactionStatus;
98
import in.shop2020.model.v1.user.ItemPriceQuantity;
99
import in.shop2020.model.v1.user.ShoppingCartException;
100
import in.shop2020.model.v1.user.UserContextService.Client;
101
import in.shop2020.payments.Attribute;
102
import in.shop2020.payments.PaymentException;
103
import in.shop2020.payments.PaymentStatus;
104
 
23405 amit.gupta 105
@Controller
106
@Transactional(rollbackFor = Throwable.class)
107
public class IndentController {
108
 
23568 govind 109
	private static final Logger LOGGER = LogManager.getLogger(IndentController.class);
23796 amit.gupta 110
	private static final int WALLET_GATEWAY_ID = 8;
24406 amit.gupta 111
	private static final Set<Integer> defaultTags = new HashSet<Integer>(Arrays.asList(4));
23405 amit.gupta 112
 
23796 amit.gupta 113
	private final List<OrderStatus> validOrderStatusList = Arrays.asList(OrderStatus.ACCEPTED,
114
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
115
			OrderStatus.DELIVERY_SUCCESS, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
116
			OrderStatus.REACHED_DESTINATION_CITY);
117
 
24231 amit.gupta 118
	private final List<OrderStatus> partnerPendingOrderList = Arrays.asList(OrderStatus.ACCEPTED,
119
			OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.BILLED, OrderStatus.SHIPPED_FROM_WH,
120
			OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.SHIPPED_TO_LOGST,
121
			OrderStatus.REACHED_DESTINATION_CITY);
25721 tejbeer 122
 
25547 amit.gupta 123
	@Autowired
124
	WalletService walletService;
24231 amit.gupta 125
 
23405 amit.gupta 126
	@Autowired
25721 tejbeer 127
	private JavaMailSender googleMailSender;
128
 
129
	@Autowired
23405 amit.gupta 130
	private CookiesProcessor cookiesProcessor;
24231 amit.gupta 131
 
23796 amit.gupta 132
	@Autowired
133
	private UserWalletRepository userWalletRepository;
23785 amit.gupta 134
 
23779 amit.gupta 135
	@Autowired
23796 amit.gupta 136
	private UserRepository userRepository;
137
 
138
	@Autowired
23779 amit.gupta 139
	FofoStoreRepository fofoStoreRepository;
23405 amit.gupta 140
 
141
	@Autowired
23796 amit.gupta 142
	private OrderRepository orderRepository;
143
 
144
	@Autowired
23405 amit.gupta 145
	private ItemRepository itemRepository;
146
 
147
	@Autowired
23779 amit.gupta 148
	private StockAllocationService stockAllocationService;
149
 
150
	@Autowired
151
	private RetailerService retailerService;
23405 amit.gupta 152
 
153
	@Autowired
154
	private TagListingRepository tagListingRepository;
155
 
156
	@Autowired
157
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
158
 
159
	@Autowired
23796 amit.gupta 160
	private PurchaseRepository purchaseRepository;
161
 
162
	@Autowired
23405 amit.gupta 163
	private MVCResponseSender mvcResponseSender;
164
 
23785 amit.gupta 165
	@Autowired
25721 tejbeer 166
	private FocusedModelRepository focusedModelRepository;
167
 
168
	@Autowired
169
	private MonthlyPlannedRepository monthlyPlannedRepository;
170
 
171
	@Autowired
172
	private FofoOrderRepository fofoOrderRepository;
25732 tejbeer 173
 
25721 tejbeer 174
	@Autowired
25732 tejbeer 175
	private FofoOrderItemRepository fofoOrderItemRepository;
176
 
177
	@Autowired
25721 tejbeer 178
	private PlannedDetailRepository plannedDetailRepository;
25732 tejbeer 179
 
25721 tejbeer 180
	@Autowired
23785 amit.gupta 181
	RoleManager roleManager;
23405 amit.gupta 182
 
25721 tejbeer 183
	@Autowired
25736 tejbeer 184
	private Mongo mongoClient;
185
 
186
	@Autowired
187
	private InventoryService inventoryService;
188
 
189
	@Autowired
25721 tejbeer 190
	CsService csService;
191
 
192
	/*
193
	 * @RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
194
	 * public String saveOpenIndent(HttpServletRequest request, Model model,
195
	 * 
196
	 * @RequestBody List<StockAllocationModel>
197
	 * stockAllocationModelList, @RequestParam int fofoId,
198
	 * 
199
	 * @RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws
200
	 * Exception { LoginDetails loginDetails =
201
	 * cookiesProcessor.getCookiesObject(request); boolean response = false; if
202
	 * (fofoId > 0) { FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
203
	 * stockAllocationModelList.forEach(x -> { x.setFofoId(fofoId);
204
	 * x.setCounterSize(fs.getCounterSize()); }); } else {
205
	 * stockAllocationModelList.forEach(x -> { x.setFofoId(fofoId);
206
	 * x.setCounterSize(counterSize); }); } if
207
	 * (roleManager.isAdmin(loginDetails.getRoleIds())) { response =
208
	 * stockAllocationService.addToAllocation(stockAllocationModelList);
209
	 * model.addAttribute("response",
210
	 * mvcResponseSender.createResponseString(response)); } return "response"; }
211
	 */
23779 amit.gupta 212
	@RequestMapping(value = "/open-indent/save", method = RequestMethod.POST)
25721 tejbeer 213
	public String saveOpenIndent(HttpServletRequest request, Model model, @RequestParam int catalogId,
214
			@RequestParam int itemQty) throws Exception {
23405 amit.gupta 215
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
26082 tejbeer 216
		LocalDate currentMonthDate = LocalDate.now();
217
		MonthlyPlanned monthlyPlanned = null;
25721 tejbeer 218
 
26082 tejbeer 219
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(25))
220
				&& LocalDate.now().isBefore(LocalDate.now().plusMonths(1).withDayOfMonth(8))) {
221
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
222
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(loginDetails.getFofoId(),
223
					currentMonthDate);
25721 tejbeer 224
 
26082 tejbeer 225
			saveMonthlyPlanned(monthlyPlanned, loginDetails.getFofoId(), currentMonthDate, catalogId, itemQty);
226
		} else if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(8))
227
				&& (LocalDate.now().isBefore(LocalDate.now().withDayOfMonth(26)))) {
228
			// freezed code;
229
		} else if (LocalDate.now().isBefore(LocalDate.now().withDayOfMonth(8))) {
230
			currentMonthDate = LocalDate.now().withDayOfMonth(1);
231
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(loginDetails.getFofoId(),
232
					currentMonthDate);
233
 
234
			saveMonthlyPlanned(monthlyPlanned, loginDetails.getFofoId(), currentMonthDate, catalogId, itemQty);
235
		}
236
 
237
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
238
 
239
		model.addAttribute("response", mvcResponseSender.createResponseString(false));
240
 
241
		return "response";
242
	}
243
 
244
	private void saveMonthlyPlanned(MonthlyPlanned monthlyPlanned, int fofoId, LocalDate currentMonthDate,
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)
282
	public String confirmOpenIndent(HttpServletRequest request, Model model) throws Exception {
283
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
284
		int fofoId = loginDetails.getFofoId();
285
		CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
26082 tejbeer 286
		LocalDate currentMonthDate = LocalDate.now();
287
		MonthlyPlanned monthlyPlanned = null;
288
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(25))
289
				&& LocalDate.now().isBefore(LocalDate.now().plusMonths(1).withDayOfMonth(8))) {
290
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
291
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
25721 tejbeer 292
 
26082 tejbeer 293
			confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
294
		} else if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(8))
295
				&& (LocalDate.now().isBefore(LocalDate.now().withDayOfMonth(26)))) {
296
			// freezed code;
297
		} else if (LocalDate.now().isBefore(LocalDate.now().withDayOfMonth(8))) {
298
			currentMonthDate = LocalDate.now().withDayOfMonth(1);
299
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
300
 
301
			confirmMonthlyPlanned(monthlyPlanned, customRetailer, fofoId);
302
		}
303
 
304
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
305
 
306
		return "response";
307
	}
308
 
309
	private void confirmMonthlyPlanned(MonthlyPlanned monthlyPlanned, CustomRetailer customRetailer, int fofoId)
310
			throws Exception {
25721 tejbeer 311
		List<PlannedDetail> plannedDetails = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId());
312
 
313
		List<PlannedModel> plannedModel = new ArrayList<>();
314
		for (PlannedDetail plannedDetail : plannedDetails) {
315
 
316
			List<Item> items = itemRepository.selectAllByCatalogItemId(plannedDetail.getCatalogId());
317
			String itemDesription = items.get(0).getItemDescriptionNoColor();
318
			PlannedModel pm = new PlannedModel();
319
			pm.setItemDescription(itemDesription);
320
			pm.setStoreName(customRetailer.getBusinessName());
321
			pm.setQty(plannedDetail.getQuantity());
26082 tejbeer 322
			pm.setFofoId(fofoId);
25721 tejbeer 323
			plannedModel.add(pm);
324
			LOGGER.info("plannedModel" + plannedModel);
325
 
23785 amit.gupta 326
		}
25732 tejbeer 327
		List<String> emails = csService.getAuthUserByPartnerId(fofoId);
328
		emails.add(customRetailer.getEmail());
25727 tejbeer 329
 
25721 tejbeer 330
		LOGGER.info("emails" + emails);
26082 tejbeer 331
 
25721 tejbeer 332
		ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
333
				Arrays.asList("Partner Id", "Partner Name", "Model Name", "Qty"),
334
				plannedModel.stream()
335
						.map(x -> Arrays.asList(x.getFofoId(), x.getStoreName(), x.getItemDescription(), x.getQty()))
336
						.collect(Collectors.toList()));
337
		LOGGER.info("baos" + baos);
338
		Utils.sendMailWithAttachments(googleMailSender, emails.toArray(new String[emails.size()]), null,
339
				"Planned Indent", "PFA",
340
				new Attachment[] { new Attachment("PlannedIndent.csv", new ByteArrayResource(baos.toByteArray())), });
341
 
23405 amit.gupta 342
	}
343
 
24231 amit.gupta 344
	@RequestMapping(value = "/indent/download", method = RequestMethod.GET)
345
	public ResponseEntity<ByteArrayResource> downloadIndent(HttpServletRequest request, Model model,
346
			@RequestParam(required = false, defaultValue = "0") int fofoId,
347
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 348
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
349
		Set<Integer> roleIds = loginDetails.getRoleIds();
24231 amit.gupta 350
		LOGGER.info("Counter size is {}", counterSize);
351
		LOGGER.info("Fofo Id is {}", fofoId);
25721 tejbeer 352
		if (roleManager.isAdmin(roleIds) || loginDetails.getFofoId() == fofoId) {
24231 amit.gupta 353
			List<Integer> fofoIds = fofoStoreRepository.selectAll().stream().map(x -> x.getId())
354
					.collect(Collectors.toList());
355
			Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);
23415 amit.gupta 356
 
24232 amit.gupta 357
			List<StockAllocationModel> stockAllocationList = stockAllocationService.getStockAllocation(counterSize,
358
					true);
359
			Map<Integer, Integer> modelStockAllocationMap = stockAllocationList.stream()
360
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
23405 amit.gupta 361
 
24232 amit.gupta 362
			Map<String, Integer> catalogUserQtyMap = new HashMap<>();
25702 amit.gupta 363
			currentInventorySnapshotRepository.selectByFofoId(fofoId).stream().forEach(x -> {
24232 amit.gupta 364
				int retailerId = x.getFofoId();
365
				int catalogId;
366
				try {
367
					catalogId = itemRepository.selectById(x.getItemId()).getCatalogItemId();
368
					String key = catalogId + "-" + retailerId;
369
					if (!catalogUserQtyMap.containsKey(key)) {
370
						catalogUserQtyMap.put(key, 0);
371
					}
372
					catalogUserQtyMap.put(key, catalogUserQtyMap.get(key) + x.getAvailability());
373
				} catch (ProfitMandiBusinessException e) {
374
					// TODO Auto-generated catch block
375
					throw new RuntimeException(e);
24231 amit.gupta 376
				}
377
			});
23779 amit.gupta 378
 
24231 amit.gupta 379
			List<Order> inTransitOrders = orderRepository.selectOrders(fofoIds, partnerPendingOrderList);
24232 amit.gupta 380
			Map<String, Integer> catalogUserInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> {
381
				try {
382
					return itemRepository.selectById(x.getLineItem().getItemId()).getCatalogItemId() + "-"
383
							+ x.getRetailerId();
384
				} catch (ProfitMandiBusinessException e) {
385
					// TODO Auto-generated catch block
386
					return "";
387
				}
388
			}, Collectors.summingInt(x -> x.getLineItem().getQuantity())));
23779 amit.gupta 389
 
24232 amit.gupta 390
			Map<String, CatalogListingModel> catalogListingMap = new HashMap<>();
391
 
392
			List<TagListing> tagListings = tagListingRepository.selectAll(true);
393
			Iterator<TagListing> iterator = tagListings.iterator();
24231 amit.gupta 394
			while (iterator.hasNext()) {
395
				TagListing tagListing = iterator.next();
396
				Item item = itemRepository.selectById(tagListing.getItemId());
24232 amit.gupta 397
				int catalogId = item.getCatalogItemId();
24231 amit.gupta 398
				if (item.getCategoryId() != 10006) {
399
					continue;
400
				}
23779 amit.gupta 401
 
24232 amit.gupta 402
				int catalogStockAllocationQuantity = modelStockAllocationMap.containsKey(catalogId)
403
						? modelStockAllocationMap.get(catalogId)
404
						: 0;
405
				for (int retailerId : fofoIds) {
406
					String key = catalogId + "-" + retailerId;
407
					if (catalogListingMap.containsKey(key)) {
408
						continue;
24231 amit.gupta 409
					}
24232 amit.gupta 410
					int catalogInTransit = catalogUserInTransit.containsKey(key) ? catalogUserInTransit.get(key) : 0;
411
					int catalogInStock = catalogUserQtyMap.containsKey(key) ? catalogUserQtyMap.get(key) : 0;
412
					if (catalogInTransit + catalogInStock == 0 && catalogStockAllocationQuantity == 0) {
413
						continue;
414
					}
415
					CatalogListingModel catalogListingModel = new CatalogListingModel();
416
					catalogListingModel.setFofoId(retailerId);
417
					catalogListingModel.setModelName(item.getModelName());
418
					catalogListingModel.setModelNumber(item.getModelNumber());
419
					catalogListingModel.setCatalogId(catalogId);
420
					catalogListingModel.setDp(tagListing.getSellingPrice());
421
					catalogListingModel.setMop(tagListing.getMop());
422
					catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
423
					catalogListingModel.setAllocatedQuantity(catalogStockAllocationQuantity);
424
					catalogListingModel.setInTransitQuantity(catalogInTransit);
425
					catalogListingModel
426
							.setToBeOrdered(catalogStockAllocationQuantity - catalogInTransit - catalogInStock);
24233 amit.gupta 427
					catalogListingModel.setStockInHand(catalogInStock);
24232 amit.gupta 428
					catalogListingModel.setBrand(item.getBrand());
429
					catalogListingModel.setModelName(item.getModelName());
430
					catalogListingModel.setModelNumber(item.getModelNumber());
431
					catalogListingModel.setCategoryId(item.getCategoryId());
432
					catalogListingMap.put(key, catalogListingModel);
23405 amit.gupta 433
				}
434
			}
25853 amit.gupta 435
			List<List<?>> listOfRows = new ArrayList<>();
24231 amit.gupta 436
			for (CatalogListingModel clm : catalogListingMap.values()) {
437
				CustomRetailer cr = customRetailersMap.get(clm.getFofoId());
24349 amit.gupta 438
				listOfRows.add(Arrays.asList(cr.getPartnerId(), cr.getBusinessName(), clm.getCatalogId(),
439
						clm.getBrand(), clm.getModelName(), clm.getModelNumber(), clm.getDp(), clm.getMop(),
440
						clm.getAllocatedQuantity(), clm.getInTransitQuantity(), clm.getStockInHand(),
441
						clm.getToBeOrdered()));
24231 amit.gupta 442
			}
24349 amit.gupta 443
			ByteArrayOutputStream baos = FileUtil
444
					.getCSVByteStream(
445
							Arrays.asList("StoreId", "StoreName", "Catalog Id", "Brand", "Model Name", "Model Number",
446
									"DP", "MOP", "Allocated Quantity", "In Transit", "Stock In hand", "Shortage"),
447
							listOfRows);
24231 amit.gupta 448
			HttpHeaders headers = new HttpHeaders();
449
			headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
450
			headers.set("Content-disposition", "inline; filename=retailer-allocation.csv");
24232 amit.gupta 451
			return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(baos.toByteArray()), headers,
452
					HttpStatus.OK);
23405 amit.gupta 453
		}
24231 amit.gupta 454
		return null;
24232 amit.gupta 455
 
23405 amit.gupta 456
	}
457
 
24349 amit.gupta 458
	@RequestMapping(value = "/itemsByCatalogId")
459
	public String getItemsByCatalogId(HttpServletRequest request, Model model,
24410 amit.gupta 460
			@RequestParam(required = false) int catalogId, @RequestParam(required = false) int itemId)
25378 tejbeer 461
			throws ProfitMandiBusinessException {
24410 amit.gupta 462
		if (catalogId == 0) {
463
			catalogId = itemRepository.selectById(itemId).getCatalogItemId();
464
		}
24349 amit.gupta 465
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogId);
24414 amit.gupta 466
		LOGGER.info("Items {}", items);
25378 tejbeer 467
		Map<Integer, String> itemsColorMap = items.stream().filter(x -> x.getColorNatural().startsWith("f_"))
468
				.collect(Collectors.toMap(Item::getId, Item::getColor));
24413 amit.gupta 469
		Map<Integer, TagListing> tagsMap = tagListingRepository
470
				.selectByItemIdsAndTagIds(items.stream().map(x -> x.getId()).collect(Collectors.toSet()), defaultTags)
25378 tejbeer 471
				.stream().collect(Collectors.toMap(TagListing::getItemId, x -> x));
24414 amit.gupta 472
		LOGGER.info("Items color map {}", itemsColorMap);
24349 amit.gupta 473
		JSONArray response = new JSONArray();
24413 amit.gupta 474
		itemsColorMap.keySet().stream().forEach(x -> {
25378 tejbeer 475
			response.put(new JSONObject().put("color", itemsColorMap.get(x)).put("id", x).put("active",
476
					tagsMap.get(x) == null ? false : tagsMap.get(x).isActive()));
24349 amit.gupta 477
		});
478
		model.addAttribute("response", response.toString());
479
		return "response";
24410 amit.gupta 480
 
24349 amit.gupta 481
	}
482
 
23405 amit.gupta 483
	@RequestMapping(value = "/indent/loadIndent")
23785 amit.gupta 484
	public String loadOpenIndent(HttpServletRequest request, Model model,
485
			@RequestParam(required = false, defaultValue = "0") int fofoId,
25736 tejbeer 486
			@RequestParam(defaultValue = "TEN_LAC") CounterSize counterSize) throws Exception {
25702 amit.gupta 487
 
488
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
489
		Set<Integer> roleIds = loginDetails.getRoleIds();
23785 amit.gupta 490
		LOGGER.info("Counter size is {}", counterSize);
491
		LOGGER.info("Fofo Id is {}", fofoId);
25736 tejbeer 492
		boolean isAdmin = roleManager.isAdmin(roleIds);
25796 tejbeer 493
 
25797 tejbeer 494
		List<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
495
				.collect(Collectors.toList());
496
 
25796 tejbeer 497
		Map<String, Object> equalsMap = new HashMap<>();
498
		equalsMap.put("categoryId", 10006);
25797 tejbeer 499
		equalsMap.put("brand", brands);
25796 tejbeer 500
		Map<String, List<?>> notEqualsMap = new HashMap<>();
501
 
502
		Map<String, List<?>> notEqualsJoinMap = new HashMap<>();
503
		Map<Integer, Integer> currentStockMap;
504
 
25721 tejbeer 505
		if (!isAdmin && fofoId == 0) {
23786 amit.gupta 506
			fofoId = cookiesProcessor.getCookiesObject(request).getFofoId();
25796 tejbeer 507
			Map<String, Object> equalsStockJoinMap = new HashMap<>();
508
			equalsStockJoinMap.put("fofoId", fofoId);
509
			currentStockMap = itemRepository
25800 tejbeer 510
					.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
511
							equalsStockJoinMap, notEqualsJoinMap, "availability")
25796 tejbeer 512
					.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25797 tejbeer 513
			LOGGER.info("currentStock");
23786 amit.gupta 514
		} else {
515
			if (fofoId == 0) {
25796 tejbeer 516
 
517
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
518
				equalsStockJoinMap.put("fofoId", fofoId);
519
 
520
				currentStockMap = itemRepository
25800 tejbeer 521
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 522
								equalsStockJoinMap, notEqualsJoinMap, "availability")
523
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
524
 
23779 amit.gupta 525
			} else {
25796 tejbeer 526
 
527
				Map<String, Object> equalsStockJoinMap = new HashMap<>();
528
				equalsStockJoinMap.put("fofoId", fofoId);
529
 
530
				currentStockMap = itemRepository
25800 tejbeer 531
						.selectItems(CurrentInventorySnapshot.class, "id", "itemId", equalsMap, notEqualsMap,
25796 tejbeer 532
								equalsStockJoinMap, notEqualsJoinMap, "availability")
533
						.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
534
 
23405 amit.gupta 535
			}
23786 amit.gupta 536
		}
25796 tejbeer 537
 
538
		LOGGER.info("currentStock" + currentStockMap);
25797 tejbeer 539
 
23796 amit.gupta 540
		Map<Integer, Integer> itemsInTransit = null;
23855 amit.gupta 541
		List<TagListing> tagListings = tagListingRepository.selectAll(true);
25702 amit.gupta 542
		if (!isAdmin) {
23786 amit.gupta 543
			tagListings = new ArrayList<>(tagListings);
25797 tejbeer 544
			List<Order> inTransitOrders = orderRepository.selectPendingGrnOrder(fofoId, validOrderStatusList);
23796 amit.gupta 545
			inTransitOrders = this.filterValidOrders(inTransitOrders);
546
			itemsInTransit = inTransitOrders.stream().collect(Collectors.groupingBy(x -> x.getLineItem().getItemId(),
547
					Collectors.summingInt(x -> x.getLineItem().getQuantity())));
548
		} else {
549
			itemsInTransit = new HashMap<>();
23786 amit.gupta 550
		}
25797 tejbeer 551
 
23796 amit.gupta 552
		int totalPcs = 0;
25797 tejbeer 553
 
23796 amit.gupta 554
		float totalAmount = 0;
24231 amit.gupta 555
		Map<Integer, CatalogListingModel> catalogListingMap = new HashMap<>();
25796 tejbeer 556
 
25721 tejbeer 557
		Map<Integer, FocusedModel> focusedModelMap = focusedModelRepository.selectAll().stream()
558
				.collect(Collectors.toMap(FocusedModel::getCatalogId, Function.identity()));
25728 tejbeer 559
 
26082 tejbeer 560
		LocalDate currentMonthDate = LocalDate.now();
561
		MonthlyPlanned monthlyPlanned = null;
562
		LOGGER.info("localDate" + LocalDate.now());
563
		if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(25))
564
				&& LocalDate.now().isBefore(LocalDate.now().plusMonths(1).withDayOfMonth(8))) {
565
			currentMonthDate = LocalDate.now().plusMonths(1).withDayOfMonth(1);
566
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
567
			LOGGER.info("monthlyPlanned2" + monthlyPlanned);
568
 
569
			model.addAttribute("planningMonth", LocalDate.now().plusMonths(1).getMonth());
570
		} else if (LocalDate.now().isAfter(LocalDate.now().withDayOfMonth(8))
571
				&& (LocalDate.now().isBefore(LocalDate.now().withDayOfMonth(26)))) {
572
			currentMonthDate = LocalDate.now().withDayOfMonth(1);
573
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
574
			LOGGER.info("monthlyPlanned1" + monthlyPlanned);
575
		} else if (LocalDate.now().isBefore(LocalDate.now().withDayOfMonth(8))) {
576
			currentMonthDate = LocalDate.now().withDayOfMonth(1);
577
			monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(fofoId, currentMonthDate);
578
			LOGGER.info("monthlyPlanned3" + monthlyPlanned);
579
			model.addAttribute("planningMonth", LocalDate.now().getMonth());
580
		}
581
 
25721 tejbeer 582
		Map<Integer, Integer> plannedDetailMap = null;
583
		if (monthlyPlanned != null) {
584
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
585
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
586
 
587
		}
25797 tejbeer 588
		LOGGER.info("plannedDetailMap" + plannedDetailMap);
25796 tejbeer 589
		List<Integer> fofoOrderIds = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(),
590
				LocalDateTime.now().minusDays(15), LocalDateTime.now()).stream().map(x -> x.getId())
591
				.collect(Collectors.toList());
592
		LOGGER.info("fofoOrderIds" + fofoOrderIds);
593
		Map<String, Object> equalsJoinMap = new HashMap<>();
594
		equalsJoinMap.put("orderId", fofoOrderIds);
24231 amit.gupta 595
 
25796 tejbeer 596
		Map<Integer, Integer> last15daysMap = itemRepository
25800 tejbeer 597
				.selectItems(FofoOrderItem.class, "id", "itemId", equalsMap, notEqualsMap, equalsJoinMap,
598
						notEqualsJoinMap, "quantity")
25796 tejbeer 599
				.stream().collect(Collectors.toMap(x -> x.getCatalogId(), x -> (int) x.getAggregateValue()));
25797 tejbeer 600
		LOGGER.info("last15daysMap");
25796 tejbeer 601
		LOGGER.info("last15daysMap" + last15daysMap);
25721 tejbeer 602
 
25796 tejbeer 603
		Map<Integer, TagListing> taglistingMap = tagListings.stream()
604
				.collect(Collectors.toMap(x -> x.getItemId(), x -> x));
605
		List<Item> items = itemRepository.selectByIds(taglistingMap.keySet());
606
		Map<Integer, List<Item>> catalogIdItemMap = items.stream().collect(
607
				Collectors.groupingBy(x -> x.getCatalogItemId(), Collectors.mapping(y -> y, Collectors.toList())));
25797 tejbeer 608
		LOGGER.info("catalogIdItemMap");
24231 amit.gupta 609
 
25796 tejbeer 610
		Map<String, Object> equalsItemJoinMap = new HashMap<>();
25797 tejbeer 611
		equalsItemJoinMap.put("active", 1);
25800 tejbeer 612
		List<CatalogIdAggregateValue> tagListingCatalogIds = itemRepository.selectItems(TagListing.class, "id",
613
				"itemId", equalsMap, notEqualsMap, equalsItemJoinMap, notEqualsJoinMap, "tagId");
25797 tejbeer 614
		LOGGER.info("tagListingCatalogIds");
25796 tejbeer 615
		for (CatalogIdAggregateValue catalogIdAggregateValue : tagListingCatalogIds) {
616
			int catalogId = catalogIdAggregateValue.getCatalogId();
617
			Item item = catalogIdItemMap.get(catalogId).get(0);
618
			TagListing tagListing = taglistingMap.get(item.getId());
24231 amit.gupta 619
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
620
			if (!catalogListingMap.containsKey(catalogId)) {
621
				catalogListingModel = new CatalogListingModel();
622
				catalogListingModel.setCatalogId(catalogId);
623
				catalogListingModel.setDp(tagListing.getSellingPrice());
624
				catalogListingModel.setMop(tagListing.getMop());
625
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
25721 tejbeer 626
				if (plannedDetailMap != null) {
627
 
628
					Integer quantity = plannedDetailMap.get(catalogId);
629
					if (quantity != null) {
630
						catalogListingModel.setAllocatedQuantity(quantity);
631
					}
632
				}
633
 
25796 tejbeer 634
				if (last15daysMap != null) {
635
					Integer last15DaysSale = last15daysMap.get(catalogId);
636
 
25721 tejbeer 637
					if (last15DaysSale != null) {
638
						catalogListingModel.setLast15DaysSale(last15DaysSale);
639
					} else {
640
						catalogListingModel.setLast15DaysSale(0);
641
					}
642
				} else {
643
					catalogListingModel.setLast15DaysSale(0);
644
				}
645
 
24231 amit.gupta 646
				catalogListingModel.setBrand(item.getBrand());
647
				if (item.getCategoryId() == 10006) {
648
					catalogListingModel.setCategoryId(item.getCategoryId());
649
				}
25721 tejbeer 650
 
651
				FocusedModel fm = focusedModelMap.get(catalogId);
652
				if (fm != null) {
653
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
654
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
655
 
656
				} else {
657
					catalogListingModel.setRecommendedQty(0);
658
					catalogListingModel.setMinimumQty(0);
659
				}
660
 
24231 amit.gupta 661
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 662
 
24231 amit.gupta 663
			}
25736 tejbeer 664
			int itemAvailability = 0;
25796 tejbeer 665
			if (currentStockMap != null) {
666
				Integer qty = currentStockMap.get(catalogId);
25736 tejbeer 667
				itemAvailability = qty == null ? 0 : qty;
668
				catalogListingModel.setStockInHand(itemAvailability);
669
			} else {
670
				catalogListingModel.setStockInHand(0);
671
			}
24231 amit.gupta 672
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
673
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
674
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
675
 
23786 amit.gupta 676
		}
25721 tejbeer 677
 
25702 amit.gupta 678
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers();
23786 amit.gupta 679
		if (fofoId > 0) {
680
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
681
			model.addAttribute("retailerName",
682
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
683
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
684
			model.addAttribute("retailerId", customRetailer.getPartnerId());
685
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 686
		} else {
23786 amit.gupta 687
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 688
		}
23786 amit.gupta 689
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 690
 
691
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
692
 
25721 tejbeer 693
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 694
				Comparator.reverseOrder());
25721 tejbeer 695
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
25796 tejbeer 696
		model.addAttribute("catalogTagListings",
697
				catalogModelList.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 698
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
25799 tejbeer 699
		model.addAttribute("brandStockPrices", this.getBrandStockPrices(loginDetails.getFofoId()));
23786 amit.gupta 700
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 701
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 702
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 703
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 704
		return "open-indent";
25796 tejbeer 705
 
23405 amit.gupta 706
	}
23796 amit.gupta 707
 
708
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
25812 amit.gupta 709
		int orderRemovedCount = 0;
23796 amit.gupta 710
		Iterator<Order> orderIterator = lastOrdersList.iterator();
711
		while (orderIterator.hasNext()) {
712
			Order o = orderIterator.next();
713
			if (o.getInvoiceNumber() != null) {
714
				try {
715
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
716
					orderIterator.remove();
25812 amit.gupta 717
					orderRemovedCount++;
23796 amit.gupta 718
				} catch (Exception e) {
719
 
720
				}
721
			}
722
		}
25812 amit.gupta 723
		LOGGER.info("Order removed count is {}", orderRemovedCount);
23796 amit.gupta 724
		return lastOrdersList;
725
	}
726
 
24406 amit.gupta 727
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
24410 amit.gupta 728
	public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
729
			throws Exception {
24406 amit.gupta 730
		JSONArray jsonArray = new JSONArray(jsonArrayString);
24410 amit.gupta 731
		for (int i = 0; i < jsonArray.length(); i++) {
24406 amit.gupta 732
			JSONObject obj = jsonArray.getJSONObject(i);
25378 tejbeer 733
 
24406 amit.gupta 734
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
25378 tejbeer 735
			if (tl == null) {
736
				continue;
737
			} else {
738
				tl.setActive(obj.getBoolean("active"));
739
				tagListingRepository.persist(tl);
740
			}
24406 amit.gupta 741
		}
24410 amit.gupta 742
		model.addAttribute("response", true);
23855 amit.gupta 743
		return "response";
744
	}
24231 amit.gupta 745
 
746
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
23796 amit.gupta 747
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
748
		boolean success = false;
749
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
750
		int fofoId = loginDetails.getFofoId();
751
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
752
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
753
		Client userClient = new UserClient().getClient();
24231 amit.gupta 754
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
23796 amit.gupta 755
 
24231 amit.gupta 756
		if (totalAmount > 0) {
23796 amit.gupta 757
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
758
			User user = userRepository.selectById(loginDetails.getFofoId());
759
			userClient = new UserClient().getClient();
760
			LOGGER.info("Setting wallet amount in cart");
24231 amit.gupta 761
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
762
					7890, OrderSource.WEBSITE.getValue(), true);
23796 amit.gupta 763
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
764
			createPayment(user, totalAmount, transactionId);
24231 amit.gupta 765
			TransactionService.Client transactionClient = new TransactionClient().getClient();
23796 amit.gupta 766
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
24231 amit.gupta 767
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 768
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
24231 amit.gupta 769
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 770
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
771
			transactionClient = new TransactionClient().getClient();
772
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
773
			try {
774
				transactionClient.enqueueTransactionInfoEmail(transactionId);
775
			} catch (Exception e1) {
776
				e1.printStackTrace();
777
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
778
			}
779
			resetCart(transactionClient.getTransaction(transactionId));
780
		}
781
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
782
		return "response";
783
	}
24231 amit.gupta 784
 
785
	private void createPayment(User user, double totalAmount, long transactionId)
786
			throws NumberFormatException, PaymentException, TException {
23796 amit.gupta 787
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
788
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
789
		paymentAttributes.add(new Attribute("payMethod", "7890"));
24231 amit.gupta 790
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
791
				false);
792
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
793
				PaymentStatus.SUCCESS, null, paymentAttributes);
23796 amit.gupta 794
	}
24231 amit.gupta 795
 
23796 amit.gupta 796
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
797
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
24231 amit.gupta 798
		/*
799
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
800
		 * currentInventorySnapshots = currentInventorySnapshotRepository
801
		 * .selectItemsStock(fofoId); itemCisMap =
802
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
803
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
804
		 * List<StockAllocationModel> stockAllocationList =
805
		 * stockAllocationService.getStockAllocation(fofoId, true);
806
		 * 
807
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
808
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
809
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
810
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
811
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
812
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
813
		 * validOrderStatusList); inTransitOrders =
814
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
815
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
816
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
817
		 * x.getLineItem().getQuantity())));
818
		 * 
819
		 * Iterator<TagListing> iterator = tagListings.iterator();
820
		 * 
821
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
822
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
823
		 * tagListing.getAllocatedQuantity()); if
824
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
825
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
826
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
827
		 * itemCisMap.get(tagListing.getItemId());
828
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
829
		 * itemIdAvailability.getAvailability()); StockAllocationModel
830
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
831
		 * 
832
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
833
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
834
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
835
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
836
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
837
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
838
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
839
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
840
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
841
		 */
23796 amit.gupta 842
		return itemQuantities;
843
 
844
	}
24231 amit.gupta 845
 
23796 amit.gupta 846
	private long resetCart(Transaction transaction) {
847
		long sum = 0;
848
		Map<Long, Double> items = new HashMap<Long, Double>();
849
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
850
			sum += order.getGvAmount();
851
			for (LineItem lineitem : order.getLineitems()) {
852
				Long itemId = lineitem.getItem_id();
853
				Double quantity = items.get(itemId);
854
				if (quantity == null) {
855
					quantity = lineitem.getQuantity();
856
				} else {
857
					quantity = quantity + lineitem.getQuantity();
858
				}
859
				items.put(itemId, quantity);
860
			}
861
		}
862
 
863
		LOGGER.debug("Items to reset in cart are: " + items);
864
 
865
		try {
866
			Client userClient = new UserClient().getClient();
867
			userClient.resetCart(transaction.getShoppingCartid(), items);
868
		} catch (TException e) {
869
			LOGGER.error("Error while updating information in payment database.", e);
870
		} catch (ShoppingCartException e) {
871
			LOGGER.error("Error while reseting the cart in cart database.", e);
872
		} catch (Exception e) {
873
			LOGGER.error("Unexpected exception", e);
874
		}
875
		return sum;
876
	}
877
 
25721 tejbeer 878
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
879
	public String getFocusedModel(HttpServletRequest request,
880
			@RequestParam(name = "offset", defaultValue = "0") int offset,
881
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
882
			throws ProfitMandiBusinessException {
25736 tejbeer 883
 
884
		long size = 0;
25721 tejbeer 885
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
25736 tejbeer 886
		size = focusedModelRepository.selectAllCount();
25721 tejbeer 887
 
25736 tejbeer 888
		if (!focusedModels.isEmpty()) {
889
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
25721 tejbeer 890
 
25736 tejbeer 891
			model.addAttribute("focusedModels", focusedModels);
892
			model.addAttribute("itemMap", itemMap);
25721 tejbeer 893
 
25736 tejbeer 894
			model.addAttribute("start", offset + 1);
895
			model.addAttribute("size", size);
896
			model.addAttribute("url", "/getPaginatedFocusedModel");
897
 
898
			if (focusedModels.size() < limit) {
899
				model.addAttribute("end", offset + focusedModels.size());
900
			} else {
901
				model.addAttribute("end", offset + limit);
902
			}
903
		} else {
904
 
905
			model.addAttribute("walletRequest", focusedModels);
906
			model.addAttribute("size", size);
907
 
908
		}
909
 
25721 tejbeer 910
		return "focused_model";
911
	}
912
 
25736 tejbeer 913
	@RequestMapping(value = "/getPaginatedFocusedModel", method = RequestMethod.GET)
914
	public String getPaginatedFocusedModel(HttpServletRequest request,
915
			@RequestParam(name = "offset", defaultValue = "0") int offset,
916
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
917
			throws ProfitMandiBusinessException {
918
		LOGGER.info("requested offset=[{}], limit = [{}]", offset, limit);
919
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
920
 
921
		if (!focusedModels.isEmpty()) {
922
			Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
923
 
924
			model.addAttribute("focusedModels", focusedModels);
925
			model.addAttribute("itemMap", itemMap);
926
 
927
			model.addAttribute("url", "/getPaginatedFocusedModel");
928
		} else {
929
			model.addAttribute("focusedModels", focusedModels);
930
 
931
		}
932
		return "focused-model-paginated";
933
	}
934
 
25721 tejbeer 935
	private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
936
		Map<Integer, Item> itemMap = new HashMap<>();
937
		for (FocusedModel focusedModel : focusedModels) {
938
			List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
939
			itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
940
		}
941
 
942
		return itemMap;
943
	}
944
 
945
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
946
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int recommended,
947
			@RequestParam int minimumQty, Model model) throws ProfitMandiBusinessException {
948
 
949
		FocusedModel fm = new FocusedModel();
950
		fm.setCatalogId(catalogId);
951
		fm.setMinimumQty(minimumQty);
952
		fm.setRecommendedQty(recommended);
953
		fm.setCreatedTimestamp(LocalDateTime.now());
954
		focusedModelRepository.persist(fm);
955
		return "focused_model";
956
	}
957
 
958
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
959
	public String removeFocusedModelItem(HttpServletRequest request,
960
			@RequestParam(name = "catalogId", defaultValue = "0") int catalogId, Model model) throws Exception {
961
 
962
		focusedModelRepository.deleteById(catalogId);
963
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
964
		return "response";
965
	}
25736 tejbeer 966
 
25798 tejbeer 967
	private List<BrandStockPrice> getBrandStockPrices(int fofoId) throws Exception {
968
		Map<String, BrandStockPrice> brandStockPricesMap = inventoryService.getBrandWiseStockValue(fofoId);
25736 tejbeer 969
 
25798 tejbeer 970
		List<DBObject> mobileBrands = mongoClient.getMongoBrands(fofoId, "", 3);
971
		List<BrandStockPrice> brandStockPrices = new ArrayList<>();
972
 
973
		mobileBrands.stream().forEach(x -> {
974
			String brand = (String) x.get("name");
975
			if (brandStockPricesMap.containsKey(brand)) {
976
				BrandStockPrice brandStockPrice = brandStockPricesMap.get(brand);
977
				brandStockPrice.setBrandUrl((String) x.get("url"));
978
				brandStockPrice.setRank(((Double) x.get("rank")).intValue());
979
				brandStockPrices.add(brandStockPrice);
980
			}
981
		});
982
 
983
		return brandStockPrices.stream().filter(x -> x.getTotalQty() > 0).sorted((x, y) -> x.getRank() - y.getRank())
984
				.collect(Collectors.toList());
985
	}
986
 
25721 tejbeer 987
}