Subversion Repositories SmartDukaan

Rev

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