Subversion Repositories SmartDukaan

Rev

Rev 30589 | 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;
27445 tejbeer 6
import java.time.LocalTime;
7
import java.time.temporal.ChronoUnit;
27421 tejbeer 8
import java.util.Base64;
9
import java.util.List;
27417 tejbeer 10
 
27421 tejbeer 11
import javax.mail.MessagingException;
27417 tejbeer 12
import javax.servlet.http.HttpServletRequest;
13
 
14
import org.apache.logging.log4j.LogManager;
15
import org.apache.logging.log4j.Logger;
27421 tejbeer 16
import org.json.JSONArray;
17
import org.json.JSONObject;
27417 tejbeer 18
import org.springframework.beans.factory.annotation.Autowired;
19
import org.springframework.http.MediaType;
20
import org.springframework.http.ResponseEntity;
21
import org.springframework.stereotype.Controller;
22
import org.springframework.transaction.annotation.Transactional;
23
import org.springframework.web.bind.annotation.RequestBody;
24
import org.springframework.web.bind.annotation.RequestMapping;
25
import org.springframework.web.bind.annotation.RequestMethod;
27421 tejbeer 26
import org.springframework.web.bind.annotation.RequestParam;
27417 tejbeer 27
 
28
import com.google.gson.Gson;
27421 tejbeer 29
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
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;
30487 tejbeer 34
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
27421 tejbeer 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;
27417 tejbeer 39
import com.spice.profitmandi.dao.repository.user.HypertrackKeyRepository;
27421 tejbeer 40
import com.spice.profitmandi.service.user.RetailerService;
27417 tejbeer 41
 
42
import io.swagger.annotations.ApiImplicitParam;
43
import io.swagger.annotations.ApiImplicitParams;
44
import io.swagger.annotations.ApiOperation;
27421 tejbeer 45
import okhttp3.OkHttpClient;
46
import okhttp3.Request;
47
import okhttp3.Response;
27417 tejbeer 48
 
49
@Controller
50
@Transactional(rollbackFor = Throwable.class)
51
public class HyperTrackController {
52
 
53
	private static final Logger LOGGER = LogManager.getLogger(HyperTrackController.class);
54
 
55
	@Autowired
56
	ResponseSender<?> responseSender;
57
 
58
	@Autowired
59
	Gson gson;
60
 
61
	@Autowired
62
	private HypertrackKeyRepository hypertrackKeyRepository;
63
 
27421 tejbeer 64
	@Autowired
65
	private EmployeeAttendanceRepository employeeAttendanceRepository;
66
 
67
	@Autowired
68
	private FofoStoreRepository fofoStoreRepository;
69
 
70
	@Autowired
71
	private RetailerService retailerService;
72
 
27417 tejbeer 73
	private static final String ACCOUNT_ID = "aZ6flHhrgPIEl18buHdPBdueEN4";
74
	private static final String SECRET_KEY = "a7rsX5B4UNNfTTx1-IJ19qdH48BT4YvBKlQJg3n3_KKNe7WWych55g";
75
 
76
	@RequestMapping(value = "/devices/hypertrackId", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
77
	@ApiImplicitParams({
78
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
79
	@ApiOperation(value = "")
80
	public ResponseEntity<?> deviceHypertrackId(HttpServletRequest request,
81
			@RequestBody HyperTrackKeyModel hyperTrackKeyModel) {
82
		HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(hyperTrackKeyModel.getUserId(),
83
				hyperTrackKeyModel.getDeviceId());
84
		if (hyperTrackKey == null) {
85
			hyperTrackKey = new HypertrackKey();
27444 tejbeer 86
			hyperTrackKey.setUserId(hyperTrackKeyModel.getUserId());
87
			hyperTrackKey.setCreatedTimestamp(LocalDateTime.now());
27417 tejbeer 88
			hyperTrackKey.setDeviceId(hyperTrackKeyModel.getDeviceId());
89
		}
27422 tejbeer 90
 
27444 tejbeer 91
		hyperTrackKey.setHypertrackKeyId(hyperTrackKeyModel.getHyperTrackId());
92
 
27417 tejbeer 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
 
27781 amit.gupta 102
		LOGGER.info("UserId -> {}, Device Id -> {}", userId, deviceId);
27426 tejbeer 103
		double lat1 = 28.516045882182738;
104
		double lng1 = 77.3771954997187;
27421 tejbeer 105
 
106
		HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(userId, deviceId);
27428 tejbeer 107
 
108
		List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKey(userId, deviceId,
109
				LocalDate.now());
28112 tejbeer 110
		EmployeeAttendanceModel em = null;
27432 tejbeer 111
		LOGGER.info("hyperTrackKey" + hyperTrackKey);
112
		LOGGER.info("employeeAttendance" + employeeAttendances);
27421 tejbeer 113
		OkHttpClient client = new OkHttpClient();
114
 
115
		String authString = "Basic "
116
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
117
 
118
		Request request1 = new Request.Builder()
27426 tejbeer 119
				.url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId()).get()
27421 tejbeer 120
				.addHeader("Authorization", authString).build();
121
 
122
		Response response = client.newCall(request1).execute();
28112 tejbeer 123
 
27421 tejbeer 124
		JSONObject jsonObj = new JSONObject(response.body().string());
27498 tejbeer 125
 
126
		JSONObject deviceStatus = jsonObj.getJSONObject("device_status");
27502 tejbeer 127
		String status = deviceStatus.getString("value");
27498 tejbeer 128
 
28113 tejbeer 129
		if (status.equals("inactive") || status.equals("disconnected")) {
27432 tejbeer 130
 
28113 tejbeer 131
			LOGGER.info("status" + status);
28114 tejbeer 132
			okhttp3.RequestBody reqbody = okhttp3.RequestBody.create(null, new byte[0]);
28113 tejbeer 133
 
28112 tejbeer 134
			Request request2 = new Request.Builder()
135
					.url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId() + "/start")
28114 tejbeer 136
					.post(reqbody).addHeader("Authorization", authString).build();
28112 tejbeer 137
 
138
			Response resp = client.newCall(request2).execute();
28113 tejbeer 139
			LOGGER.info("resp" + resp);
28116 tejbeer 140
			em = new EmployeeAttendanceModel();
141
			em.setPunchIn(false);
28123 tejbeer 142
			em.setDeviceStatus(status);
28113 tejbeer 143
		} else if (status.equals("active")) {
28112 tejbeer 144
			JSONObject c = jsonObj.getJSONObject("location");
145
			JSONObject d = c.getJSONObject("geometry");
146
			JSONArray coords = d.getJSONArray("coordinates");
147
 
148
			double lat2 = coords.getDouble(1);
149
			double lng2 = coords.getDouble(0);
150
			double dist = distance(lat1, lng1, lat2, lng2, "m");
151
			LOGGER.info("jsonObj" + jsonObj);
152
			JSONObject deviceData = deviceStatus.getJSONObject("data");
28122 tejbeer 153
			LOGGER.info("status1" + status);
28112 tejbeer 154
 
155
			em = new EmployeeAttendanceModel();
156
			em.setDistance(dist);
157
			em.setLatitude(lat2);
158
			em.setLongitude(lng2);
159
			em.setDeviceStatus(status);
160
 
161
			if (!employeeAttendances.isEmpty()) {
162
				if (employeeAttendances.get(0).getCreateTimestamp().toLocalDate().equals(LocalDate.now())) {
163
					if (employeeAttendances.get(0).getPunch().equals("punchIn")) {
164
						em.setPunchIn(true);
165
					} else {
166
						em.setPunchIn(false);
167
					}
27428 tejbeer 168
				} else {
169
					em.setPunchIn(false);
170
				}
28112 tejbeer 171
 
172
				if (employeeAttendances.get(0).getPunch().equals("punchOut")) {
173
					LocalTime startTime = employeeAttendances.get(employeeAttendances.size() - 1).getCreateTimestamp()
174
							.toLocalTime();
175
					Long secondsBetween = ChronoUnit.SECONDS.between(startTime,
176
							employeeAttendances.get(0).getCreateTimestamp().toLocalTime());
177
					long hours = secondsBetween / 3600;
178
					long minutes = (secondsBetween % 3600) / 60;
179
					long seconds = secondsBetween % 60;
180
					em.setPunchHours(hours);
181
					em.setPunchMinutes(minutes);
182
					em.setPunchSeconds(seconds);
183
 
184
				} else if (employeeAttendances.get(employeeAttendances.size() - 1).getPunch().equals("punchIn")) {
185
					LocalTime startTime = employeeAttendances.get(employeeAttendances.size() - 1).getCreateTimestamp()
186
							.toLocalTime();
187
					Long secondsBetween = ChronoUnit.SECONDS.between(startTime, LocalDateTime.now().toLocalTime());
188
					long hours = secondsBetween / 3600;
189
					long minutes = (secondsBetween % 3600) / 60;
190
					long seconds = secondsBetween % 60;
191
					em.setPunchHours(hours);
192
					em.setPunchMinutes(minutes);
193
					em.setPunchSeconds(seconds);
194
				}
195
 
27421 tejbeer 196
			} else {
197
				em.setPunchIn(false);
28123 tejbeer 198
				em.setDeviceStatus(status);
27421 tejbeer 199
			}
28122 tejbeer 200
		} else {
201
 
202
			LOGGER.info("status3" + status);
203
 
204
			em.setPunchIn(false);
28123 tejbeer 205
			em.setDeviceStatus(status);
27421 tejbeer 206
		}
207
		return responseSender.ok(em);
208
	}
209
 
210
	private static double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
211
		if ((lat1 == lat2) && (lon1 == lon2)) {
212
			return 0;
213
		} else {
214
			double theta = lon1 - lon2;
215
			double dist = Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
216
					+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta));
217
			dist = Math.acos(dist);
218
			dist = Math.toDegrees(dist);
219
			dist = dist * 60 * 1.1515;
220
			if (unit.equals("m")) {
221
				dist = dist * 1.609344;
222
				dist = dist / 0.0010000;
223
			} else if (unit.equals("N")) {
224
				dist = dist * 0.8684;
225
			}
226
			return (dist);
227
		}
228
	}
229
 
27475 tejbeer 230
	@RequestMapping(value = "/getPunchHistory", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
231
	public ResponseEntity<?> getPunchHistory(HttpServletRequest request, @RequestParam int userId,
232
			@RequestParam int deviceId) {
233
 
234
		List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKey(userId, deviceId,
235
				LocalDate.now());
236
 
237
		return responseSender.ok(employeeAttendances);
238
	}
239
 
27421 tejbeer 240
	@RequestMapping(value = "/employee/attendance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
241
	@ApiImplicitParams({
242
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
243
	@ApiOperation(value = "")
244
	public ResponseEntity<?> employeeAttendance(HttpServletRequest request, @RequestParam(name = "userId") int userId,
245
			@RequestParam(name = "deviceId") int deviceId, @RequestParam(name = "punchType") PunchType punchType,
27493 tejbeer 246
			@RequestParam(name = "punch") String punch) {
27421 tejbeer 247
 
248
		EmployeeAttendance employeeAttendance = new EmployeeAttendance();
249
		employeeAttendance.setUserId(userId);
250
		employeeAttendance.setDeviceId(deviceId);
251
		employeeAttendance.setPunch(punch);
252
		employeeAttendance.setPunchType(punchType);
253
		employeeAttendance.setCreateTimestamp(LocalDateTime.now());
254
		employeeAttendanceRepository.persist(employeeAttendance);
27445 tejbeer 255
		if (punch.equals("punchOut")) {
256
			List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKeyASC(userId,
257
					deviceId, LocalDate.now());
258
			long hours = 0;
259
			long minutes = 0;
260
			long seconds = 0;
27446 tejbeer 261
			long totalSeconds = 0;
262
			LocalTime startTime = null;
263
			LocalTime endTime = null;
27445 tejbeer 264
 
265
			for (EmployeeAttendance em : employeeAttendances) {
266
				if (em.getPunch().equals("punchIn")) {
27446 tejbeer 267
					startTime = em.getCreateTimestamp().toLocalTime();
27445 tejbeer 268
				} else if (em.getPunch().equals("punchOut")) {
27446 tejbeer 269
					endTime = em.getCreateTimestamp().toLocalTime();
27445 tejbeer 270
				}
271
				if (startTime != null && endTime != null) {
27446 tejbeer 272
					Long secondsBetween = ChronoUnit.SECONDS.between(startTime, endTime);
273
					totalSeconds += secondsBetween;
27445 tejbeer 274
					startTime = null;
275
					endTime = null;
276
				}
277
 
278
			}
27446 tejbeer 279
			hours = totalSeconds / 3600;
280
			minutes = (totalSeconds % 3600) / 60;
281
			seconds = totalSeconds % 60;
27445 tejbeer 282
			EmployeeAttendanceModel emm = new EmployeeAttendanceModel();
283
			emm.setHours(hours);
284
			emm.setMinutes(minutes);
285
			emm.setSeconds(seconds);
286
			return responseSender.ok(emm);
287
 
288
		}
27421 tejbeer 289
		return responseSender.ok(true);
290
	}
291
 
27426 tejbeer 292
	@RequestMapping(value = "/create/geofence", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
27445 tejbeer 293
	public ResponseEntity<?> createGeofence(HttpServletRequest request)
27426 tejbeer 294
			throws IOException, ProfitMandiBusinessException {
295
 
27475 tejbeer 296
		/*
297
		 * List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores(); for
298
		 * (FofoStore fofoStore : fofoStores) { if (fofoStore.getLatitude() != null &&
299
		 * fofoStore.getLongitude() != null) { CustomRetailer customRetailer =
300
		 * retailerService.getFofoRetailer(fofoStore.getId());
301
		 */
302
		OkHttpClient client = new OkHttpClient();
27426 tejbeer 303
 
27475 tejbeer 304
		okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
305
		JSONObject geofe = new JSONObject();
306
		JSONArray geofences = new JSONArray();
307
		JSONObject geometry = new JSONObject();
308
		JSONObject geo = new JSONObject();
309
		JSONArray coordinates = new JSONArray();
310
		coordinates.put(77.08596155373755);
311
		coordinates.put(28.64944201113976);
312
		geo.put("type", "Point");
313
		geo.put("coordinates", coordinates);
314
		geometry.put("geometry", geo);
315
		JSONObject metadata = new JSONObject();
316
		metadata.put("name", "Test");
317
		geometry.put("radius", 500);
318
		geofences.put(geometry);
319
		geofe.put("geofences", geofences);
320
		okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, geofe.toString());
321
		String authString = "Basic "
322
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
27426 tejbeer 323
 
27475 tejbeer 324
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences").post(body)
325
				.addHeader("Authorization", authString).build();
27426 tejbeer 326
 
27475 tejbeer 327
		Response response = client.newCall(request1).execute();
328
		String geofenceId = null;
329
		JSONArray ja = new JSONArray(response.body().string());
330
		for (int i = 0; i < ja.length(); i++) {
331
			JSONObject c = ja.getJSONObject(i);
332
			geofenceId = c.getString("geofence_id");
333
		}
27426 tejbeer 334
 
27475 tejbeer 335
		LOGGER.info("response" + response.body().string());
27426 tejbeer 336
 
27475 tejbeer 337
		return responseSender.ok(geofenceId);
27426 tejbeer 338
 
339
	}
340
 
27449 tejbeer 341
	@RequestMapping(value = "/getgeofence", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
342
	public ResponseEntity<?> getAllGeofences(HttpServletRequest request)
343
			throws IOException, ProfitMandiBusinessException {
344
 
345
		OkHttpClient client = new OkHttpClient();
346
 
347
		String authString = "Basic "
348
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
349
 
350
		// Get geofences created for all app users
351
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences")
352
				.addHeader("Authorization", authString).build();
353
 
354
		Response response = client.newCall(request1).execute();
355
		return responseSender.ok(response.body().string());
356
 
357
	}
358
 
27475 tejbeer 359
	@RequestMapping(value = "/deletegeofence", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
360
	public ResponseEntity<?> deleteGeofences(HttpServletRequest request, String geofenceId)
361
			throws IOException, ProfitMandiBusinessException {
362
		OkHttpClient client = new OkHttpClient();
363
 
364
		String authString = "Basic "
365
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
366
 
367
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences/" + geofenceId).delete()
368
				.addHeader("Authorization", authString).build();
369
 
370
		Response response = client.newCall(request1).execute();
371
		return responseSender.ok(response.body().string());
372
 
373
	}
374
 
30487 tejbeer 375
	@RequestMapping(value = "/devices/partner/location", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
376
	public ResponseEntity<?> getPartnerLocationByKeyId(HttpServletRequest request, @RequestParam int userId,
377
			@RequestParam int deviceId, @RequestParam int fofoId)
378
			throws IOException, MessagingException, ProfitMandiBusinessException {
379
 
380
		LOGGER.info("UserId -> {}, Device Id -> {}", userId, deviceId);
381
		FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
30590 tejbeer 382
 
383
		LOGGER.info("fs{}", fs);
30533 tejbeer 384
		Double dist = null;
30487 tejbeer 385
		HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(userId, deviceId);
386
 
30529 tejbeer 387
		LOGGER.info("hyperTrackKey {}" + hyperTrackKey);
30487 tejbeer 388
		OkHttpClient client = new OkHttpClient();
389
 
390
		String authString = "Basic "
391
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
392
 
393
		Request request1 = new Request.Builder()
394
				.url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId()).get()
395
				.addHeader("Authorization", authString).build();
396
 
397
		Response response = client.newCall(request1).execute();
398
 
399
		JSONObject jsonObj = new JSONObject(response.body().string());
400
 
30490 tejbeer 401
		LOGGER.info("jsonObj" + jsonObj);
30487 tejbeer 402
		JSONObject deviceStatus = jsonObj.getJSONObject("device_status");
403
		String status = deviceStatus.getString("value");
404
 
405
		if (status.equals("inactive") || status.equals("disconnected")) {
406
 
407
			LOGGER.info("status" + status);
408
			okhttp3.RequestBody reqbody = okhttp3.RequestBody.create(null, new byte[0]);
409
 
410
			Request request2 = new Request.Builder()
411
					.url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId() + "/start")
412
					.post(reqbody).addHeader("Authorization", authString).build();
413
 
414
			Response resp = client.newCall(request2).execute();
415
			LOGGER.info("resp" + resp);
416
 
417
		} else if (status.equals("active")) {
418
			JSONObject c = jsonObj.getJSONObject("location");
419
			JSONObject d = c.getJSONObject("geometry");
420
			JSONArray coords = d.getJSONArray("coordinates");
421
 
422
			double lat2 = coords.getDouble(1);
423
			double lng2 = coords.getDouble(0);
30498 tejbeer 424
			dist = distance(Float.valueOf(fs.getLatitude()), Float.valueOf(fs.getLongitude()), lat2, lng2, "m");
30487 tejbeer 425
 
30498 tejbeer 426
			// dist = distance(lat1, lng1, lat2, lng2, "m");
30487 tejbeer 427
			LOGGER.info("jsonObj" + jsonObj);
30589 tejbeer 428
 
429
			LOGGER.info("dist" + dist);
30487 tejbeer 430
			JSONObject deviceData = deviceStatus.getJSONObject("data");
431
			LOGGER.info("status1" + status);
432
 
433
		}
434
		return responseSender.ok(dist);
435
	}
436
 
27417 tejbeer 437
}