Subversion Repositories SmartDukaan

Rev

Rev 25727 | Rev 25729 | 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));
25728 tejbeer 492
		List<FofoOrder> fofoOrderMaps = fofoOrderRepository.selectByFofoIdBetweenCreatedTimeStamp(
493
				loginDetails.getFofoId(), LocalDateTime.now().minusDays(15), LocalDateTime.now());
494
 
495
		LOGGER.info("fofoOrderMaps" + fofoOrderMaps);
25721 tejbeer 496
		Map<Integer, Integer> fofoOrderMap = fofoOrderRepository
497
				.selectByFofoIdBetweenCreatedTimeStamp(loginDetails.getFofoId(), LocalDateTime.now().minusDays(15),
498
						LocalDateTime.now())
499
				.stream()
500
				.collect(Collectors.toMap(x -> x.getOrderItem().getItemId(), x -> x.getOrderItem().getQuantity()));
25728 tejbeer 501
 
502
		LOGGER.info("fofoOrderMap" + fofoOrderMap);
25721 tejbeer 503
		Map<Integer, Integer> last15DaysMap = null;
504
		if (!fofoOrderMap.isEmpty()) {
505
			last15DaysMap = itemRepository.selectByIds(fofoOrderMap.keySet()).stream().collect(Collectors
506
					.groupingBy(x -> x.getCatalogItemId(), Collectors.summingInt(x -> fofoOrderMap.get(x.getId()))));
507
		}
508
 
509
		MonthlyPlanned monthlyPlanned = monthlyPlannedRepository.selectByFofoIdYearMonth(loginDetails.getFofoId(),
510
				LocalDate.now().withDayOfMonth(1));
511
		Map<Integer, Integer> plannedDetailMap = null;
512
		if (monthlyPlanned != null) {
513
			plannedDetailMap = plannedDetailRepository.selectByPlannedId(monthlyPlanned.getId()).stream()
514
					.collect(Collectors.toMap(x -> x.getCatalogId(), x -> x.getQuantity()));
515
 
516
		}
517
 
23786 amit.gupta 518
		while (iterator.hasNext()) {
519
			TagListing tagListing = iterator.next();
24231 amit.gupta 520
 
25702 amit.gupta 521
			Item item = items.get(tagListing.getItemId());
24231 amit.gupta 522
			// itemRepository.select
523
			// catalogTagListingMap
25702 amit.gupta 524
			if (isAdmin) {
24231 amit.gupta 525
				if (item.getBrand() == null || item.getCategoryId() != 10006) {
23785 amit.gupta 526
					iterator.remove();
527
					continue;
528
				}
23786 amit.gupta 529
			} else {
24231 amit.gupta 530
				if (!(itemCisMap.containsKey(tagListing.getItemId())
24232 amit.gupta 531
						|| itemStockAllocationMap.containsKey(tagListing.getItemId()))) {
23786 amit.gupta 532
					iterator.remove();
533
					continue;
23779 amit.gupta 534
				}
535
			}
25721 tejbeer 536
 
24231 amit.gupta 537
			int catalogId = item.getCatalogItemId();
538
 
539
			CatalogListingModel catalogListingModel = catalogListingMap.get(catalogId);
540
			if (!catalogListingMap.containsKey(catalogId)) {
541
				catalogListingModel = new CatalogListingModel();
542
				catalogListingModel.setCatalogId(catalogId);
543
				catalogListingModel.setDp(tagListing.getSellingPrice());
544
				catalogListingModel.setMop(tagListing.getMop());
545
				catalogListingModel.setItemDescription(item.getItemDescriptionNoColor());
546
				StockAllocationModel stockAllocationModel = itemStockAllocationMap.get(item.getCatalogItemId());
547
				int stockAllocationQuantity = stockAllocationModel == null ? 0 : stockAllocationModel.getQuantity();
25721 tejbeer 548
				if (plannedDetailMap != null) {
549
 
550
					Integer quantity = plannedDetailMap.get(catalogId);
551
					if (quantity != null) {
552
						catalogListingModel.setAllocatedQuantity(quantity);
553
					} else {
554
 
555
						catalogListingModel.setAllocatedQuantity(stockAllocationQuantity);
556
					}
557
				} else {
558
					catalogListingModel.setAllocatedQuantity(stockAllocationQuantity);
559
				}
560
				if (last15DaysMap != null) {
561
					Integer last15DaysSale = last15DaysMap.get(catalogId);
562
 
563
					if (last15DaysSale != null) {
564
						catalogListingModel.setLast15DaysSale(last15DaysSale);
565
					} else {
566
						catalogListingModel.setLast15DaysSale(0);
567
					}
568
				} else {
569
					catalogListingModel.setLast15DaysSale(0);
570
				}
571
 
24231 amit.gupta 572
				catalogListingModel.setToBeOrdered(stockAllocationQuantity);
573
				catalogListingModel.setBrand(item.getBrand());
574
				if (item.getCategoryId() == 10006) {
575
					catalogListingModel.setCategoryId(item.getCategoryId());
576
				}
25721 tejbeer 577
 
578
				FocusedModel fm = focusedModelMap.get(catalogId);
579
				if (fm != null) {
580
					catalogListingModel.setRecommendedQty(fm.getRecommendedQty());
581
					catalogListingModel.setMinimumQty(fm.getMinimumQty());
582
 
583
				} else {
584
					catalogListingModel.setRecommendedQty(0);
585
					catalogListingModel.setMinimumQty(0);
586
				}
587
 
24231 amit.gupta 588
				catalogListingMap.put(catalogId, catalogListingModel);
25721 tejbeer 589
 
24231 amit.gupta 590
			}
591
 
23796 amit.gupta 592
			ItemIdAvailability itemIdAvailability = itemCisMap.get(tagListing.getItemId());
24231 amit.gupta 593
			int itemAvailability = itemIdAvailability == null ? 0 : itemIdAvailability.getAvailability();
594
			catalogListingModel.setStockInHand(catalogListingModel.getStockInHand() + itemAvailability);
23796 amit.gupta 595
 
24231 amit.gupta 596
			Integer inTransitQuantity = itemsInTransit.get(item.getId());
597
			int inTransitQty = (inTransitQuantity == null ? 0 : inTransitQuantity);
598
			catalogListingModel.setInTransitQuantity(catalogListingModel.getInTransitQuantity() + inTransitQty);
599
 
600
			if (catalogListingModel.getAllocatedQuantity() > 0) {
601
				toBeOrdered = Math.max(catalogListingModel.getToBeOrdered() - inTransitQty - itemAvailability, 0);
602
				catalogListingModel.setToBeOrdered(toBeOrdered);
23796 amit.gupta 603
			}
23786 amit.gupta 604
		}
25721 tejbeer 605
 
25702 amit.gupta 606
		Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers();
23786 amit.gupta 607
		if (fofoId > 0) {
608
			CustomRetailer customRetailer = customRetailersMap.get(fofoId);
609
			model.addAttribute("retailerName",
610
					customRetailer.getBusinessName() + "-" + customRetailer.getAddress().getCity());
611
			FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
612
			model.addAttribute("retailerId", customRetailer.getPartnerId());
613
			model.addAttribute("counterSize", fs.getCounterSize().toString());
23779 amit.gupta 614
		} else {
23786 amit.gupta 615
			model.addAttribute("counterSize", counterSize.toString());
23405 amit.gupta 616
		}
23786 amit.gupta 617
		String customRetailers = JSONObject.valueToString(customRetailersMap.values());
25702 amit.gupta 618
 
619
		List<CatalogListingModel> catalogModelList = new ArrayList<>(catalogListingMap.values());
25721 tejbeer 620
		List<CatalogListingModel> catalogModel = catalogModelList.stream()
621
				.filter(x -> !(x.getBrand().equals("Live Demo"))).collect(Collectors.toList());
25702 amit.gupta 622
 
25721 tejbeer 623
		LOGGER.info("item" + catalogModelList);
624
		Comparator<CatalogListingModel> firstCmp = Comparator.comparing(CatalogListingModel::getMinimumQty,
24231 amit.gupta 625
				Comparator.reverseOrder());
25721 tejbeer 626
		LOGGER.info("monthlyPlanned" + monthlyPlanned);
627
		model.addAttribute("catalogTagListings", catalogModel.stream().sorted(firstCmp).collect(Collectors.toList()));
25702 amit.gupta 628
		model.addAttribute("isAdmin", roleManager.isAdmin(roleIds));
23786 amit.gupta 629
		model.addAttribute("customRetailers", customRetailers);
23796 amit.gupta 630
		model.addAttribute("totalAmount", totalAmount);
25721 tejbeer 631
		model.addAttribute("monthlyPlanned", monthlyPlanned);
23796 amit.gupta 632
		model.addAttribute("totalPcs", totalPcs);
23786 amit.gupta 633
		return "open-indent";
23405 amit.gupta 634
	}
23796 amit.gupta 635
 
636
	private List<Order> filterValidOrders(List<Order> lastOrdersList) {
637
		Iterator<Order> orderIterator = lastOrdersList.iterator();
638
		while (orderIterator.hasNext()) {
639
			Order o = orderIterator.next();
640
			if (o.getInvoiceNumber() != null) {
641
				try {
642
					purchaseRepository.selectByPurchaseReferenceAndFofoId(o.getInvoiceNumber(), o.getRetailerId());
643
					orderIterator.remove();
644
					continue;
645
				} catch (Exception e) {
646
 
647
				}
648
			}
649
		}
650
		return lastOrdersList;
651
	}
652
 
24406 amit.gupta 653
	@RequestMapping(value = "/indent/confirm-pause", method = RequestMethod.POST)
24410 amit.gupta 654
	public String raisePO(HttpServletRequest request, Model model, @RequestBody String jsonArrayString)
655
			throws Exception {
24406 amit.gupta 656
		JSONArray jsonArray = new JSONArray(jsonArrayString);
24410 amit.gupta 657
		for (int i = 0; i < jsonArray.length(); i++) {
24406 amit.gupta 658
			JSONObject obj = jsonArray.getJSONObject(i);
25378 tejbeer 659
 
24406 amit.gupta 660
			TagListing tl = tagListingRepository.selectByItemId(obj.getInt("id"));
25378 tejbeer 661
			if (tl == null) {
662
				continue;
663
			} else {
664
				tl.setActive(obj.getBoolean("active"));
665
				tagListingRepository.persist(tl);
666
			}
24406 amit.gupta 667
		}
24410 amit.gupta 668
		model.addAttribute("response", true);
23855 amit.gupta 669
		return "response";
670
	}
24231 amit.gupta 671
 
672
	@RequestMapping(value = "/indent/create-po", method = RequestMethod.POST)
23796 amit.gupta 673
	public String raisePO(HttpServletRequest request, Model model) throws Exception {
674
		boolean success = false;
675
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
676
		int fofoId = loginDetails.getFofoId();
677
		List<ItemPriceQuantity> itemQuantities = this.getItemQuantities(fofoId);
678
		CustomRetailer customRetailer = retailerService.getFofoRetailers(Arrays.asList(fofoId)).get(fofoId);
679
		Client userClient = new UserClient().getClient();
24231 amit.gupta 680
		double totalAmount = itemQuantities.stream().mapToDouble(x -> x.getQty() * x.getPrice()).sum();
23796 amit.gupta 681
 
24231 amit.gupta 682
		if (totalAmount > 0) {
23796 amit.gupta 683
			userClient.addItemPricingToCart(customRetailer.getCartId(), itemQuantities);
684
			User user = userRepository.selectById(loginDetails.getFofoId());
685
			userClient = new UserClient().getClient();
686
			LOGGER.info("Setting wallet amount in cart");
24231 amit.gupta 687
			long transactionId = userClient.createOrders(user.getActiveCartId(), "", 0, "", 0, loginDetails.getFofoId(),
688
					7890, OrderSource.WEBSITE.getValue(), true);
23796 amit.gupta 689
			LOGGER.info("Creating wallet payment for transactionId - {}", transactionId);
690
			createPayment(user, totalAmount, transactionId);
24231 amit.gupta 691
			TransactionService.Client transactionClient = new TransactionClient().getClient();
23796 amit.gupta 692
			transactionClient.changeTransactionStatus(transactionId, TransactionStatus.AUTHORIZED,
24231 amit.gupta 693
					"Payment received for the order", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 694
			transactionClient.changeTransactionStatus(Long.valueOf(transactionId), TransactionStatus.IN_PROCESS,
24231 amit.gupta 695
					"Paid fully through wallet", PickUpType.RUNNER.getValue(), OrderType.B2B, OrderSource.WEBSITE);
23796 amit.gupta 696
			LOGGER.info("Successfully created transaction: " + transactionId + " for amount: " + totalAmount);
697
			transactionClient = new TransactionClient().getClient();
698
			transactionClient.markOrderForRegisteredGstInvoice(Collections.singletonList(Long.valueOf(transactionId)));
699
			try {
700
				transactionClient.enqueueTransactionInfoEmail(transactionId);
701
			} catch (Exception e1) {
702
				e1.printStackTrace();
703
				LOGGER.error("Unable to update status of transaction. Thrift Exception:", e1);
704
			}
705
			resetCart(transactionClient.getTransaction(transactionId));
706
		}
707
		model.addAttribute("response", mvcResponseSender.createResponseString(success));
708
		return "response";
709
	}
24231 amit.gupta 710
 
711
	private void createPayment(User user, double totalAmount, long transactionId)
712
			throws NumberFormatException, PaymentException, TException {
23796 amit.gupta 713
		List<Attribute> paymentAttributes = new ArrayList<Attribute>();
714
		in.shop2020.payments.PaymentService.Client paymentClient = new PaymentClient().getClient();
715
		paymentAttributes.add(new Attribute("payMethod", "7890"));
24231 amit.gupta 716
		long paymentId = paymentClient.createPayment(user.getId(), totalAmount, WALLET_GATEWAY_ID, transactionId,
717
				false);
718
		paymentClient.updatePaymentDetails(paymentId, null, null, null, null, null, null, null, null,
719
				PaymentStatus.SUCCESS, null, paymentAttributes);
23796 amit.gupta 720
	}
24231 amit.gupta 721
 
23796 amit.gupta 722
	private List<ItemPriceQuantity> getItemQuantities(int fofoId) throws ProfitMandiBusinessException {
723
		List<ItemPriceQuantity> itemQuantities = new ArrayList<>();
24231 amit.gupta 724
		/*
725
		 * Map<Integer, ItemIdAvailability> itemCisMap = null; List<ItemIdAvailability>
726
		 * currentInventorySnapshots = currentInventorySnapshotRepository
727
		 * .selectItemsStock(fofoId); itemCisMap =
728
		 * currentInventorySnapshots.stream().filter(x -> x.getAvailability() > 0)
729
		 * .collect(Collectors.toMap(x -> x.getItemId(), x -> x));
730
		 * List<StockAllocationModel> stockAllocationList =
731
		 * stockAllocationService.getStockAllocation(fofoId, true);
732
		 * 
733
		 * Map<Integer, StockAllocationModel> itemStockAllocationMap =
734
		 * stockAllocationList.stream() .collect(Collectors.toMap(x -> x.catalogId(), x
735
		 * -> x)); Map<Integer, Integer> itemsInTransit = null;
736
		 * LOGGER.info("Item Stock Allocation Model Map {}", itemStockAllocationMap);
737
		 * List<TagListing> tagListings = tagListingRepository.selectAll(false);
738
		 * List<Order> inTransitOrders = orderRepository.selectOrders(fofoId,
739
		 * validOrderStatusList); inTransitOrders =
740
		 * this.filterValidOrders(inTransitOrders); itemsInTransit =
741
		 * inTransitOrders.stream().collect(Collectors.groupingBy(x ->
742
		 * x.getLineItem().getItemId(), Collectors.summingInt(x ->
743
		 * x.getLineItem().getQuantity())));
744
		 * 
745
		 * Iterator<TagListing> iterator = tagListings.iterator();
746
		 * 
747
		 * int toBeOrdered = 0; while (iterator.hasNext()) { TagListing tagListing =
748
		 * iterator.next(); LOGGER.info(" tagListing.setAllocatedQuantity {}",
749
		 * tagListing.getAllocatedQuantity()); if
750
		 * (!itemCisMap.containsKey(tagListing.getItemId()) &&
751
		 * !itemStockAllocationMap.containsKey(tagListing.getItemId())) {
752
		 * iterator.remove(); continue; } ItemIdAvailability itemIdAvailability =
753
		 * itemCisMap.get(tagListing.getItemId());
754
		 * tagListing.setStockInHand(itemIdAvailability == null ? 0 :
755
		 * itemIdAvailability.getAvailability()); StockAllocationModel
756
		 * stockAllocationModel = itemStockAllocationMap.get(tagListing.getItemId());
757
		 * 
758
		 * if (itemsInTransit.containsKey(tagListing.getItemId())) {
759
		 * tagListing.setInTransitQuantity(itemsInTransit.get(tagListing.getItemId()));
760
		 * } else { tagListing.setInTransitQuantity(0); } if (stockAllocationModel !=
761
		 * null) { tagListing.setAllocatedQuantity(stockAllocationModel.getQuantity());
762
		 * toBeOrdered = Math.max(tagListing.getAllocatedQuantity() -
763
		 * tagListing.getInTransitQuantity() - tagListing.getStockInHand(), 0); if
764
		 * (toBeOrdered > 0) { ItemPriceQuantity ipq = new ItemPriceQuantity();
765
		 * ipq.setItemId(tagListing.getItemId()); ipq.setQty((long) toBeOrdered);
766
		 * ipq.setPrice(tagListing.getSellingPrice()); itemQuantities.add(ipq); } } }
767
		 */
23796 amit.gupta 768
		return itemQuantities;
769
 
770
	}
24231 amit.gupta 771
 
23796 amit.gupta 772
	private long resetCart(Transaction transaction) {
773
		long sum = 0;
774
		Map<Long, Double> items = new HashMap<Long, Double>();
775
		for (in.shop2020.model.v1.order.Order order : transaction.getOrders()) {
776
			sum += order.getGvAmount();
777
			for (LineItem lineitem : order.getLineitems()) {
778
				Long itemId = lineitem.getItem_id();
779
				Double quantity = items.get(itemId);
780
				if (quantity == null) {
781
					quantity = lineitem.getQuantity();
782
				} else {
783
					quantity = quantity + lineitem.getQuantity();
784
				}
785
				items.put(itemId, quantity);
786
			}
787
		}
788
 
789
		LOGGER.debug("Items to reset in cart are: " + items);
790
 
791
		try {
792
			Client userClient = new UserClient().getClient();
793
			userClient.resetCart(transaction.getShoppingCartid(), items);
794
		} catch (TException e) {
795
			LOGGER.error("Error while updating information in payment database.", e);
796
		} catch (ShoppingCartException e) {
797
			LOGGER.error("Error while reseting the cart in cart database.", e);
798
		} catch (Exception e) {
799
			LOGGER.error("Unexpected exception", e);
800
		}
801
		return sum;
802
	}
803
 
25721 tejbeer 804
	@RequestMapping(value = "/getFocusedModel", method = RequestMethod.GET)
805
	public String getFocusedModel(HttpServletRequest request,
806
			@RequestParam(name = "offset", defaultValue = "0") int offset,
807
			@RequestParam(name = "limit", defaultValue = "10") int limit, Model model)
808
			throws ProfitMandiBusinessException {
809
		List<FocusedModel> focusedModels = focusedModelRepository.selectAll(offset, limit);
810
 
811
		Map<Integer, Item> itemMap = this.getItemByCatalogId(focusedModels);
812
 
813
		model.addAttribute("focusedModels", focusedModels);
814
		model.addAttribute("itemMap", itemMap);
815
 
816
		return "focused_model";
817
	}
818
 
819
	private Map<Integer, Item> getItemByCatalogId(List<FocusedModel> focusedModels) {
820
		Map<Integer, Item> itemMap = new HashMap<>();
821
		for (FocusedModel focusedModel : focusedModels) {
822
			List<Item> items = itemRepository.selectAllByCatalogItemId(focusedModel.getCatalogId());
823
			itemMap.put(items.get(0).getCatalogItemId(), items.get(0));
824
		}
825
 
826
		return itemMap;
827
	}
828
 
829
	@RequestMapping(value = "/focusedModel", method = RequestMethod.POST)
830
	public String focusedModel(HttpServletRequest request, @RequestParam int catalogId, @RequestParam int recommended,
831
			@RequestParam int minimumQty, Model model) throws ProfitMandiBusinessException {
832
 
833
		FocusedModel fm = new FocusedModel();
834
		fm.setCatalogId(catalogId);
835
		fm.setMinimumQty(minimumQty);
836
		fm.setRecommendedQty(recommended);
837
		fm.setCreatedTimestamp(LocalDateTime.now());
838
		focusedModelRepository.persist(fm);
839
		return "focused_model";
840
	}
841
 
842
	@RequestMapping(value = "/removeItem", method = RequestMethod.DELETE)
843
	public String removeFocusedModelItem(HttpServletRequest request,
844
			@RequestParam(name = "catalogId", defaultValue = "0") int catalogId, Model model) throws Exception {
845
 
846
		focusedModelRepository.deleteById(catalogId);
847
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
848
		return "response";
849
	}
850
}