Rev 27427 | Rev 27432 | 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.io.IOException;import java.time.LocalDate;import java.time.LocalDateTime;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.apache.velocity.app.VelocityEngine;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.model.CustomRetailer;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.fofo.CustomerRepository;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);@AutowiredResponseSender<?> responseSender;@AutowiredGson gson;@Autowiredprivate HypertrackKeyRepository hypertrackKeyRepository;@Autowiredprivate EmployeeAttendanceRepository employeeAttendanceRepository;@Autowiredprivate FofoStoreRepository fofoStoreRepository;@Autowiredprivate 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.setHypertrackKeyId(hyperTrackKeyModel.getHyperTrackId());hyperTrackKey.setDeviceId(hyperTrackKeyModel.getDeviceId());}hyperTrackKey.setUserId(hyperTrackKeyModel.getUserId());hyperTrackKey.setCreatedTimestamp(LocalDateTime.now());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 {double lat1 = 28.516045882182738;double lng1 = 77.3771954997187;HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(userId, deviceId);// EmployeeAttendance employeeAttendance =// employeeAttendanceRepository.selectLatestPunchTimeStamp();List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKey(userId, deviceId,LocalDate.now());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 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");EmployeeAttendanceModel em = new EmployeeAttendanceModel();em.setDistance(dist);em.setLatitude(lat2);em.setLongitude(lng2);LOGGER.info("hyperTrackKey" + hyperTrackKey);LOGGER.info("employeeAttendance" + employeeAttendances);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);}} else {em.setPunchIn(false);}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 = "/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);return responseSender.ok(true);}@RequestMapping(value = "/create/geofence", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> createGreofence(HttpServletRequest request)throws IOException, ProfitMandiBusinessException {List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();for (FofoStore fofoStore : fofoStores) {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(fofoStore.getLongitude());coordinates.put(fofoStore.getLatitude());geo.put("type", "Point");geo.put("coordinates", coordinates);geometry.put("geometry", geo);JSONObject metadata = new JSONObject();metadata.put("name", customRetailer.getBusinessName());metadata.put("city", customRetailer.getAddress().getCity());geometry.put("metadata", metadata);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();}return responseSender.ok(true);}}