Subversion Repositories SmartDukaan

Rev

Rev 25721 | Rev 25727 | 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
		}
25722 tejbeer 271
	//	List<String> emails = csService.getAuthUserByPartnerId(fofoId);
272
		//emails.add(customRetailer.getEmail());
273
 
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()));
490
 
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()));
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
}