Subversion Repositories SmartDukaan

Rev

Rev 32367 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.security.Key;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.web.client.RestClient;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.fofo.Campaign;
import com.spice.profitmandi.dao.entity.fofo.Customer;
import com.spice.profitmandi.dao.entity.fofo.ThriweMembers;
import com.spice.profitmandi.dao.model.thriwe.benefit.BenefitGroup;
import com.spice.profitmandi.dao.model.thriwe.benefit.BenefitResponse;
import com.spice.profitmandi.dao.model.thriwe.benefitConfiguration.BenefitConfigurationResponse;
import com.spice.profitmandi.dao.repository.fofo.CampaignRepository;
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
import com.spice.profitmandi.dao.repository.fofo.ThriweMemberRepository;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Controller
@Transactional(rollbackFor = Throwable.class)
public class ThriweController {

    @Autowired
    private ResponseSender<?> responseSender;

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    RestClient restClient;

   // @Value("${thriwe.account.token}")
    private String token;

    @Autowired
    CampaignRepository campaignRepository;

    @Autowired
    private ThriweMemberRepository thriweMemberRepository;

    @Autowired
    private Gson gson;


    private static final Logger LOGGER = LogManager.getLogger(ThriweController.class);


    @RequestMapping(value = "/thriwe/validate/customer", method = RequestMethod.GET)
    public ResponseEntity<?> validateCustomer(HttpServletRequest request) throws HttpHostConnectException, ProfitMandiBusinessException {

        List<Campaign> campaigns = campaignRepository.selectAll();
        String memberShipId = null;
        if (!campaigns.isEmpty()) {

            Campaign campaign = campaigns.get(0);
            Customer customer = customerRepository.selectById(32697);

            Map<String, String> params = new HashMap<String, String>();
            String userName = customer.getId() + "-" + campaign.getId();
            LOGGER.info("token {}", token);


            String secretKey = "smartdukan@thriwe_123smartdukaan";

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("exp", LocalDateTime.now().plusDays(4).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() / 1000);
            jsonObject.put("iat", LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() / 1000);
            jsonObject.put("userName", userName);
            jsonObject.put("email", customer.getEmailId());
            jsonObject.put("mobileNumber", customer.getMobileNumber());
            jsonObject.put("firstName", customer.getFirstName());
            jsonObject.put("lastName", customer.getLastName());
            jsonObject.put("expiryDate", LocalDate.now().plusDays(4).format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));

            LOGGER.info("jsonObject {}", jsonObject.toString());

            Map<String, Object> headersjwt = new HashMap<>();
            headersjwt.put("alg", "HS256");
            headersjwt.put("typ", "JWT");

            Key key = Keys.hmacShaKeyFor(secretKey.getBytes());

            String jwt = Jwts.builder().setHeaderParam("alg", "HS256").setHeaderParam("typ", "JWT").setPayload(jsonObject.toString()).signWith(key).compact();

            LOGGER.info("jwt {}", jwt);


            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Project-Code", "SMART_DUKAAN");
            headers.put("X-Auth-Token", jwt);
            String url = "https://staging-india-api-gateway.thriwe.com/validate-user";
            HttpResponse response = restClient.getResponse(url, params, headers);
            LOGGER.info("response {}", response);


            Header[] authToken = response.getHeaders("Authorization");
            LOGGER.info("authToken {}", Arrays.asList(authToken).get(0).getValue());

            ThriweMembers thriweMember = thriweMemberRepository.selectByUsername(userName, campaign.getStartDate(), campaign.getEndDate());
            LOGGER.info("thriweMembers {}", thriweMember);

            if (thriweMember != null) {

                thriweMember.setAuthToken(Arrays.asList(authToken).get(0).getValue());

                try {
                    String responseString = restClient.toString(response.getEntity().getContent());
                    LOGGER.info("responseString {}", new JSONObject(responseString).get("membershipId"));
                    JSONObject responseJson = new JSONObject(responseString);
                    String membershipId = responseJson.getString("membershipId");
                    thriweMember.setMembershipId(membershipId);
                    memberShipId = thriweMember.getMembershipId();
                } catch (Exception e) {
                    // TODO: handle exception
                }


            }
        }

        return responseSender.ok(memberShipId);
    }

    @RequestMapping(value = "/thriwe/benefit-configs", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "")
    public ResponseEntity<?> benefitConfigs(HttpServletRequest request, @RequestParam String membershipId) throws HttpHostConnectException, ProfitMandiBusinessException {


        ThriweMembers thriweMember = thriweMemberRepository.selectByMembershipId(membershipId);

        Map<String, String> params = new HashMap<String, String>();
        Map<String, String> headers = new HashMap<String, String>();

        headers.put("Authorization", thriweMember.getAuthToken());
        headers.put("Project-Code", "SMART_DUKAAN");

        String url = "https://staging-india-api-gateway.thriwe.com/client/benefit-configs";

        String response = restClient.get(url, params, headers);
        LOGGER.info("response {}", response);

        BenefitConfigurationResponse benefitConfigurationResponse = gson.fromJson(response, BenefitConfigurationResponse.class);

        LOGGER.info("benefitConfigurationResponse {}", benefitConfigurationResponse);

        return responseSender.ok(benefitConfigurationResponse);
    }

    @RequestMapping(value = "/thriwe/benefits", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "")
    public ResponseEntity<?> benefits(HttpServletRequest request, @RequestParam String membershipId, @RequestParam String configId) throws HttpHostConnectException, ProfitMandiBusinessException {

        ThriweMembers thriweMember = thriweMemberRepository.selectByMembershipId(membershipId);

        Map<String, String> params = new HashMap<String, String>();

        params.put("configId", configId);

        Map<String, String> headers = new HashMap<String, String>();

        headers.put("Authorization", thriweMember.getAuthToken());
        headers.put("Project-Code", "SMART_DUKAAN");

        String url = "https://staging-india-api-gateway.thriwe.com/client/benefit-items";
        String response = restClient.get(url, params, headers);

        BenefitResponse benefitResponse = gson.fromJson(response, BenefitResponse.class);

        LOGGER.info("benefitResponse {}", benefitResponse);

        return responseSender.ok(benefitResponse);

    }


    @RequestMapping(value = "/thriwe/createBooking", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "")
    public ResponseEntity<?> createBooking(HttpServletRequest request, @RequestBody BenefitGroup benefitGroup) throws HttpHostConnectException, ProfitMandiBusinessException {

        ThriweMembers thriweMember = thriweMemberRepository.selectByMembershipId(benefitGroup.getMembershipId());

        Map<String, String> headers = new HashMap<String, String>();

        headers.put("token", token);
        headers.put("Project-Code", "SMART_DUKAAN");

        String url = "https://staging-india-api-gateway.thriwe.com/create-booking";
        String response = restClient.post(url, benefitGroup.toString(), headers);

        LOGGER.info("response {}", response);
        return responseSender.ok(true);
    }


}