Subversion Repositories SmartDukaan

Rev

Rev 27444 | Rev 27446 | 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.apache.velocity.app.VelocityEngine;
18
import org.json.JSONArray;
19
import org.json.JSONObject;
27417 tejbeer 20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.http.MediaType;
22
import org.springframework.http.ResponseEntity;
23
import org.springframework.stereotype.Controller;
24
import org.springframework.transaction.annotation.Transactional;
25
import org.springframework.web.bind.annotation.RequestBody;
26
import org.springframework.web.bind.annotation.RequestMapping;
27
import org.springframework.web.bind.annotation.RequestMethod;
27421 tejbeer 28
import org.springframework.web.bind.annotation.RequestParam;
27417 tejbeer 29
 
30
import com.google.gson.Gson;
27445 tejbeer 31
import com.ibm.icu.impl.duration.Period;
27421 tejbeer 32
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
33
import com.spice.profitmandi.common.model.CustomRetailer;
27417 tejbeer 34
import com.spice.profitmandi.common.web.util.ResponseSender;
27421 tejbeer 35
import com.spice.profitmandi.dao.entity.dtr.EmployeeAttendance;
27417 tejbeer 36
import com.spice.profitmandi.dao.entity.dtr.HyperTrackKeyModel;
37
import com.spice.profitmandi.dao.entity.dtr.HypertrackKey;
27421 tejbeer 38
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
39
import com.spice.profitmandi.dao.enumuration.dtr.PunchType;
40
import com.spice.profitmandi.dao.model.EmployeeAttendanceModel;
41
import com.spice.profitmandi.dao.repository.dtr.EmployeeAttendanceRepository;
42
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
43
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
27417 tejbeer 44
import com.spice.profitmandi.dao.repository.user.HypertrackKeyRepository;
27421 tejbeer 45
import com.spice.profitmandi.service.user.RetailerService;
27417 tejbeer 46
 
47
import io.swagger.annotations.ApiImplicitParam;
48
import io.swagger.annotations.ApiImplicitParams;
49
import io.swagger.annotations.ApiOperation;
27421 tejbeer 50
import okhttp3.OkHttpClient;
51
import okhttp3.Request;
52
import okhttp3.Response;
27417 tejbeer 53
 
54
@Controller
55
@Transactional(rollbackFor = Throwable.class)
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
 
27417 tejbeer 78
	private static final String ACCOUNT_ID = "aZ6flHhrgPIEl18buHdPBdueEN4";
79
	private static final String SECRET_KEY = "a7rsX5B4UNNfTTx1-IJ19qdH48BT4YvBKlQJg3n3_KKNe7WWych55g";
80
 
81
	@RequestMapping(value = "/devices/hypertrackId", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
82
	@ApiImplicitParams({
83
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
84
	@ApiOperation(value = "")
85
	public ResponseEntity<?> deviceHypertrackId(HttpServletRequest request,
86
			@RequestBody HyperTrackKeyModel hyperTrackKeyModel) {
87
		HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(hyperTrackKeyModel.getUserId(),
88
				hyperTrackKeyModel.getDeviceId());
89
		if (hyperTrackKey == null) {
90
			hyperTrackKey = new HypertrackKey();
27444 tejbeer 91
			hyperTrackKey.setUserId(hyperTrackKeyModel.getUserId());
92
			hyperTrackKey.setCreatedTimestamp(LocalDateTime.now());
27417 tejbeer 93
			hyperTrackKey.setDeviceId(hyperTrackKeyModel.getDeviceId());
94
		}
27422 tejbeer 95
 
27444 tejbeer 96
		hyperTrackKey.setHypertrackKeyId(hyperTrackKeyModel.getHyperTrackId());
97
 
27417 tejbeer 98
		hyperTrackKey.setUpdatedTimestamp(LocalDateTime.now());
99
		hypertrackKeyRepository.persist(hyperTrackKey);
100
		return responseSender.ok(true);
101
	}
102
 
27421 tejbeer 103
	@RequestMapping(value = "/devices/location", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
104
	public ResponseEntity<?> getLocationByKeyId(HttpServletRequest request, @RequestParam int userId,
27426 tejbeer 105
			@RequestParam int deviceId) throws IOException, MessagingException, ProfitMandiBusinessException {
27421 tejbeer 106
 
27426 tejbeer 107
		double lat1 = 28.516045882182738;
108
		double lng1 = 77.3771954997187;
27421 tejbeer 109
 
110
		HypertrackKey hyperTrackKey = hypertrackKeyRepository.selectByUserIdAndDeviceId(userId, deviceId);
27428 tejbeer 111
		// EmployeeAttendance employeeAttendance =
112
		// employeeAttendanceRepository.selectLatestPunchTimeStamp();
113
 
114
		List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKey(userId, deviceId,
115
				LocalDate.now());
27432 tejbeer 116
 
117
		LOGGER.info("hyperTrackKey" + hyperTrackKey);
118
		LOGGER.info("employeeAttendance" + employeeAttendances);
27421 tejbeer 119
		OkHttpClient client = new OkHttpClient();
120
 
121
		String authString = "Basic "
122
				+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
123
 
124
		Request request1 = new Request.Builder()
27426 tejbeer 125
				.url("https://v3.api.hypertrack.com/devices/" + hyperTrackKey.getHypertrackKeyId()).get()
27421 tejbeer 126
				.addHeader("Authorization", authString).build();
127
 
128
		Response response = client.newCall(request1).execute();
129
		JSONObject jsonObj = new JSONObject(response.body().string());
130
		JSONObject c = jsonObj.getJSONObject("location");
131
		JSONObject d = c.getJSONObject("geometry");
132
		JSONArray coords = d.getJSONArray("coordinates");
133
		double lat2 = coords.getDouble(1);
134
		double lng2 = coords.getDouble(0);
135
		double dist = distance(lat1, lng1, lat2, lng2, "m");
136
		EmployeeAttendanceModel em = new EmployeeAttendanceModel();
137
		em.setDistance(dist);
27422 tejbeer 138
		em.setLatitude(lat2);
139
		em.setLongitude(lng2);
27432 tejbeer 140
 
27428 tejbeer 141
		if (!employeeAttendances.isEmpty()) {
142
			if (employeeAttendances.get(0).getCreateTimestamp().toLocalDate().equals(LocalDate.now())) {
143
				if (employeeAttendances.get(0).getPunch().equals("punchIn")) {
144
					em.setPunchIn(true);
145
				} else {
146
					em.setPunchIn(false);
147
				}
27421 tejbeer 148
			} else {
149
				em.setPunchIn(false);
150
			}
151
		} else {
152
			em.setPunchIn(false);
153
		}
154
		return responseSender.ok(em);
155
	}
156
 
157
	private static double distance(double lat1, double lon1, double lat2, double lon2, String unit) {
158
		if ((lat1 == lat2) && (lon1 == lon2)) {
159
			return 0;
160
		} else {
161
			double theta = lon1 - lon2;
162
			double dist = Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
163
					+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta));
164
			dist = Math.acos(dist);
165
			dist = Math.toDegrees(dist);
166
			dist = dist * 60 * 1.1515;
167
			if (unit.equals("m")) {
168
				dist = dist * 1.609344;
169
				dist = dist / 0.0010000;
170
			} else if (unit.equals("N")) {
171
				dist = dist * 0.8684;
172
			}
173
			return (dist);
174
		}
175
	}
176
 
177
	@RequestMapping(value = "/employee/attendance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
178
	@ApiImplicitParams({
179
			@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header") })
180
	@ApiOperation(value = "")
181
	public ResponseEntity<?> employeeAttendance(HttpServletRequest request, @RequestParam(name = "userId") int userId,
182
			@RequestParam(name = "deviceId") int deviceId, @RequestParam(name = "punchType") PunchType punchType,
183
			@RequestParam(name = "punch") String punch) {
184
 
185
		EmployeeAttendance employeeAttendance = new EmployeeAttendance();
186
		employeeAttendance.setUserId(userId);
187
		employeeAttendance.setDeviceId(deviceId);
188
		employeeAttendance.setPunch(punch);
189
		employeeAttendance.setPunchType(punchType);
190
		employeeAttendance.setCreateTimestamp(LocalDateTime.now());
191
		employeeAttendanceRepository.persist(employeeAttendance);
27445 tejbeer 192
		if (punch.equals("punchOut")) {
193
			List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKeyASC(userId,
194
					deviceId, LocalDate.now());
195
			long hours = 0;
196
			long minutes = 0;
197
			long seconds = 0;
198
			LocalDateTime startTime = null;
199
			LocalDateTime endTime = null;
200
 
201
			for (EmployeeAttendance em : employeeAttendances) {
202
				if (em.getPunch().equals("punchIn")) {
203
					startTime = em.getCreateTimestamp();
204
				} else if (em.getPunch().equals("punchOut")) {
205
					endTime = em.getCreateTimestamp();
206
				}
207
				if (startTime != null && endTime != null) {
208
					long mites = ChronoUnit.MINUTES.between(startTime, endTime);
209
					long hour = ChronoUnit.HOURS.between(startTime, endTime);
210
					long secds = ChronoUnit.SECONDS.between(startTime, endTime);
211
					hours = hours + hour;
212
					minutes = minutes + mites;
213
					if (minutes >= 60) {
214
						minutes = minutes - 60;
215
					}
216
					seconds = seconds + secds;
217
					if (seconds >= 60) {
218
						seconds = seconds - 60;
219
					}
220
 
221
					startTime = null;
222
					endTime = null;
223
				}
224
 
225
			}
226
			LOGGER.info("employeeAttendance" + employeeAttendances);
227
 
228
			EmployeeAttendanceModel emm = new EmployeeAttendanceModel();
229
			emm.setHours(hours);
230
			emm.setMinutes(minutes);
231
			emm.setSeconds(seconds);
232
			return responseSender.ok(emm);
233
 
234
		}
27421 tejbeer 235
		return responseSender.ok(true);
236
	}
237
 
27426 tejbeer 238
	@RequestMapping(value = "/create/geofence", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
27445 tejbeer 239
	public ResponseEntity<?> createGeofence(HttpServletRequest request)
27426 tejbeer 240
			throws IOException, ProfitMandiBusinessException {
241
 
242
		List<FofoStore> fofoStores = fofoStoreRepository.selectActiveStores();
243
		for (FofoStore fofoStore : fofoStores) {
244
			CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoStore.getId());
245
			OkHttpClient client = new OkHttpClient();
246
 
247
			okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
248
			JSONObject geofe = new JSONObject();
249
			JSONArray geofences = new JSONArray();
250
			JSONObject geometry = new JSONObject();
251
			JSONObject geo = new JSONObject();
252
			JSONArray coordinates = new JSONArray();
253
			coordinates.put(fofoStore.getLongitude());
254
			coordinates.put(fofoStore.getLatitude());
255
			geo.put("type", "Point");
256
			geo.put("coordinates", coordinates);
257
			geometry.put("geometry", geo);
258
			JSONObject metadata = new JSONObject();
259
			metadata.put("name", customRetailer.getBusinessName());
260
			metadata.put("city", customRetailer.getAddress().getCity());
261
			geometry.put("metadata", metadata);
262
			geometry.put("radius", 500);
263
 
264
			geofences.put(geometry);
265
			geofe.put("geofences", geofences);
266
			okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, geofe.toString());
267
			String authString = "Basic "
268
					+ Base64.getEncoder().encodeToString(String.format("%s:%s", ACCOUNT_ID, SECRET_KEY).getBytes());
269
 
270
			Request request1 = new Request.Builder().url("https://v3.api.hypertrack.com/geofences").post(body)
271
					.addHeader("Authorization", authString).build();
272
 
273
			Response response = client.newCall(request1).execute();
274
 
275
		}
276
		return responseSender.ok(true);
277
 
278
	}
279
 
27445 tejbeer 280
	@RequestMapping(value = "/employee/hourcacl", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
281
	public ResponseEntity<?> workingHourCalculation(HttpServletRequest request,
282
			@RequestParam(name = "userId") int userId, @RequestParam(name = "deviceId") int deviceId,
283
			@RequestParam(name = "punchType") PunchType punchType, @RequestParam(name = "punch") String punch) {
27442 tejbeer 284
 
27445 tejbeer 285
		EmployeeAttendance employeeAttendance = new EmployeeAttendance();
286
		employeeAttendance.setUserId(userId);
287
		employeeAttendance.setDeviceId(deviceId);
288
		employeeAttendance.setPunch(punch);
289
		employeeAttendance.setPunchType(punchType);
290
		employeeAttendance.setCreateTimestamp(LocalDateTime.now());
291
		employeeAttendanceRepository.persist(employeeAttendance);
27442 tejbeer 292
 
27445 tejbeer 293
		List<EmployeeAttendance> employeeAttendances = employeeAttendanceRepository.selectByUserIdKeyASC(userId,
294
				deviceId, LocalDate.now());
295
		long hours = 0;
296
		long minutes = 0;
297
		long seconds = 0;
298
		LocalDateTime startTime = null;
299
		LocalDateTime endTime = null;
300
		List<Long> hghg = new ArrayList<>();
27442 tejbeer 301
 
27445 tejbeer 302
		for (EmployeeAttendance em : employeeAttendances) {
303
			if (em.getPunch().equals("punchIn")) {
304
				startTime = em.getCreateTimestamp();
305
			} else if (em.getPunch().equals("punchOut")) {
306
				endTime = em.getCreateTimestamp();
307
			}
308
			if (startTime != null && endTime != null) {
309
				long mites = ChronoUnit.MINUTES.between(startTime, endTime);
310
				long hour = ChronoUnit.HOURS.between(startTime, endTime);
311
				long secds = ChronoUnit.SECONDS.between(startTime, endTime);
312
				hours = hours + hour;
313
				minutes = minutes + mites;
314
				if (minutes >= 60) {
315
					minutes = minutes - 60;
316
				}
317
				seconds = seconds + secds;
318
				if (seconds >= 60) {
319
					seconds = seconds - 60;
320
				}
27442 tejbeer 321
 
27445 tejbeer 322
				startTime = null;
323
				endTime = null;
324
			}
325
 
326
		}
327
		LOGGER.info("employeeAttendance" + employeeAttendances);
328
 
329
		EmployeeAttendanceModel emm = new EmployeeAttendanceModel();
330
		emm.setHours(hours);
331
		emm.setMinutes(minutes);
332
		emm.setSeconds(seconds);
333
		return responseSender.ok(emm);
334
 
27442 tejbeer 335
	}
27417 tejbeer 336
}