Subversion Repositories SmartDukaan

Rev

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