Subversion Repositories SmartDukaan

Rev

Rev 27475 | Rev 27492 | 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;
27445 tejbeer 6
import java.time.LocalTime;
7
import java.time.temporal.ChronoUnit;
8
import java.util.ArrayList;
27421 tejbeer 9
import java.util.Base64;
10
import java.util.List;
27417 tejbeer 11
 
27421 tejbeer 12
import javax.mail.MessagingException;
27417 tejbeer 13
import javax.servlet.http.HttpServletRequest;
14
 
15
import org.apache.logging.log4j.LogManager;
16
import org.apache.logging.log4j.Logger;
27421 tejbeer 17
import org.json.JSONArray;
18
import org.json.JSONObject;
27417 tejbeer 19
import org.springframework.beans.factory.annotation.Autowired;
20
import org.springframework.http.MediaType;
21
import org.springframework.http.ResponseEntity;
22
import org.springframework.stereotype.Controller;
23
import org.springframework.transaction.annotation.Transactional;
24
import org.springframework.web.bind.annotation.RequestBody;
25
import org.springframework.web.bind.annotation.RequestMapping;
26
import org.springframework.web.bind.annotation.RequestMethod;
27421 tejbeer 27
import org.springframework.web.bind.annotation.RequestParam;
27417 tejbeer 28
 
29
import com.google.gson.Gson;
27421 tejbeer 30
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
27417 tejbeer 31
import com.spice.profitmandi.common.web.util.ResponseSender;
27421 tejbeer 32
import com.spice.profitmandi.dao.entity.dtr.EmployeeAttendance;
27417 tejbeer 33
import com.spice.profitmandi.dao.entity.dtr.HyperTrackKeyModel;
34
import com.spice.profitmandi.dao.entity.dtr.HypertrackKey;
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
 
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
 
27475 tejbeer 172
	@RequestMapping(value = "/getPunchHistory", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
173
	public ResponseEntity<?> getPunchHistory(HttpServletRequest request, @RequestParam int userId,
174
			@RequestParam int deviceId) {
175
 
176
		List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKey(userId, deviceId,
177
				LocalDate.now());
178
 
179
		return responseSender.ok(employeeAttendances);
180
	}
181
 
27421 tejbeer 182
	@RequestMapping(value = "/employee/attendance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
183
	@ApiImplicitParams({
184
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
185
	@ApiOperation(value = "")
186
	public ResponseEntity<?> employeeAttendance(HttpServletRequest request, @RequestParam(name = "userId") int userId,
187
			@RequestParam(name = "deviceId") int deviceId, @RequestParam(name = "punchType") PunchType punchType,
27490 tejbeer 188
			@RequestParam(name = "punch") String punch, @RequestParam(name = "time") LocalDateTime dateTime) {
27421 tejbeer 189
 
190
		EmployeeAttendance employeeAttendance = new EmployeeAttendance();
191
		employeeAttendance.setUserId(userId);
192
		employeeAttendance.setDeviceId(deviceId);
193
		employeeAttendance.setPunch(punch);
194
		employeeAttendance.setPunchType(punchType);
195
		employeeAttendance.setCreateTimestamp(LocalDateTime.now());
196
		employeeAttendanceRepository.persist(employeeAttendance);
27445 tejbeer 197
		if (punch.equals("punchOut")) {
198
			List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKeyASC(userId,
199
					deviceId, LocalDate.now());
200
			long hours = 0;
201
			long minutes = 0;
202
			long seconds = 0;
27446 tejbeer 203
			long totalSeconds = 0;
27490 tejbeer 204
			String punchTotalHour = null;
27446 tejbeer 205
			LocalTime startTime = null;
206
			LocalTime endTime = null;
207
			List<Long> hghg = new ArrayList<>();
27445 tejbeer 208
 
209
			for (EmployeeAttendance em : employeeAttendances) {
210
				if (em.getPunch().equals("punchIn")) {
27446 tejbeer 211
					startTime = em.getCreateTimestamp().toLocalTime();
27445 tejbeer 212
				} else if (em.getPunch().equals("punchOut")) {
27446 tejbeer 213
					endTime = em.getCreateTimestamp().toLocalTime();
27445 tejbeer 214
				}
215
				if (startTime != null && endTime != null) {
27446 tejbeer 216
					Long secondsBetween = ChronoUnit.SECONDS.between(startTime, endTime);
217
					totalSeconds += secondsBetween;
27445 tejbeer 218
 
219
					startTime = null;
220
					endTime = null;
221
				}
222
 
223
			}
27490 tejbeer 224
 
225
			if (employeeAttendances.get(0).getPunch().equals("punchIn")) {
226
				LocalTime punchInTime = employeeAttendances.get(0).getCreateTimestamp().toLocalTime();
227
				Long totalPunchSeconds = ChronoUnit.SECONDS.between(punchInTime, dateTime.toLocalTime());
228
				long punchHours = totalPunchSeconds / 3600;
229
				long punchMinutes = (totalPunchSeconds % 3600) / 60;
230
				long punchSeconds = totalPunchSeconds % 60;
231
				punchTotalHour = punchHours + ":" + punchMinutes + ":" + punchSeconds;
232
 
233
			}
27445 tejbeer 234
			LOGGER.info("employeeAttendance" + employeeAttendances);
235
 
27446 tejbeer 236
			hours = totalSeconds / 3600;
237
			minutes = (totalSeconds % 3600) / 60;
238
			seconds = totalSeconds % 60;
27445 tejbeer 239
			EmployeeAttendanceModel emm = new EmployeeAttendanceModel();
240
			emm.setHours(hours);
241
			emm.setMinutes(minutes);
242
			emm.setSeconds(seconds);
27490 tejbeer 243
			emm.setTotalPunchHour(punchTotalHour);
27445 tejbeer 244
			return responseSender.ok(emm);
245
 
246
		}
27421 tejbeer 247
		return responseSender.ok(true);
248
	}
249
 
27426 tejbeer 250
	@RequestMapping(value = "/create/geofence", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
27445 tejbeer 251
	public ResponseEntity<?> createGeofence(HttpServletRequest request)
27426 tejbeer 252
			throws IOException, ProfitMandiBusinessException {
253
 
27475 tejbeer 254
		/*
255
		 * List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores(); for
256
		 * (FofoStore fofoStore : fofoStores) { if (fofoStore.getLatitude() != null &&
257
		 * fofoStore.getLongitude() != null) { CustomRetailer customRetailer =
258
		 * retailerService.getFofoRetailer(fofoStore.getId());
259
		 */
260
		OkHttpClient client = new OkHttpClient();
27426 tejbeer 261
 
27475 tejbeer 262
		okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
263
		JSONObject geofe = new JSONObject();
264
		JSONArray geofences = new JSONArray();
265
		JSONObject geometry = new JSONObject();
266
		JSONObject geo = new JSONObject();
267
		JSONArray coordinates = new JSONArray();
268
		coordinates.put(77.08596155373755);
269
		coordinates.put(28.64944201113976);
270
		geo.put("type", "Point");
271
		geo.put("coordinates", coordinates);
272
		geometry.put("geometry", geo);
273
		JSONObject metadata = new JSONObject();
274
		metadata.put("name", "Test");
275
		geometry.put("radius", 500);
276
		geofences.put(geometry);
277
		geofe.put("geofences", geofences);
278
		okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, geofe.toString());
279
		String authString = "Basic "
280
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
27426 tejbeer 281
 
27475 tejbeer 282
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences").post(body)
283
				.addHeader("Authorization", authString).build();
27426 tejbeer 284
 
27475 tejbeer 285
		Response response = client.newCall(request1).execute();
286
		String geofenceId = null;
287
		JSONArray ja = new JSONArray(response.body().string());
288
		for (int i = 0; i < ja.length(); i++) {
289
			JSONObject c = ja.getJSONObject(i);
290
			geofenceId = c.getString("geofence_id");
291
		}
27426 tejbeer 292
 
27475 tejbeer 293
		LOGGER.info("response" + response.body().string());
27426 tejbeer 294
 
27475 tejbeer 295
		return responseSender.ok(geofenceId);
27426 tejbeer 296
 
297
	}
298
 
27449 tejbeer 299
	@RequestMapping(value = "/getgeofence", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
300
	public ResponseEntity<?> getAllGeofences(HttpServletRequest request)
301
			throws IOException, ProfitMandiBusinessException {
302
 
303
		OkHttpClient client = new OkHttpClient();
304
 
305
		String authString = "Basic "
306
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
307
 
308
		// Get geofences created for all app users
309
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences")
310
				.addHeader("Authorization", authString).build();
311
 
312
		Response response = client.newCall(request1).execute();
313
		return responseSender.ok(response.body().string());
314
 
315
	}
316
 
27475 tejbeer 317
	@RequestMapping(value = "/deletegeofence", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
318
	public ResponseEntity<?> deleteGeofences(HttpServletRequest request, String geofenceId)
319
			throws IOException, ProfitMandiBusinessException {
320
		OkHttpClient client = new OkHttpClient();
321
 
322
		String authString = "Basic "
323
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
324
 
325
		Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences/" + geofenceId).delete()
326
				.addHeader("Authorization", authString).build();
327
 
328
		Response response = client.newCall(request1).execute();
329
		return responseSender.ok(response.body().string());
330
 
331
	}
332
 
27417 tejbeer 333
}