Subversion Repositories SmartDukaan

Rev

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