Subversion Repositories SmartDukaan

Rev

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