<commit_before>package com.hackovation.hybo.Controllers;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hack17.hybo.domain.Allocation;
import com.hack17.hybo.domain.CurrentDate;
import com.hack17.hybo.domain.InvestorProfile;
import com.hack17.hybo.domain.Portfolio;
import com.hack17.hybo.domain.UserClientMapping;
import com.hack17.hybo.repository.PortfolioRepository;
import com.hackovation.hybo.CreatedBy;
import com.hackovation.hybo.Util.HyboUtil;
import com.hackovation.hybo.bean.DataVO;
import com.hackovation.hybo.bean.ProfileRequest;
import com.hackovation.hybo.bean.ProfileResponse;
import com.hackovation.hybo.rebalance.Rebalance;
import com.hackovation.hybo.services.PortfolioService;

@RestController
@RequestMapping(value="/black")
@CrossOrigin
public class BlackLittermanController {
	
	@Autowired
	PortfolioRepository portfolioRepository;
	@Autowired
	PortfolioService portfolioService;
	
	@Autowired
	Rebalance rebalance;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	
	@RequestMapping(value="/validateUser", method=RequestMethod.GET,produces="application/json")
	public @ResponseBody String validateUser(@RequestParam(name="userId")String userId) throws JsonProcessingException{
		String str;
		Object object = portfolioRepository.getEntityForAny(UserClientMapping.class,userId);
		if(object==null){
			ProfileResponse response = new ProfileResponse();
			response.setLabel("0");
			ObjectMapper responseMapper = new ObjectMapper();
			str = responseMapper.writeValueAsString(response);
			return str;
		}else{
			UserClientMapping existingObject = (UserClientMapping)object;
			ProfileResponse response = new ProfileResponse();
			response.setLabel("1");
			ObjectMapper responseMapper = new ObjectMapper();
			str = responseMapper.writeValueAsString(response);
			return str;
		}
	}

	@RequestMapping(value="/createProfile", method=RequestMethod.POST,produces = "application/json",consumes =  MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody String createProfileAndCreatePortfolio(HttpEntity<String> entity){
		String str = "";
		StopWatch stopWatch = new StopWatch("Started Building Profile!!!");
		stopWatch.start();
		try {
			String json = entity.getBody();
			ObjectMapper mapper = new ObjectMapper();
			ProfileRequest profileRequest;
			profileRequest = mapper.readValue(json, ProfileRequest.class);
			String userId = profileRequest.getUserId();
			InvestorProfile investorProfile = portfolioService.createProfile(profileRequest);
			Date date = new Date();
			if(profileRequest.getDate() != null && !profileRequest.getDate().isEmpty()){
				date = sdf.parse(profileRequest.getDate());
			}else{
				CurrentDate existingDate = (CurrentDate)portfolioRepository.getEntity(1, CurrentDate.class);
				date = existingDate.getDate();
			}
			Map<String,Portfolio> dataMap = createPortfolio(investorProfile, profileRequest.getAmount(),date,userId);
			
			
			List<ProfileResponse> responseList = new ArrayList<>();
			Set<Entry<String,Portfolio>> entrySet = dataMap.entrySet();
			Map<String,String> etfAssetClassMap = HyboUtil.ETFToAssetClassMap();
			for(Entry<String,Portfolio> entry:entrySet){
				Portfolio portfolio= entry.getValue();
				List<Allocation> allocationList = portfolio.getAllocations();
				for(Allocation allocation:allocationList){
					ProfileResponse response = new ProfileResponse();
					response.setClientId(Integer.valueOf(entry.getKey()));
					response.setLabel(etfAssetClassMap.get(allocation.getFund().getTicker()));
					response.setValue(String.valueOf(allocation.getPercentage()));
					responseList.add(response);
				}
			}
			ObjectMapper responseMapper = new ObjectMapper();
			str = responseMapper.writeValueAsString(responseList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		stopWatch.stop();
		System.out.println(stopWatch.shortSummary());
		return str;
	}
	
	public Map<String,Portfolio> createPortfolio(InvestorProfile profile,int investment,Date date,String userId) throws Exception{
		System.out.println("Started creating portfolio for client: "+userId+" For Date: "+date );
		return portfolioService.buildPortfolio(profile,userId,false,date,investment);
	}
	
	@RequestMapping(value="/getPortfolioCid", method=RequestMethod.GET,produces = "application/json")
	public @ResponseBody String getPortfolioForClientIdAsPerAmount(@RequestParam(name="userId") String userId){
		String str = "No Data To Display";
		try{
			int clientId = getClientId(userId);
			List<Portfolio>	portfolioList = portfolioRepository.getPortfolio(Integer.valueOf(clientId));
			Portfolio portfolio = portfolioList.get(0);
			
			List<ProfileResponse> responseList = new ArrayList<>();
			List<Allocation> allocationList = portfolio.getAllocations();
			
			Calendar cal = Calendar.getInstance();
			CurrentDate existingDate = (CurrentDate)portfolioRepository.getEntity(1, CurrentDate.class);
			Date date = existingDate.getDate();
			cal.setTime(date);
	 		cal = trimTime(cal);

			for(Allocation allocation:allocationList){
				if(allocation.getCostPrice()==0d || allocation.getIsActive().equals("N"))continue;
				double latestPrice = portfolioRepository.getIndexPriceForGivenDate(allocation.getFund().getTicker(), cal.getTime());
				ProfileResponse response = new ProfileResponse();
				response.setClientId(Integer.valueOf(clientId));
				response.setLabel(allocation.getFund().getTicker());
				response.setValue(String.valueOf(allocation.getCostPrice()*allocation.getQuantity()));
				responseList.add(response);
			}
			ObjectMapper responseMapper = new ObjectMapper();
			str = responseMapper.writeValueAsString(responseList);

			
			
		}catch(Exception e){<commit_msg>get portfolio price as per date<commit_after>package com.hackovation.hybo.Controllers;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hack17.hybo.domain.Allocation;
import com.hack17.hybo.domain.CurrentDate;
import com.hack17.hybo.domain.InvestorProfile;
import com.hack17.hybo.domain.Portfolio;
import com.hack17.hybo.domain.UserClientMapping;
import com.hack17.hybo.repository.PortfolioRepository;
import com.hackovation.hybo.CreatedBy;
import com.hackovation.hybo.Util.HyboUtil;
import com.hackovation.hybo.bean.DataVO;
import com.hackovation.hybo.bean.ProfileRequest;
import com.hackovation.hybo.bean.ProfileResponse;
import com.hackovation.hybo.rebalance.Rebalance;
import com.hackovation.hybo.services.PortfolioService;

@RestController
@RequestMapping(value="/black")
@CrossOrigin
public class BlackLittermanController {
	
	@Autowired
	PortfolioRepository portfolioRepository;
	@Autowired
	PortfolioService portfolioService;
	
	@Autowired
	Rebalance rebalance;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	
	@RequestMapping(value="/validateUser", method=RequestMethod.GET,produces="application/json")
	public @ResponseBody String validateUser(@RequestParam(name="userId")String userId) throws JsonProcessingException{
		String str;
		Object object = portfolioRepository.getEntityForAny(UserClientMapping.class,userId);
		if(object==null){
			ProfileResponse response = new ProfileResponse();
			response.setLabel("0");
			ObjectMapper responseMapper = new ObjectMapper();
			str = responseMapper.writeValueAsString(response);
			return str;
		}else{
			UserClientMapping existingObject = (UserClientMapping)object;
			ProfileResponse response = new ProfileResponse();
			response.setLabel("1");
			ObjectMapper responseMapper = new ObjectMapper();
			str = responseMapper.writeValueAsString(response);
			return str;
		}
	}

	@RequestMapping(value="/createProfile", method=RequestMethod.POST,produces = "application/json",consumes =  MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody String createProfileAndCreatePortfolio(HttpEntity<String> entity){
		String str = "";
		StopWatch stopWatch = new StopWatch("Started Building Profile!!!");
		stopWatch.start();
		try {
			String json = entity.getBody();
			ObjectMapper mapper = new ObjectMapper();
			ProfileRequest profileRequest;
			profileRequest = mapper.readValue(json, ProfileRequest.class);
			String userId = profileRequest.getUserId();
			InvestorProfile investorProfile = portfolioService.createProfile(profileRequest);
			Date date = new Date();
			if(profileRequest.getDate() != null && !profileRequest.getDate().isEmpty()){
				date = sdf.parse(profileRequest.getDate());
			}else{
				CurrentDate existingDate = (CurrentDate)portfolioRepository.getEntity(1, CurrentDate.class);
				date = existingDate.getDate();
			}
			Map<String,Portfolio> dataMap = createPortfolio(investorProfile, profileRequest.getAmount(),date,userId);
			
			
			List<ProfileResponse> responseList = new ArrayList<>();
			Set<Entry<String,Portfolio>> entrySet = dataMap.entrySet();
			Map<String,String> etfAssetClassMap = HyboUtil.ETFToAssetClassMap();
			for(Entry<String,Portfolio> entry:entrySet){
				Portfolio portfolio= entry.getValue();
				List<Allocation> allocationList = portfolio.getAllocations();
				for(Allocation allocation:allocationList){
					ProfileResponse response = new ProfileResponse();
					response.setClientId(Integer.valueOf(entry.getKey()));
					response.setLabel(etfAssetClassMap.get(allocation.getFund().getTicker()));
					response.setValue(String.valueOf(allocation.getPercentage()));
					responseList.add(response);
				}
			}
			ObjectMapper responseMapper = new ObjectMapper();
			str = responseMapper.writeValueAsString(responseList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		stopWatch.stop();
		System.out.println(stopWatch.shortSummary());
		return str;
	}
	
	public Map<String,Portfolio> createPortfolio(InvestorProfile profile,int investment,Date date,String userId) throws Exception{
		System.out.println("Started creating portfolio for client: "+userId+" For Date: "+date );
		return portfolioService.buildPortfolio(profile,userId,false,date,investment);
	}
	
	@RequestMapping(value="/getPortfolioCid", method=RequestMethod.GET,produces = "application/json")
	public @ResponseBody String getPortfolioForClientIdAsPerAmount(@RequestParam(name="userId") String userId){
		String str = "No Data To Display";
		try{
			int clientId = getClientId(userId);
			List<Portfolio>	portfolioList = portfolioRepository.getPortfolio(Integer.valueOf(clientId));
			Portfolio portfolio = portfolioList.get(0);
			
			List<ProfileResponse> responseList = new ArrayList<>();
			List<Allocation> allocationList = portfolio.getAllocations();
			
			Calendar cal = Calendar.getInstance();
			CurrentDate existingDate = (CurrentDate)portfolioRepository.getEntity(1, CurrentDate.class);
			Date date = existingDate.getDate();
			cal.setTime(date);
	 		cal = trimTime(cal);

			for(Allocation allocation:allocationList){
				if(allocation.getCostPrice()==0d || allocation.getIsActive().equals("N"))continue;
				double latestPrice = portfolioRepository.getIndexPriceForGivenDate(allocation.getFund().getTicker(), cal.getTime());
				ProfileResponse response = new ProfileResponse();
				response.setClientId(Integer.valueOf(clientId));
				response.setLabel(allocation.getFund().getTicker());
				response.setValue(String.valueOf(latestPrice*allocation.getQuantity()));
				responseList.add(response);
			}
			ObjectMapper responseMapper = new ObjectMapper();
			str = responseMapper.writeValueAsString(responseList);

			
			
		}catch(Exception e){
{'fraction_non_alphanumeric': 0.1116828525873315, 'fraction_numerical': 0.002609073778808523, 'mean_word_length': 6.1608718214841725, 'pattern_counts': {'":': 0, '<': 31, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5328097', 'n_tokens_mistral': 4297, 'n_tokens_neox': 3868, 'n_words': 700}