Subversion Repositories SmartDukaan

Rev

Rev 27432 | Rev 27443 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
27417 tejbeer 1
package com.spice.profitmandi.web.controller;
2
 
27421 tejbeer 3
import java.io.IOException;
4
import java.time.LocalDate;
27417 tejbeer 5
import java.time.LocalDateTime;
27421 tejbeer 6
import java.util.Base64;
7
import java.util.List;
27417 tejbeer 8
 
27421 tejbeer 9
import javax.mail.MessagingException;
27417 tejbeer 10
import javax.servlet.http.HttpServletRequest;
11
 
12
import org.apache.logging.log4j.LogManager;
13
import org.apache.logging.log4j.Logger;
27421 tejbeer 14
import org.apache.velocity.app.VelocityEngine;
15
import org.json.JSONArray;
16
import org.json.JSONObject;
27417 tejbeer 17
import org.springframework.beans.factory.annotation.Autowired;
18
import org.springframework.http.MediaType;
19
import org.springframework.http.ResponseEntity;
20
import org.springframework.stereotype.Controller;
21
import org.springframework.transaction.annotation.Transactional;
22
import org.springframework.web.bind.annotation.RequestBody;
23
import org.springframework.web.bind.annotation.RequestMapping;
24
import org.springframework.web.bind.annotation.RequestMethod;
27421 tejbeer 25
import org.springframework.web.bind.annotation.RequestParam;
27417 tejbeer 26
 
27
import com.google.gson.Gson;
27421 tejbeer 28
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
29
import com.spice.profitmandi.common.model.CustomRetailer;
27417 tejbeer 30
import com.spice.profitmandi.common.web.util.ResponseSender;
27421 tejbeer 31
import com.spice.profitmandi.dao.entity.dtr.EmployeeAttendance;
27417 tejbeer 32
import com.spice.profitmandi.dao.entity.dtr.HyperTrackKeyModel;
33
import com.spice.profitmandi.dao.entity.dtr.HypertrackKey;
27421 tejbeer 34
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
35
import com.spice.profitmandi.dao.enumuration.dtr.PunchType;
36
import com.spice.profitmandi.dao.model.EmployeeAttendanceModel;
37
import com.spice.profitmandi.dao.repository.dtr.EmployeeAttendanceRepository;
38
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
39
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
27417 tejbeer 40
import com.spice.profitmandi.dao.repository.user.HypertrackKeyRepository;
27421 tejbeer 41
import com.spice.profitmandi.service.user.RetailerService;
27417 tejbeer 42
 
43
import io.swagger.annotations.ApiImplicitParam;
44
import io.swagger.annotations.ApiImplicitParams;
45
import io.swagger.annotations.ApiOperation;
27421 tejbeer 46
import okhttp3.OkHttpClient;
47
import okhttp3.Request;
48
import okhttp3.Response;
27417 tejbeer 49
 
50
@Controller
51
@Transactional(rollbackFor = Throwable.class)
52
public class HyperTrackController {
53
 
54
	private static final Logger LOGGER = LogManager.getLogger(HyperTrackController.class);
55
 
56
	@Autowired
57
	ResponseSender<?> responseSender;
58
 
59
	@Autowired
60
	Gson gson;
61
 
62
	@Autowired
63
	private HypertrackKeyRepository hypertrackKeyRepository;
64
 
27421 tejbeer 65
	@Autowired
66
	private EmployeeAttendanceRepository employeeAttendanceRepository;
67
 
68
	@Autowired
69
	private FofoStoreRepository fofoStoreRepository;
70
 
71
	@Autowired
72
	private RetailerService retailerService;
73
 
27417 tejbeer 74
	private static final String ACCOUNT_ID = "aZ6flHhrgPIEl18buHdPBdueEN4";
75
	private static final String SECRET_KEY = "a7rsX5B4UNNfTTx1-IJ19qdH48BT4YvBKlQJg3n3_KKNe7WWych55g";
76
 
77
	@RequestMapping(value = "/devices/hypertrackId", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
78
	@ApiImplicitParams({
79
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
80
	@ApiOperation(value = "")
81
	public ResponseEntity<?> deviceHypertrackId(HttpServletRequest request,
82
			@RequestBody HyperTrackKeyModel hyperTrackKeyModel) {
83
		HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(hyperTrackKeyModel.getUserId(),
84
				hyperTrackKeyModel.getDeviceId());
85
		if (hyperTrackKey == null) {
86
			hyperTrackKey = new HypertrackKey();
27421 tejbeer 87
			hyperTrackKey.setHypertrackKeyId(hyperTrackKeyModel.getHyperTrackId());
27417 tejbeer 88
			hyperTrackKey.setDeviceId(hyperTrackKeyModel.getDeviceId());
89
		}
27422 tejbeer 90
 
27421 tejbeer 91
		hyperTrackKey.setUserId(hyperTrackKeyModel.getUserId());
27417 tejbeer 92
		hyperTrackKey.setCreatedTimestamp(LocalDateTime.now());
93
		hyperTrackKey.setUpdatedTimestamp(LocalDateTime.now());
94
		hypertrackKeyRepository.persist(hyperTrackKey);
95
		return responseSender.ok(true);
96
	}
97
 
27421 tejbeer 98
	@RequestMapping(value = "/devices/location", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
99
	public ResponseEntity<?> getLocationByKeyId(HttpServletRequest request, @RequestParam int userId,
27426 tejbeer 100
			@RequestParam int deviceId) throws IOException, MessagingException, ProfitMandiBusinessException {
27421 tejbeer 101
 
27426 tejbeer 102
		double lat1 = 28.516045882182738;
103
		double lng1 = 77.3771954997187;
27421 tejbeer 104
 
105
		HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(userId, deviceId);
27428 tejbeer 106
		// EmployeeAttendance employeeAttendance =
107
		// employeeAttendanceRepository.selectLatestPunchTimeStamp();
108
 
109
		List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKey(userId, deviceId,
110
				LocalDate.now());
27432 tejbeer 111
 
112
		LOGGER.info("hyperTrackKey" + hyperTrackKey);
113
		LOGGER.info("employeeAttendance" + employeeAttendances);
27421 tejbeer 114
		OkHttpClient client = new OkHttpClient();
115
 
116
		String authString = "Basic "
117
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
118
 
119
		Request request1 = new Request.Builder()
27426 tejbeer 120
				.url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId()).get()
27421 tejbeer 121
				.addHeader("Authorization", authString).build();
122
 
123
		Response response = client.newCall(request1).execute();
124
		JSONObject jsonObj = new JSONObject(response.body().string());
125
		JSONObject c = jsonObj.getJSONObject("location");
126
		JSONObject d = c.getJSONObject("geometry");
127
		JSONArray coords = d.getJSONArray("coordinates");
128
		double lat2 = coords.getDouble(1);
129
		double lng2 = coords.getDouble(0);
130
		double dist = distance(lat1, lng1, lat2, lng2, "m");
131
		EmployeeAttendanceModel em = new EmployeeAttendanceModel();
132
		em.setDistance(dist);
27422 tejbeer 133
		em.setLatitude(lat2);
134
		em.setLongitude(lng2);
27432 tejbeer 135
 
27428 tejbeer 136
		if (!employeeAttendances.isEmpty()) {
137
			if (employeeAttendances.get(0).getCreateTimestamp().toLocalDate().equals(LocalDate.now())) {
138
				if (employeeAttendances.get(0).getPunch().equals("punchIn")) {
139
					em.setPunchIn(true);
140
				} else {
141
					em.setPunchIn(false);
142
				}
27421 tejbeer 143
			} else {
144
				em.setPunchIn(false);
145
			}
146
		} else {
147
			em.setPunchIn(false);
148
		}
149
		return responseSender.ok(em);
150
	}
151
 
152
	private static double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
153
		if ((lat1 == lat2) && (lon1 == lon2)) {
154
			return 0;
155
		} else {
156
			double theta = lon1 - lon2;
157
			double dist = Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
158
					+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta));
159
			dist = Math.acos(dist);
160
			dist = Math.toDegrees(dist);
161
			dist = dist * 60 * 1.1515;
162
			if (unit.equals("m")) {
163
				dist = dist * 1.609344;
164
				dist = dist / 0.0010000;
165
			} else if (unit.equals("N")) {
166
				dist = dist * 0.8684;
167
			}
168
			return (dist);
169
		}
170
	}
171
 
172
	@RequestMapping(value = "/employee/attendance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
173
	@ApiImplicitParams({
174
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
175
	@ApiOperation(value = "")
176
	public ResponseEntity<?> employeeAttendance(HttpServletRequest request, @RequestParam(name = "userId") int userId,
177
			@RequestParam(name = "deviceId") int deviceId, @RequestParam(name = "punchType") PunchType punchType,
178
			@RequestParam(name = "punch") String punch) {
179
 
180
		EmployeeAttendance employeeAttendance = new EmployeeAttendance();
181
		employeeAttendance.setUserId(userId);
182
		employeeAttendance.setDeviceId(deviceId);
183
		employeeAttendance.setPunch(punch);
184
		employeeAttendance.setPunchType(punchType);
185
		employeeAttendance.setCreateTimestamp(LocalDateTime.now());
186
		employeeAttendanceRepository.persist(employeeAttendance);
187
		return responseSender.ok(true);
188
	}
189
 
27426 tejbeer 190
	@RequestMapping(value = "/create/geofence", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
191
	public ResponseEntity<?> createGreofence(HttpServletRequest request)
192
			throws IOException, ProfitMandiBusinessException {
193
 
194
		List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
195
		for (FofoStore fofoStore : fofoStores) {
196
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoStore.getId());
197
			OkHttpClient client = new OkHttpClient();
198
 
199
			okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
200
			JSONObject geofe = new JSONObject();
201
			JSONArray geofences = new JSONArray();
202
			JSONObject geometry = new JSONObject();
203
			JSONObject geo = new JSONObject();
204
			JSONArray coordinates = new JSONArray();
205
			coordinates.put(fofoStore.getLongitude());
206
			coordinates.put(fofoStore.getLatitude());
207
			geo.put("type", "Point");
208
			geo.put("coordinates", coordinates);
209
			geometry.put("geometry", geo);
210
			JSONObject metadata = new JSONObject();
211
			metadata.put("name", customRetailer.getBusinessName());
212
			metadata.put("city", customRetailer.getAddress().getCity());
213
			geometry.put("metadata", metadata);
214
			geometry.put("radius", 500);
215
 
216
			geofences.put(geometry);
217
			geofe.put("geofences", geofences);
218
			okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, geofe.toString());
219
			String authString = "Basic "
220
					+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
221
 
222
			Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences").post(body)
223
					.addHeader("Authorization", authString).build();
224
 
225
			Response response = client.newCall(request1).execute();
226
 
227
		}
228
		return responseSender.ok(true);
229
 
230
	}
231
 
27442 tejbeer 232
	@RequestMapping(value = "/device/status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
233
	@ApiImplicitParams({
234
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
235
	@ApiOperation(value = "")
236
	public ResponseEntity<?> deviceStatus(HttpServletRequest request, @RequestParam String hyperTrackKey)
237
			throws IOException {
238
		OkHttpClient client = new OkHttpClient();
239
 
240
		String authString = "Basic "
241
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
242
 
243
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey).get()
244
				.addHeader("Authorization", authString).build();
245
 
246
		Response response = client.newCall(request1).execute();
247
		return responseSender.ok(new Gson().toJson(response.body().string()));
248
 
249
	}
250
 
27417 tejbeer 251
}