Subversion Repositories SmartDukaan

Rev

Rev 30589 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.List;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
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.util.ResponseSender;
import com.spice.profitmandi.dao.entity.dtr.EmployeeAttendance;
import com.spice.profitmandi.dao.entity.dtr.HyperTrackKeyModel;
import com.spice.profitmandi.dao.entity.dtr.HypertrackKey;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.enumuration.dtr.PunchType;
import com.spice.profitmandi.dao.model.EmployeeAttendanceModel;
import com.spice.profitmandi.dao.repository.dtr.EmployeeAttendanceRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.user.HypertrackKeyRepository;
import com.spice.profitmandi.service.user.RetailerService;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

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

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

        @Autowired
        ResponseSender<?> responseSender;

        @Autowired
        Gson gson;

        @Autowired
        private HypertrackKeyRepository hypertrackKeyRepository;

        @Autowired
        private EmployeeAttendanceRepository employeeAttendanceRepository;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private RetailerService retailerService;

        private static final String ACCOUNT_ID = "aZ6flHhrgPIEl18buHdPBdueEN4";
        private static final String SECRET_KEY = "a7rsX5B4UNNfTTx1-IJ19qdH48BT4YvBKlQJg3n3_KKNe7WWych55g";

        @RequestMapping(value = "/devices/hypertrackId", 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<?> deviceHypertrackId(HttpServletRequest request,
                        @RequestBody HyperTrackKeyModel hyperTrackKeyModel) {
                HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(hyperTrackKeyModel.getUserId(),
                                hyperTrackKeyModel.getDeviceId());
                if (hyperTrackKey == null) {
                        hyperTrackKey = new HypertrackKey();
                        hyperTrackKey.setUserId(hyperTrackKeyModel.getUserId());
                        hyperTrackKey.setCreatedTimestamp(LocalDateTime.now());
                        hyperTrackKey.setDeviceId(hyperTrackKeyModel.getDeviceId());
                }

                hyperTrackKey.setHypertrackKeyId(hyperTrackKeyModel.getHyperTrackId());

                hyperTrackKey.setUpdatedTimestamp(LocalDateTime.now());
                hypertrackKeyRepository.persist(hyperTrackKey);
                return responseSender.ok(true);
        }

        @RequestMapping(value = "/devices/location", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> getLocationByKeyId(HttpServletRequest request, @RequestParam int userId,
                        @RequestParam int deviceId) throws IOException, MessagingException, ProfitMandiBusinessException {

                LOGGER.info("UserId -> {}, Device Id -> {}", userId, deviceId);
                double lat1 = 28.516045882182738;
                double lng1 = 77.3771954997187;

                HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(userId, deviceId);

                List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKey(userId, deviceId,
                                LocalDate.now());
                EmployeeAttendanceModel em = null;
                LOGGER.info("hyperTrackKey" + hyperTrackKey);
                LOGGER.info("employeeAttendance" + employeeAttendances);
                OkHttpClient client = new OkHttpClient();

                String authString = "Basic "
                                + Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());

                Request request1 = new Request.Builder()
                                .url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId()).get()
                                .addHeader("Authorization", authString).build();

                Response response = client.newCall(request1).execute();

                JSONObject jsonObj = new JSONObject(response.body().string());

                JSONObject deviceStatus = jsonObj.getJSONObject("device_status");
                String status = deviceStatus.getString("value");

                if (status.equals("inactive") || status.equals("disconnected")) {

                        LOGGER.info("status" + status);
                        okhttp3.RequestBody reqbody = okhttp3.RequestBody.create(null, new byte[0]);

                        Request request2 = new Request.Builder()
                                        .url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId() + "/start")
                                        .post(reqbody).addHeader("Authorization", authString).build();

                        Response resp = client.newCall(request2).execute();
                        LOGGER.info("resp" + resp);
                        em = new EmployeeAttendanceModel();
                        em.setPunchIn(false);
                        em.setDeviceStatus(status);
                } else if (status.equals("active")) {
                        JSONObject c = jsonObj.getJSONObject("location");
                        JSONObject d = c.getJSONObject("geometry");
                        JSONArray coords = d.getJSONArray("coordinates");

                        double lat2 = coords.getDouble(1);
                        double lng2 = coords.getDouble(0);
                        double dist = distance(lat1, lng1, lat2, lng2, "m");
                        LOGGER.info("jsonObj" + jsonObj);
                        JSONObject deviceData = deviceStatus.getJSONObject("data");
                        LOGGER.info("status1" + status);

                        em = new EmployeeAttendanceModel();
                        em.setDistance(dist);
                        em.setLatitude(lat2);
                        em.setLongitude(lng2);
                        em.setDeviceStatus(status);

                        if (!employeeAttendances.isEmpty()) {
                                if (employeeAttendances.get(0).getCreateTimestamp().toLocalDate().equals(LocalDate.now())) {
                                        if (employeeAttendances.get(0).getPunch().equals("punchIn")) {
                                                em.setPunchIn(true);
                                        } else {
                                                em.setPunchIn(false);
                                        }
                                } else {
                                        em.setPunchIn(false);
                                }

                                if (employeeAttendances.get(0).getPunch().equals("punchOut")) {
                                        LocalTime startTime = employeeAttendances.get(employeeAttendances.size() - 1).getCreateTimestamp()
                                                        .toLocalTime();
                                        Long secondsBetween = ChronoUnit.SECONDS.between(startTime,
                                                        employeeAttendances.get(0).getCreateTimestamp().toLocalTime());
                                        long hours = secondsBetween / 3600;
                                        long minutes = (secondsBetween % 3600) / 60;
                                        long seconds = secondsBetween % 60;
                                        em.setPunchHours(hours);
                                        em.setPunchMinutes(minutes);
                                        em.setPunchSeconds(seconds);

                                } else if (employeeAttendances.get(employeeAttendances.size() - 1).getPunch().equals("punchIn")) {
                                        LocalTime startTime = employeeAttendances.get(employeeAttendances.size() - 1).getCreateTimestamp()
                                                        .toLocalTime();
                                        Long secondsBetween = ChronoUnit.SECONDS.between(startTime, LocalDateTime.now().toLocalTime());
                                        long hours = secondsBetween / 3600;
                                        long minutes = (secondsBetween % 3600) / 60;
                                        long seconds = secondsBetween % 60;
                                        em.setPunchHours(hours);
                                        em.setPunchMinutes(minutes);
                                        em.setPunchSeconds(seconds);
                                }

                        } else {
                                em.setPunchIn(false);
                                em.setDeviceStatus(status);
                        }
                } else {

                        LOGGER.info("status3" + status);

                        em.setPunchIn(false);
                        em.setDeviceStatus(status);
                }
                return responseSender.ok(em);
        }

        private static double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
                if ((lat1 == lat2) && (lon1 == lon2)) {
                        return 0;
                } else {
                        double theta = lon1 - lon2;
                        double dist = Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
                                        + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta));
                        dist = Math.acos(dist);
                        dist = Math.toDegrees(dist);
                        dist = dist * 60 * 1.1515;
                        if (unit.equals("m")) {
                                dist = dist * 1.609344;
                                dist = dist / 0.0010000;
                        } else if (unit.equals("N")) {
                                dist = dist * 0.8684;
                        }
                        return (dist);
                }
        }

        @RequestMapping(value = "/getPunchHistory", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> getPunchHistory(HttpServletRequest request, @RequestParam int userId,
                        @RequestParam int deviceId) {

                List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKey(userId, deviceId,
                                LocalDate.now());

                return responseSender.ok(employeeAttendances);
        }

        @RequestMapping(value = "/employee/attendance", 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<?> employeeAttendance(HttpServletRequest request, @RequestParam(name = "userId") int userId,
                        @RequestParam(name = "deviceId") int deviceId, @RequestParam(name = "punchType") PunchType punchType,
                        @RequestParam(name = "punch") String punch) {

                EmployeeAttendance employeeAttendance = new EmployeeAttendance();
                employeeAttendance.setUserId(userId);
                employeeAttendance.setDeviceId(deviceId);
                employeeAttendance.setPunch(punch);
                employeeAttendance.setPunchType(punchType);
                employeeAttendance.setCreateTimestamp(LocalDateTime.now());
                employeeAttendanceRepository.persist(employeeAttendance);
                if (punch.equals("punchOut")) {
                        List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKeyASC(userId,
                                        deviceId, LocalDate.now());
                        long hours = 0;
                        long minutes = 0;
                        long seconds = 0;
                        long totalSeconds = 0;
                        LocalTime startTime = null;
                        LocalTime endTime = null;

                        for (EmployeeAttendance em : employeeAttendances) {
                                if (em.getPunch().equals("punchIn")) {
                                        startTime = em.getCreateTimestamp().toLocalTime();
                                } else if (em.getPunch().equals("punchOut")) {
                                        endTime = em.getCreateTimestamp().toLocalTime();
                                }
                                if (startTime != null && endTime != null) {
                                        Long secondsBetween = ChronoUnit.SECONDS.between(startTime, endTime);
                                        totalSeconds += secondsBetween;
                                        startTime = null;
                                        endTime = null;
                                }

                        }
                        hours = totalSeconds / 3600;
                        minutes = (totalSeconds % 3600) / 60;
                        seconds = totalSeconds % 60;
                        EmployeeAttendanceModel emm = new EmployeeAttendanceModel();
                        emm.setHours(hours);
                        emm.setMinutes(minutes);
                        emm.setSeconds(seconds);
                        return responseSender.ok(emm);

                }
                return responseSender.ok(true);
        }

        @RequestMapping(value = "/create/geofence", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> createGeofence(HttpServletRequest request)
                        throws IOException, ProfitMandiBusinessException {

                /*
                 * List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores(); for
                 * (FofoStore fofoStore : fofoStores) { if (fofoStore.getLatitude() != null &&
                 * fofoStore.getLongitude() != null) { CustomRetailer customRetailer =
                 * retailerService.getFofoRetailer(fofoStore.getId());
                 */
                OkHttpClient client = new OkHttpClient();

                okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
                JSONObject geofe = new JSONObject();
                JSONArray geofences = new JSONArray();
                JSONObject geometry = new JSONObject();
                JSONObject geo = new JSONObject();
                JSONArray coordinates = new JSONArray();
                coordinates.put(77.08596155373755);
                coordinates.put(28.64944201113976);
                geo.put("type", "Point");
                geo.put("coordinates", coordinates);
                geometry.put("geometry", geo);
                JSONObject metadata = new JSONObject();
                metadata.put("name", "Test");
                geometry.put("radius", 500);
                geofences.put(geometry);
                geofe.put("geofences", geofences);
                okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, geofe.toString());
                String authString = "Basic "
                                + Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());

                Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences").post(body)
                                .addHeader("Authorization", authString).build();

                Response response = client.newCall(request1).execute();
                String geofenceId = null;
                JSONArray ja = new JSONArray(response.body().string());
                for (int i = 0; i < ja.length(); i++) {
                        JSONObject c = ja.getJSONObject(i);
                        geofenceId = c.getString("geofence_id");
                }

                LOGGER.info("response" + response.body().string());

                return responseSender.ok(geofenceId);

        }

        @RequestMapping(value = "/getgeofence", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> getAllGeofences(HttpServletRequest request)
                        throws IOException, ProfitMandiBusinessException {

                OkHttpClient client = new OkHttpClient();

                String authString = "Basic "
                                + Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());

                // Get geofences created for all app users
                Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences")
                                .addHeader("Authorization", authString).build();

                Response response = client.newCall(request1).execute();
                return responseSender.ok(response.body().string());

        }

        @RequestMapping(value = "/deletegeofence", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> deleteGeofences(HttpServletRequest request, String geofenceId)
                        throws IOException, ProfitMandiBusinessException {
                OkHttpClient client = new OkHttpClient();

                String authString = "Basic "
                                + Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());

                Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences/" + geofenceId).delete()
                                .addHeader("Authorization", authString).build();

                Response response = client.newCall(request1).execute();
                return responseSender.ok(response.body().string());

        }

        @RequestMapping(value = "/devices/partner/location", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> getPartnerLocationByKeyId(HttpServletRequest request, @RequestParam int userId,
                        @RequestParam int deviceId, @RequestParam int fofoId)
                        throws IOException, MessagingException, ProfitMandiBusinessException {

                LOGGER.info("UserId -> {}, Device Id -> {}", userId, deviceId);
                FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);

                LOGGER.info("fs{}", fs);
                Double dist = null;
                HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(userId, deviceId);

                LOGGER.info("hyperTrackKey {}" + hyperTrackKey);
                OkHttpClient client = new OkHttpClient();

                String authString = "Basic "
                                + Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());

                Request request1 = new Request.Builder()
                                .url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId()).get()
                                .addHeader("Authorization", authString).build();

                Response response = client.newCall(request1).execute();

                JSONObject jsonObj = new JSONObject(response.body().string());

                LOGGER.info("jsonObj" + jsonObj);
                JSONObject deviceStatus = jsonObj.getJSONObject("device_status");
                String status = deviceStatus.getString("value");

                if (status.equals("inactive") || status.equals("disconnected")) {

                        LOGGER.info("status" + status);
                        okhttp3.RequestBody reqbody = okhttp3.RequestBody.create(null, new byte[0]);

                        Request request2 = new Request.Builder()
                                        .url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId() + "/start")
                                        .post(reqbody).addHeader("Authorization", authString).build();

                        Response resp = client.newCall(request2).execute();
                        LOGGER.info("resp" + resp);

                } else if (status.equals("active")) {
                        JSONObject c = jsonObj.getJSONObject("location");
                        JSONObject d = c.getJSONObject("geometry");
                        JSONArray coords = d.getJSONArray("coordinates");

                        double lat2 = coords.getDouble(1);
                        double lng2 = coords.getDouble(0);
                        dist = distance(Float.valueOf(fs.getLatitude()), Float.valueOf(fs.getLongitude()), lat2, lng2, "m");

                        // dist = distance(lat1, lng1, lat2, lng2, "m");
                        LOGGER.info("jsonObj" + jsonObj);

                        LOGGER.info("dist" + dist);
                        JSONObject deviceData = deviceStatus.getJSONObject("data");
                        LOGGER.info("status1" + status);

                }
                return responseSender.ok(dist);
        }

}