Subversion Repositories SmartDukaan

Rev

Rev 30590 | 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;
36418 amit 30
import com.spice.profitmandi.common.web.client.HttpClientFactory;
31
import com.spice.profitmandi.common.web.client.RestClient;
27417 tejbeer 32
import com.spice.profitmandi.common.web.util.ResponseSender;
27421 tejbeer 33
import com.spice.profitmandi.dao.entity.dtr.EmployeeAttendance;
27417 tejbeer 34
import com.spice.profitmandi.dao.entity.dtr.HyperTrackKeyModel;
35
import com.spice.profitmandi.dao.entity.dtr.HypertrackKey;
30487 tejbeer 36
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
27421 tejbeer 37
import com.spice.profitmandi.dao.enumuration.dtr.PunchType;
38
import com.spice.profitmandi.dao.model.EmployeeAttendanceModel;
39
import com.spice.profitmandi.dao.repository.dtr.EmployeeAttendanceRepository;
40
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
27417 tejbeer 41
import com.spice.profitmandi.dao.repository.user.HypertrackKeyRepository;
27421 tejbeer 42
import com.spice.profitmandi.service.user.RetailerService;
27417 tejbeer 43
 
44
import io.swagger.annotations.ApiImplicitParam;
45
import io.swagger.annotations.ApiImplicitParams;
46
import io.swagger.annotations.ApiOperation;
36418 amit 47
import org.apache.http.client.methods.CloseableHttpResponse;
48
import org.apache.http.client.methods.HttpDelete;
49
import org.apache.http.impl.client.CloseableHttpClient;
50
import org.apache.http.util.EntityUtils;
27417 tejbeer 51
 
36418 amit 52
import java.util.Collections;
53
import java.util.Map;
54
 
27417 tejbeer 55
@Controller
56
public class HyperTrackController {
57
 
58
	private static final Logger LOGGER = LogManager.getLogger(HyperTrackController.class);
59
 
60
	@Autowired
61
	ResponseSender<?> responseSender;
62
 
63
	@Autowired
64
	Gson gson;
65
 
66
	@Autowired
67
	private HypertrackKeyRepository hypertrackKeyRepository;
68
 
27421 tejbeer 69
	@Autowired
70
	private EmployeeAttendanceRepository employeeAttendanceRepository;
71
 
72
	@Autowired
73
	private FofoStoreRepository fofoStoreRepository;
74
 
75
	@Autowired
76
	private RetailerService retailerService;
77
 
36418 amit 78
	@Autowired
79
	private RestClient restClient;
80
 
81
	@Autowired
82
	private HyperTrackService hyperTrackService;
83
 
27417 tejbeer 84
	private static final String ACCOUNT_ID = "aZ6flHhrgPIEl18buHdPBdueEN4";
85
	private static final String SECRET_KEY = "a7rsX5B4UNNfTTx1-IJ19qdH48BT4YvBKlQJg3n3_KKNe7WWych55g";
86
 
36418 amit 87
	private Map<String, String> hypertrackAuthHeader() {
88
		String authString = "Basic "
89
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
90
		return Collections.singletonMap("Authorization", authString);
91
	}
92
 
27417 tejbeer 93
	@RequestMapping(value = "/devices/hypertrackId", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
94
	@ApiImplicitParams({
95
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
96
	@ApiOperation(value = "")
36418 amit 97
	@Transactional
27417 tejbeer 98
	public ResponseEntity<?> deviceHypertrackId(HttpServletRequest request,
99
			@RequestBody HyperTrackKeyModel hyperTrackKeyModel) {
100
		HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(hyperTrackKeyModel.getUserId(),
101
				hyperTrackKeyModel.getDeviceId());
102
		if (hyperTrackKey == null) {
103
			hyperTrackKey = new HypertrackKey();
27444 tejbeer 104
			hyperTrackKey.setUserId(hyperTrackKeyModel.getUserId());
105
			hyperTrackKey.setCreatedTimestamp(LocalDateTime.now());
27417 tejbeer 106
			hyperTrackKey.setDeviceId(hyperTrackKeyModel.getDeviceId());
107
		}
27422 tejbeer 108
 
27444 tejbeer 109
		hyperTrackKey.setHypertrackKeyId(hyperTrackKeyModel.getHyperTrackId());
110
 
27417 tejbeer 111
		hyperTrackKey.setUpdatedTimestamp(LocalDateTime.now());
112
		hypertrackKeyRepository.persist(hyperTrackKey);
113
		return responseSender.ok(true);
114
	}
115
 
27421 tejbeer 116
	@RequestMapping(value = "/devices/location", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
117
	public ResponseEntity<?> getLocationByKeyId(HttpServletRequest request, @RequestParam int userId,
27426 tejbeer 118
			@RequestParam int deviceId) throws IOException, MessagingException, ProfitMandiBusinessException {
27421 tejbeer 119
 
27781 amit.gupta 120
		LOGGER.info("UserId -> {}, Device Id -> {}", userId, deviceId);
27426 tejbeer 121
		double lat1 = 28.516045882182738;
122
		double lng1 = 77.3771954997187;
27421 tejbeer 123
 
36418 amit 124
		// Read-only tx in the service: connection released before the external HTTP call below.
125
		HyperTrackService.LocationContext ctx = hyperTrackService.loadLocationContext(userId, deviceId);
126
		HypertrackKey hyperTrackKey = ctx.hypertrackKey;
127
		List<EmployeeAttendance> employeeAttendances = ctx.employeeAttendances;
28112 tejbeer 128
		EmployeeAttendanceModel em = null;
27432 tejbeer 129
		LOGGER.info("hyperTrackKey" + hyperTrackKey);
130
		LOGGER.info("employeeAttendance" + employeeAttendances);
36418 amit 131
		String responseBody = restClient.get(
132
				"https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId(),
133
				null, hypertrackAuthHeader());
134
		JSONObject jsonObj = new JSONObject(responseBody);
27421 tejbeer 135
 
27498 tejbeer 136
		JSONObject deviceStatus = jsonObj.getJSONObject("device_status");
27502 tejbeer 137
		String status = deviceStatus.getString("value");
27498 tejbeer 138
 
28113 tejbeer 139
		if (status.equals("inactive") || status.equals("disconnected")) {
27432 tejbeer 140
 
28113 tejbeer 141
			LOGGER.info("status" + status);
36418 amit 142
			String startResp = restClient.post(
143
					"https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId() + "/start",
144
					"", hypertrackAuthHeader());
145
			LOGGER.info("resp" + startResp);
28116 tejbeer 146
			em = new EmployeeAttendanceModel();
147
			em.setPunchIn(false);
28123 tejbeer 148
			em.setDeviceStatus(status);
28113 tejbeer 149
		} else if (status.equals("active")) {
28112 tejbeer 150
			JSONObject c = jsonObj.getJSONObject("location");
151
			JSONObject d = c.getJSONObject("geometry");
152
			JSONArray coords = d.getJSONArray("coordinates");
153
 
154
			double lat2 = coords.getDouble(1);
155
			double lng2 = coords.getDouble(0);
156
			double dist = distance(lat1, lng1, lat2, lng2, "m");
157
			LOGGER.info("jsonObj" + jsonObj);
158
			JSONObject deviceData = deviceStatus.getJSONObject("data");
28122 tejbeer 159
			LOGGER.info("status1" + status);
28112 tejbeer 160
 
161
			em = new EmployeeAttendanceModel();
162
			em.setDistance(dist);
163
			em.setLatitude(lat2);
164
			em.setLongitude(lng2);
165
			em.setDeviceStatus(status);
166
 
167
			if (!employeeAttendances.isEmpty()) {
168
				if (employeeAttendances.get(0).getCreateTimestamp().toLocalDate().equals(LocalDate.now())) {
169
					if (employeeAttendances.get(0).getPunch().equals("punchIn")) {
170
						em.setPunchIn(true);
171
					} else {
172
						em.setPunchIn(false);
173
					}
27428 tejbeer 174
				} else {
175
					em.setPunchIn(false);
176
				}
28112 tejbeer 177
 
178
				if (employeeAttendances.get(0).getPunch().equals("punchOut")) {
179
					LocalTime startTime = employeeAttendances.get(employeeAttendances.size() - 1).getCreateTimestamp()
180
							.toLocalTime();
181
					Long secondsBetween = ChronoUnit.SECONDS.between(startTime,
182
							employeeAttendances.get(0).getCreateTimestamp().toLocalTime());
183
					long hours = secondsBetween / 3600;
184
					long minutes = (secondsBetween % 3600) / 60;
185
					long seconds = secondsBetween % 60;
186
					em.setPunchHours(hours);
187
					em.setPunchMinutes(minutes);
188
					em.setPunchSeconds(seconds);
189
 
190
				} else if (employeeAttendances.get(employeeAttendances.size() - 1).getPunch().equals("punchIn")) {
191
					LocalTime startTime = employeeAttendances.get(employeeAttendances.size() - 1).getCreateTimestamp()
192
							.toLocalTime();
193
					Long secondsBetween = ChronoUnit.SECONDS.between(startTime, LocalDateTime.now().toLocalTime());
194
					long hours = secondsBetween / 3600;
195
					long minutes = (secondsBetween % 3600) / 60;
196
					long seconds = secondsBetween % 60;
197
					em.setPunchHours(hours);
198
					em.setPunchMinutes(minutes);
199
					em.setPunchSeconds(seconds);
200
				}
201
 
27421 tejbeer 202
			} else {
203
				em.setPunchIn(false);
28123 tejbeer 204
				em.setDeviceStatus(status);
27421 tejbeer 205
			}
28122 tejbeer 206
		} else {
207
 
208
			LOGGER.info("status3" + status);
209
 
210
			em.setPunchIn(false);
28123 tejbeer 211
			em.setDeviceStatus(status);
27421 tejbeer 212
		}
213
		return responseSender.ok(em);
214
	}
215
 
216
	private static double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
217
		if ((lat1 == lat2) && (lon1 == lon2)) {
218
			return 0;
219
		} else {
220
			double theta = lon1 - lon2;
221
			double dist = Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
222
					+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta));
223
			dist = Math.acos(dist);
224
			dist = Math.toDegrees(dist);
225
			dist = dist * 60 * 1.1515;
226
			if (unit.equals("m")) {
227
				dist = dist * 1.609344;
228
				dist = dist / 0.0010000;
229
			} else if (unit.equals("N")) {
230
				dist = dist * 0.8684;
231
			}
232
			return (dist);
233
		}
234
	}
235
 
27475 tejbeer 236
	@RequestMapping(value = "/getPunchHistory", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
36418 amit 237
	@Transactional(readOnly = true)
27475 tejbeer 238
	public ResponseEntity<?> getPunchHistory(HttpServletRequest request, @RequestParam int userId,
239
			@RequestParam int deviceId) {
240
 
241
		List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKey(userId, deviceId,
242
				LocalDate.now());
243
 
244
		return responseSender.ok(employeeAttendances);
245
	}
246
 
27421 tejbeer 247
	@RequestMapping(value = "/employee/attendance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
248
	@ApiImplicitParams({
249
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
250
	@ApiOperation(value = "")
36418 amit 251
	@Transactional
27421 tejbeer 252
	public ResponseEntity<?> employeeAttendance(HttpServletRequest request, @RequestParam(name = "userId") int userId,
253
			@RequestParam(name = "deviceId") int deviceId, @RequestParam(name = "punchType") PunchType punchType,
27493 tejbeer 254
			@RequestParam(name = "punch") String punch) {
27421 tejbeer 255
 
256
		EmployeeAttendance employeeAttendance = new EmployeeAttendance();
257
		employeeAttendance.setUserId(userId);
258
		employeeAttendance.setDeviceId(deviceId);
259
		employeeAttendance.setPunch(punch);
260
		employeeAttendance.setPunchType(punchType);
261
		employeeAttendance.setCreateTimestamp(LocalDateTime.now());
262
		employeeAttendanceRepository.persist(employeeAttendance);
27445 tejbeer 263
		if (punch.equals("punchOut")) {
264
			List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKeyASC(userId,
265
					deviceId, LocalDate.now());
266
			long hours = 0;
267
			long minutes = 0;
268
			long seconds = 0;
27446 tejbeer 269
			long totalSeconds = 0;
270
			LocalTime startTime = null;
271
			LocalTime endTime = null;
27445 tejbeer 272
 
273
			for (EmployeeAttendance em : employeeAttendances) {
274
				if (em.getPunch().equals("punchIn")) {
27446 tejbeer 275
					startTime = em.getCreateTimestamp().toLocalTime();
27445 tejbeer 276
				} else if (em.getPunch().equals("punchOut")) {
27446 tejbeer 277
					endTime = em.getCreateTimestamp().toLocalTime();
27445 tejbeer 278
				}
279
				if (startTime != null && endTime != null) {
27446 tejbeer 280
					Long secondsBetween = ChronoUnit.SECONDS.between(startTime, endTime);
281
					totalSeconds += secondsBetween;
27445 tejbeer 282
					startTime = null;
283
					endTime = null;
284
				}
285
 
286
			}
27446 tejbeer 287
			hours = totalSeconds / 3600;
288
			minutes = (totalSeconds % 3600) / 60;
289
			seconds = totalSeconds % 60;
27445 tejbeer 290
			EmployeeAttendanceModel emm = new EmployeeAttendanceModel();
291
			emm.setHours(hours);
292
			emm.setMinutes(minutes);
293
			emm.setSeconds(seconds);
294
			return responseSender.ok(emm);
295
 
296
		}
27421 tejbeer 297
		return responseSender.ok(true);
298
	}
299
 
27426 tejbeer 300
	@RequestMapping(value = "/create/geofence", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
27445 tejbeer 301
	public ResponseEntity<?> createGeofence(HttpServletRequest request)
27426 tejbeer 302
			throws IOException, ProfitMandiBusinessException {
303
 
27475 tejbeer 304
		/*
305
		 * List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores(); for
306
		 * (FofoStore fofoStore : fofoStores) { if (fofoStore.getLatitude() != null &&
307
		 * fofoStore.getLongitude() != null) { CustomRetailer customRetailer =
308
		 * retailerService.getFofoRetailer(fofoStore.getId());
309
		 */
310
		JSONObject geofe = new JSONObject();
311
		JSONArray geofences = new JSONArray();
312
		JSONObject geometry = new JSONObject();
313
		JSONObject geo = new JSONObject();
314
		JSONArray coordinates = new JSONArray();
315
		coordinates.put(77.08596155373755);
316
		coordinates.put(28.64944201113976);
317
		geo.put("type", "Point");
318
		geo.put("coordinates", coordinates);
319
		geometry.put("geometry", geo);
320
		JSONObject metadata = new JSONObject();
321
		metadata.put("name", "Test");
322
		geometry.put("radius", 500);
323
		geofences.put(geometry);
324
		geofe.put("geofences", geofences);
27426 tejbeer 325
 
36418 amit 326
		String responseBody = restClient.postJson("https://v3.api.hypertrack.com/geofences",
327
				geofe.toString(), hypertrackAuthHeader());
27475 tejbeer 328
		String geofenceId = null;
36418 amit 329
		JSONArray ja = new JSONArray(responseBody);
27475 tejbeer 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
 
36418 amit 335
		LOGGER.info("response" + responseBody);
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 {
36418 amit 344
		String body = restClient.get("https://v3.api.hypertrack.com/geofences", null, hypertrackAuthHeader());
345
		return responseSender.ok(body);
27449 tejbeer 346
	}
347
 
27475 tejbeer 348
	@RequestMapping(value = "/deletegeofence", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
349
	public ResponseEntity<?> deleteGeofences(HttpServletRequest request, String geofenceId)
350
			throws IOException, ProfitMandiBusinessException {
36418 amit 351
		HttpDelete delete = new HttpDelete("https://v3.api.hypertrack.com/geofences/" + geofenceId);
352
		hypertrackAuthHeader().forEach(delete::setHeader);
353
		try (CloseableHttpClient client = HttpClientFactory.apacheHttp();
354
		     CloseableHttpResponse response = client.execute(delete)) {
355
			String body = response.getEntity() != null ? EntityUtils.toString(response.getEntity()) : "";
356
			return responseSender.ok(body);
357
		}
27475 tejbeer 358
	}
359
 
30487 tejbeer 360
	@RequestMapping(value = "/devices/partner/location", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
361
	public ResponseEntity<?> getPartnerLocationByKeyId(HttpServletRequest request, @RequestParam int userId,
362
			@RequestParam int deviceId, @RequestParam int fofoId)
363
			throws IOException, MessagingException, ProfitMandiBusinessException {
364
 
365
		LOGGER.info("UserId -> {}, Device Id -> {}", userId, deviceId);
36418 amit 366
		// Read-only tx in service: connection released before the external HTTP call below.
367
		HyperTrackService.PartnerLocationContext ctx = hyperTrackService.loadPartnerLocationContext(userId, deviceId, fofoId);
368
		FofoStore fs = ctx.fofoStore;
30590 tejbeer 369
		LOGGER.info("fs{}", fs);
30533 tejbeer 370
		Double dist = null;
36418 amit 371
		HypertrackKey hyperTrackKey = ctx.hypertrackKey;
30529 tejbeer 372
		LOGGER.info("hyperTrackKey {}" + hyperTrackKey);
36418 amit 373
		String responseBody = restClient.get(
374
				"https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId(),
375
				null, hypertrackAuthHeader());
376
		JSONObject jsonObj = new JSONObject(responseBody);
30487 tejbeer 377
 
30490 tejbeer 378
		LOGGER.info("jsonObj" + jsonObj);
30487 tejbeer 379
		JSONObject deviceStatus = jsonObj.getJSONObject("device_status");
380
		String status = deviceStatus.getString("value");
381
 
382
		if (status.equals("inactive") || status.equals("disconnected")) {
383
 
384
			LOGGER.info("status" + status);
36418 amit 385
			String startResp = restClient.post(
386
					"https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId() + "/start",
387
					"", hypertrackAuthHeader());
388
			LOGGER.info("resp" + startResp);
30487 tejbeer 389
 
390
		} else if (status.equals("active")) {
391
			JSONObject c = jsonObj.getJSONObject("location");
392
			JSONObject d = c.getJSONObject("geometry");
393
			JSONArray coords = d.getJSONArray("coordinates");
394
 
395
			double lat2 = coords.getDouble(1);
396
			double lng2 = coords.getDouble(0);
30498 tejbeer 397
			dist = distance(Float.valueOf(fs.getLatitude()), Float.valueOf(fs.getLongitude()), lat2, lng2, "m");
30487 tejbeer 398
 
30498 tejbeer 399
			// dist = distance(lat1, lng1, lat2, lng2, "m");
30487 tejbeer 400
			LOGGER.info("jsonObj" + jsonObj);
30589 tejbeer 401
 
402
			LOGGER.info("dist" + dist);
30487 tejbeer 403
			JSONObject deviceData = deviceStatus.getJSONObject("data");
404
			LOGGER.info("status1" + status);
405
 
406
		}
407
		return responseSender.ok(dist);
408
	}
409
 
27417 tejbeer 410
}