Commit 7802a1b6 authored by mmudrakola-nisum-com's avatar mmudrakola-nisum-com Committed by rbonthala-nisum-com

MT-74:integrating_biometric_data_to_the_application (#30)

parent 39abe4d2
...@@ -56,5 +56,5 @@ dependencies { ...@@ -56,5 +56,5 @@ dependencies {
compile('jcifs:jcifs:1.3.17') compile('jcifs:jcifs:1.3.17')
compile('javax.servlet:servlet-api') compile('javax.servlet:servlet-api')
compile('com.github.ozlerhakan:poiji:1.11') compile('com.github.ozlerhakan:poiji:1.11')
testCompile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '6.1.0.jre8'
} }
...@@ -15,10 +15,16 @@ public class DbConnection { ...@@ -15,10 +15,16 @@ public class DbConnection {
public static Connection getDBConnection(String dbURL) throws SQLException { public static Connection getDBConnection(String dbURL) throws SQLException {
try { try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
connection = DriverManager.getConnection(dbURL); connection = DriverManager.getConnection("jdbc:sqlserver://10.3.45.105:1433;databaseName=smartiSCC", "sa", "nisum@123");
} catch (ClassNotFoundException cnfex) { } catch (ClassNotFoundException cnfex) {
log.error("Problem in loading or " + "registering MS Access JDBC driver", cnfex); log.error("Problem in loading or " + "registering mssql JDBC driver", cnfex);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
return connection; return connection;
} }
......
...@@ -57,11 +57,11 @@ public class AttendanceController { ...@@ -57,11 +57,11 @@ public class AttendanceController {
return new ResponseEntity<>(result, HttpStatus.OK); return new ResponseEntity<>(result, HttpStatus.OK);
} }
@RequestMapping(value = "copyRemoteMdbFileToLocal", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) /* @RequestMapping(value = "copyRemoteMdbFileToLocal", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Boolean> copyRemoteMdbFileToLocal() throws MyTimeException { public ResponseEntity<Boolean> copyRemoteMdbFileToLocal() throws MyTimeException {
Boolean result = attendanceService.copyRemoteMdbFileToLocal(); Boolean result = attendanceService.copyRemoteMdbFileToLocal();
return new ResponseEntity<>(result, HttpStatus.OK); return new ResponseEntity<>(result, HttpStatus.OK);
} }*/
@RequestMapping(value = "resyncMonthData/{fromDate}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @RequestMapping(value = "resyncMonthData/{fromDate}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Boolean> resyncMonthData(@PathVariable("fromDate") String fromDate) throws MyTimeException { public ResponseEntity<Boolean> resyncMonthData(@PathVariable("fromDate") String fromDate) throws MyTimeException {
......
...@@ -19,12 +19,12 @@ public class MyTimeCronSchedularJob implements Job { ...@@ -19,12 +19,12 @@ public class MyTimeCronSchedularJob implements Job {
@Override @Override
public void execute(JobExecutionContext jobExecutionContext) { public void execute(JobExecutionContext jobExecutionContext) {
try { /*try {
if (employeeDataService.fetchEmployeesDataOnDayBasis()) { if (employeeDataService.fetchEmployeesDataOnDayBasis()) {
MyTimeLogger.getInstance().info("Shedular Executed Successfully Records Saved in DB"); MyTimeLogger.getInstance().info("Shedular Executed Successfully Records Saved in DB");
} }
} catch (MyTimeException | SQLException e) { } catch (MyTimeException | SQLException e) {
MyTimeLogger.getInstance().error("Shedular failed to Executed ::: " , e); MyTimeLogger.getInstance().error("Shedular failed to Executed ::: " , e);
} }*/
} }
} }
...@@ -10,8 +10,4 @@ public interface AttendanceService { ...@@ -10,8 +10,4 @@ public interface AttendanceService {
List<AttendenceData> getAttendanciesReport(String reportDate) throws MyTimeException, SQLException; List<AttendenceData> getAttendanciesReport(String reportDate) throws MyTimeException, SQLException;
Boolean copyRemoteMdbFileToLocal() throws MyTimeException;
void triggerMailToAbsentees() throws MyTimeException;
} }
package com.nisum.mytime.service; package com.nisum.mytime.service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang.time.DateUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.nisum.mytime.configuration.DbConnection; import com.nisum.mytime.configuration.DbConnection;
import com.nisum.mytime.exception.handler.MyTimeException; import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.AttendenceData; import com.nisum.mytime.model.AttendenceData;
import com.nisum.mytime.utils.MyTimeLogger; import com.nisum.mytime.utils.MyTimeLogger;
import com.nisum.mytime.utils.MyTimeUtils; import com.nisum.mytime.utils.MyTimeUtils;
import jcifs.smb.SmbFile;
@Service @Service
public class AttendanceServiceImpl implements AttendanceService { public class AttendanceServiceImpl implements AttendanceService {
@Value("${mytime.attendance.fileName}")
private String mdbFile;
@Value("${mytime.localFile.directory}")
private String localFileDirectory;
@Value("${mytime.remote.directory}")
private String remoteFilesDirectory;
@Value("${mytime.remote.connection}")
private String remotePath;
@Autowired
private MongoTemplate mongoTemplate;
private Connection connection = null; private Connection connection = null;
private Statement statement = null; private Statement statement = null;
private ResultSet resultSet = null; private ResultSet resultSet = null;
private File finalfile = null;
private Calendar calendar = new GregorianCalendar();
private int month = (calendar.get(Calendar.MONTH)) + 1;
private int year = calendar.get(Calendar.YEAR);
private Date toDay = calendar.getTime();
private String queryMonthDecider = null;
@Override @Override
public List<AttendenceData> getAttendanciesReport(String reportDate) throws MyTimeException, SQLException { public List getAttendanciesReport(String reportDate) throws MyTimeException, SQLException {
long start_ms = System.currentTimeMillis(); long start_ms = System.currentTimeMillis();
List<AttendenceData> listOfAbsentEmployees = null; List listOfEmployees = new ArrayList<>();
String querys="select distinct emp.EmployeeCode,emp.FirstName,'P' as AttStatus\n" +
" FROM [smartiSCC].[dbo].[Transactions] as tr,[smartiSCC].[dbo].[EmployeeMaster] as emp\n" +
" where tr.EmployeemasterID=emp.EmployeeMasterID and \n" +
" replace(convert(varchar,tr.aDateTime, 111), '/', '-')='"+reportDate+"'\n" +
" Union \n" +
" select emp.EmployeeCode,emp.FirstName,'A' as AttStatus\n" +
" FROM [smartiSCC].[dbo].[Transactions] as tr,[smartiSCC].[dbo].[EmployeeMaster] as emp\n" +
" where tr.EmployeemasterID!=emp.EmployeeMasterID and \n" +
" replace(convert(varchar,tr.aDateTime, 111), '/', '-')='"+reportDate+"'";
try { try {
File dir = new File(localFileDirectory); String dbURL = MyTimeUtils.driverUrl;
for (File file : dir.listFiles()) { MyTimeLogger.getInstance().info(dbURL);
if (file.getCanonicalPath().contains(mdbFile)) { connection = DbConnection.getDBConnection(dbURL);
finalfile = new File(file.getCanonicalPath()); statement = connection.createStatement();
} resultSet = statement.executeQuery(querys.toString());
} while (resultSet.next()) {
if (null != finalfile) { AttendenceData attendData=new AttendenceData();
int dayOftoDay = calendar.get(Calendar.DAY_OF_MONTH); attendData.setEmployeeId(resultSet.getString(1));
Date selectedDate = MyTimeUtils.dfmt.parse(reportDate); attendData.setEmployeeName(resultSet.getString(2));
calendar.setTime(MyTimeUtils.dfmt.parse(reportDate)); attendData.setIfPresent(resultSet.getString(3));
int dayOfSelectedDate = calendar.get(Calendar.DAY_OF_MONTH); listOfEmployees.add(attendData);
if (dayOfSelectedDate == dayOftoDay && month == (calendar.get(Calendar.MONTH)) + 1
&& year == calendar.get(Calendar.YEAR)) {
listOfAbsentEmployees = fecthRecordsFromMDb();
} else if (selectedDate.before(toDay)) {
calendar.setTime(selectedDate);
listOfAbsentEmployees = fecthRecordsFromMongoDb(reportDate);
} }
MyTimeLogger.getInstance().info("Time Taken for " + (System.currentTimeMillis() - start_ms)); MyTimeLogger.getInstance().info("Time Taken for " + (System.currentTimeMillis() - start_ms));
}
} catch (Exception e) { } catch (Exception e) {
MyTimeLogger.getInstance().error("Exception occured due to : ", e); MyTimeLogger.getInstance().error("Exception occured due to : ", e);
throw new MyTimeException(e.getMessage()); throw new MyTimeException(e.getMessage());
} finally { }finally {
if (null != connection) { if (null != connection) {
connection.close(); connection.close();
statement.close(); statement.close();
resultSet.close(); resultSet.close();
} }
} }
return listOfAbsentEmployees; return listOfEmployees;
}
private String createDbStatementWithFile() throws MyTimeException {
StringBuilder queryMonthDecider = null;
try {
queryMonthDecider = new StringBuilder();
String dbURL = MyTimeUtils.driverUrl + finalfile.getCanonicalPath();
MyTimeLogger.getInstance().info(dbURL);
connection = DbConnection.getDBConnection(dbURL);
statement = connection.createStatement();
Calendar calendar1 = Calendar.getInstance();
calendar1.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH), 6, 00, 00);
Date dayStartsTime = calendar1.getTime();
Date maxTimeToLogin = DateUtils.addHours(dayStartsTime, 12);
queryMonthDecider.append(MyTimeUtils.USERID_QUERY);
queryMonthDecider.append(calendar.get(Calendar.MONTH) + 1);
queryMonthDecider.append(MyTimeUtils.UNDER_SCORE);
queryMonthDecider.append(calendar.get(Calendar.YEAR));
queryMonthDecider.append(MyTimeUtils.WHERE_COND);
queryMonthDecider.append(MyTimeUtils.df.format(dayStartsTime) + MyTimeUtils.SINGLE_QUOTE);
queryMonthDecider.append(MyTimeUtils.AND_COND);
queryMonthDecider.append(MyTimeUtils.df.format(maxTimeToLogin) + MyTimeUtils.SINGLE_QUOTE);
MyTimeLogger.getInstance().info(queryMonthDecider.toString());
} catch (Exception e) {
MyTimeLogger.getInstance().error("Exception occured due to: ", e);
throw new MyTimeException(e.getMessage());
}
return queryMonthDecider.toString();
}
private List<AttendenceData> fecthRecordsFromMDb() throws MyTimeException {
List<String> presentiesList = null;
List<String> listOfPresentEmployees = new ArrayList<>();
List<AttendenceData> listOfAbsentEmployees = null;
try {
queryMonthDecider = createDbStatementWithFile();
resultSet = statement.executeQuery(queryMonthDecider);
while (resultSet.next()) {
if (resultSet.getString(1).length() >= 5) {
listOfPresentEmployees.add(resultSet.getString(1));
}
}
presentiesList = listOfPresentEmployees.stream().distinct().collect(Collectors.toList());
listOfAbsentEmployees = fetchAbsenteesListFromDb(presentiesList);
} catch (Exception e) {
MyTimeLogger.getInstance().error("Exception occured due to: ", e);
throw new MyTimeException(e.getMessage());
}
return listOfAbsentEmployees;
}
private List<AttendenceData> fecthRecordsFromMongoDb(String reportDate) throws MyTimeException {
List<String> presentiesList = null;
List<String> listOfPresentEmployees = new ArrayList<>();
List<AttendenceData> listOfAbsentEmployees = null;
DBCursor cursor = null;
queryMonthDecider = createDbStatementWithFile();
BasicDBObject gtQuery = new BasicDBObject();
gtQuery.put(MyTimeUtils.DATE_OF_LOGIN, reportDate);
listOfPresentEmployees.clear();
cursor = mongoTemplate.getCollection(MyTimeUtils.EMPLOYEE_COLLECTION).find(gtQuery)
.sort(new BasicDBObject(MyTimeUtils.EMPLOYEE_ID, 1));
while (cursor.hasNext()) {
DBObject dbObject = cursor.next();
listOfPresentEmployees.add(dbObject.get(MyTimeUtils.EMPLOYEE_ID).toString());
}
presentiesList = listOfPresentEmployees.stream().distinct().collect(Collectors.toList());
listOfAbsentEmployees = fetchAbsenteesListFromDb(presentiesList);
return listOfAbsentEmployees;
}
private List<AttendenceData> fetchAbsenteesListFromDb(List<String> presentiesList) throws MyTimeException {
List<AttendenceData> listOfAbsentEmployees = new ArrayList<>();
try {
if (!presentiesList.isEmpty()) {
StringBuilder absentiesQuery = new StringBuilder();
absentiesQuery.append(MyTimeUtils.ABESENT_QUERY);
absentiesQuery.append(queryMonthDecider);
absentiesQuery.append(MyTimeUtils.ABESENT_QUERY1);
MyTimeLogger.getInstance().info(absentiesQuery.toString());
resultSet = statement.executeQuery(absentiesQuery.toString());
listOfAbsentEmployees.clear();
while (resultSet.next()) {
if (resultSet.getString(3).length() >= 5) {
AttendenceData attendenceData = new AttendenceData();
attendenceData.setEmployeeName(resultSet.getString(2));
attendenceData.setEmployeeId(resultSet.getString(3));
attendenceData.setIfPresent(MyTimeUtils.ABESENT);
listOfAbsentEmployees.add(attendenceData);
}
}
if (!listOfAbsentEmployees.isEmpty()) {
listOfAbsentEmployees.get(0).setTotalPresent(presentiesList.size());
listOfAbsentEmployees.get(0).setTotalAbsent(listOfAbsentEmployees.size());
}
}
} catch (Exception e) {
MyTimeLogger.getInstance().error("Exception occured due to: ", e);
throw new MyTimeException(e.getMessage());
}
return listOfAbsentEmployees;
}
public Boolean copyRemoteMdbFileToLocal() throws MyTimeException {
File Finalfile = null;
boolean result = false;
try {
SmbFile[] smbFiles = new SmbFile(remotePath).listFiles();
for (SmbFile file : smbFiles) {
if (file.getCanonicalPath().contains(mdbFile)) {
Finalfile = new File(localFileDirectory + file.getName());
try (InputStream in = file.getInputStream();
FileOutputStream out = new FileOutputStream(Finalfile)) {
IOUtils.copy(in, out);
result = true;
}
}
}
} catch (Exception e) {
MyTimeLogger.getInstance().error(e.getMessage());
throw new MyTimeException(e.getMessage());
}
return result;
}
@Override
public void triggerMailToAbsentees() throws MyTimeException {
} }
......
package com.nisum.mytime.service; package com.nisum.mytime.service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.text.DateFormat; import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.nisum.mytime.configuration.DbConnection; import com.nisum.mytime.configuration.DbConnection;
import com.nisum.mytime.exception.handler.MyTimeException; import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.DateCompare;
import com.nisum.mytime.model.EmpLoginData; import com.nisum.mytime.model.EmpLoginData;
import com.nisum.mytime.repository.EmployeeAttendanceRepo; import com.nisum.mytime.repository.EmployeeAttendanceRepo;
import com.nisum.mytime.utils.MyTimeLogger; import com.nisum.mytime.utils.MyTimeLogger;
import com.nisum.mytime.utils.MyTimeUtils; import com.nisum.mytime.utils.MyTimeUtils;
import jcifs.smb.SmbFile;
@Component @Component
@Transactional @Transactional
public class EmployeeDataService { public class EmployeeDataService {
private String dateOnly = null;
private String empDatestr = null;
private Connection connection = null; private Connection connection = null;
private Statement statement = null; private Statement statement = null;
private ResultSet resultSet = null; private ResultSet resultSet = null;
private Date currentDay = null;
private Date nextCurrentDay = null;
private DBCursor cursor = null;
@Autowired
private MongoTemplate mongoTemplate;
@Value("${mytime.remote.connection}")
private String remotePath;
@Value("${mytime.localFile.directory}")
private String localFileDirectory;
@Value("${mytime.attendance.fileName}")
private String mdbFile;
@Value("${mytime.remoteFileTransfer.required}")
private Boolean isRemoteFileTransfer;
@Value("${mytime.remote.directory}")
private String remoteFilesDirectory;
@Autowired @Autowired
private EmployeeAttendanceRepo employeeLoginsRepo; private EmployeeAttendanceRepo employeeLoginsRepo;
private File finalfile = null;
public Boolean fetchEmployeesData(String perticularDate, boolean resynchFlag) throws MyTimeException {
Boolean result = false;
StringBuilder queryMonthDecider = new StringBuilder();
long start_ms = System.currentTimeMillis();
List<EmpLoginData> loginsData = new ArrayList<>();
Map<String, List<EmpLoginData>> map = new HashMap<>();
boolean frstQuery = true;
Date searchdDate = null;
Date endOfsearchDate = null;
Map<String, EmpLoginData> emp = new HashMap<>();
try {
File dir = new File(localFileDirectory);
for (File file : dir.listFiles()) {
if (file.getCanonicalPath().contains(mdbFile)) {
finalfile = new File(file.getCanonicalPath());
}
}
if (null != finalfile) {
Calendar calendar = new GregorianCalendar();
Date date = MyTimeUtils.dfmt.parse(perticularDate);
calendar.setTime(date);
int month = (calendar.get(Calendar.MONTH)) + 1;
int year = calendar.get(Calendar.YEAR);
String dbURL = MyTimeUtils.driverUrl + finalfile.getCanonicalPath();
MyTimeLogger.getInstance().info(dbURL);
connection = DbConnection.getDBConnection(dbURL);
statement = connection.createStatement();
if (!resynchFlag) {
calendar.set(year, (month - 1), calendar.get(Calendar.DAY_OF_MONTH), 6, 00, 00);
searchdDate = calendar.getTime();
endOfsearchDate = DateUtils.addHours(searchdDate, 24);
} else {
calendar.set(year, (month - 1), calendar.get(Calendar.DAY_OF_MONTH), 6, 00, 00);
endOfsearchDate = calendar.getTime();
calendar.set(year, (month - 1), calendar.get(Calendar.DAY_OF_MONTH) - 15, 6, 00, 00);
searchdDate = calendar.getTime();
}
queryMonthDecider.append(MyTimeUtils.QUERY);
queryMonthDecider.append((calendar.get(Calendar.MONTH)) + 1);
queryMonthDecider.append(MyTimeUtils.UNDER_SCORE);
queryMonthDecider.append(calendar.get(Calendar.YEAR));
queryMonthDecider.append(MyTimeUtils.WHERE_COND);
queryMonthDecider.append(MyTimeUtils.df.format(searchdDate) + MyTimeUtils.SINGLE_QUOTE);
queryMonthDecider.append(MyTimeUtils.AND_COND);
queryMonthDecider.append(MyTimeUtils.df.format(endOfsearchDate) + MyTimeUtils.SINGLE_QUOTE);
MyTimeLogger.getInstance().info(queryMonthDecider.toString());
resultSet = statement.executeQuery(queryMonthDecider.toString());
while (resultSet.next()) {
frstQuery = true;
if (resultSet.getString(4).length() >= 5) {
EmpLoginData loginData = new EmpLoginData();
loginData.setEmployeeId(resultSet.getString(4));
loginData.setFirstLogin(resultSet.getString(5));
loginData.setDirection(resultSet.getString(6));
PreparedStatement statement1 = connection.prepareStatement(MyTimeUtils.EMP_NAME_QUERY);
statement1.setLong(1, Long.valueOf(loginData.getEmployeeId()));
ResultSet resultSet1 = statement1.executeQuery();
while (resultSet1.next() && frstQuery) {
loginData.setEmployeeName(resultSet1.getString(2));
frstQuery = false;
}
loginData.setId(resultSet.getString(4));
loginsData.add(loginData);
}
}
Iterator<EmpLoginData> iter = loginsData.iterator();
while (iter.hasNext()) {
EmpLoginData empLoginData = iter.next();
getSingleEmploginData(loginsData, map, empLoginData);
}
for (Entry<String, List<EmpLoginData>> empMap : map.entrySet()) {
calculatingEachEmployeeLoginsByDate(empMap.getValue(), emp);
}
employeeLoginsRepo.save(emp.values());
result = Boolean.TRUE;
MyTimeLogger.getInstance().info("Time Taken for " + (System.currentTimeMillis() - start_ms));
}
} catch (Exception sqlex) {
MyTimeLogger.getInstance().error(sqlex.getMessage());
throw new MyTimeException(sqlex.getMessage());
} finally {
try {
if (null != connection) {
connection.close();
statement.close();
resultSet.close();
}
} catch (SQLException e) {
MyTimeLogger.getInstance().error(e.getMessage());
}
}
return result;
}
public Boolean fetchEmployeesDataOnDayBasis() throws MyTimeException, SQLException {
Boolean result = false;
StringBuilder queryMonthDecider = new StringBuilder();
long start_ms = System.currentTimeMillis();
List<EmpLoginData> loginsData = new ArrayList<>();
Map<String, List<EmpLoginData>> map = new HashMap<>();
boolean frstQuery = true;
Map<String, EmpLoginData> emp = new HashMap<>();
try {
File file = fetchRemoteFilesAndCopyToLocal();
if (null != file && file.getName().equals(mdbFile)) {
Calendar calendar = new GregorianCalendar();
int month = (calendar.get(Calendar.MONTH)) + 1;
int year = calendar.get(Calendar.YEAR);
String dbURL = MyTimeUtils.driverUrl + file.getCanonicalPath();
MyTimeLogger.getInstance().info(dbURL);
connection = DbConnection.getDBConnection(dbURL);
statement = connection.createStatement();
Calendar calendar1 = Calendar.getInstance();
int decidedDay = (calendar.get(Calendar.DAY_OF_WEEK));
int addingHoursBasedOnDay = 72;
if (decidedDay != 3) {
decidedDay = 1;
addingHoursBasedOnDay = 48;
}
calendar1.set(year, (month - 1), calendar.get(Calendar.DAY_OF_MONTH) - decidedDay, 6, 00, 00);
Date currentDayDate = calendar1.getTime();
Date nextDayDate = DateUtils.addHours(currentDayDate, addingHoursBasedOnDay);
queryMonthDecider.append(MyTimeUtils.QUERY);
queryMonthDecider.append((calendar1.get(Calendar.MONTH)) + 1);
queryMonthDecider.append(MyTimeUtils.UNDER_SCORE);
queryMonthDecider.append(calendar1.get(Calendar.YEAR));
queryMonthDecider.append(MyTimeUtils.WHERE_COND);
queryMonthDecider.append(MyTimeUtils.df.format(currentDayDate) + MyTimeUtils.SINGLE_QUOTE);
queryMonthDecider.append(MyTimeUtils.AND_COND);
queryMonthDecider.append(MyTimeUtils.df.format(nextDayDate) + MyTimeUtils.SINGLE_QUOTE);
MyTimeLogger.getInstance().info(queryMonthDecider.toString());
resultSet = statement.executeQuery(queryMonthDecider.toString());
while (resultSet.next()) {
frstQuery = true;
if (resultSet.getString(4).length() >= 5) {
EmpLoginData loginData = new EmpLoginData();
loginData.setEmployeeId(resultSet.getString(4));
loginData.setFirstLogin(resultSet.getString(5));
loginData.setDirection(resultSet.getString(6));
PreparedStatement statement1 = connection.prepareStatement(MyTimeUtils.EMP_NAME_QUERY);
statement1.setLong(1, Long.valueOf(loginData.getEmployeeId()));
ResultSet resultSet1 = statement1.executeQuery();
while (resultSet1.next() && frstQuery) {
loginData.setEmployeeName(resultSet1.getString(2));
frstQuery = false;
}
loginData.setId(resultSet.getString(4));
loginsData.add(loginData);
}
}
Iterator<EmpLoginData> iter = loginsData.iterator();
while (iter.hasNext()) {
EmpLoginData empLoginData = iter.next();
getSingleEmploginData(loginsData, map, empLoginData);
}
for (Entry<String, List<EmpLoginData>> empMap : map.entrySet()) {
calculatingEachEmployeeLoginsByDate(empMap.getValue(), emp);
}
employeeLoginsRepo.save(emp.values());
result = Boolean.TRUE;
MyTimeLogger.getInstance().info("Time Taken for " + (System.currentTimeMillis() - start_ms));
}
} catch (Exception sqlex) {
MyTimeLogger.getInstance().error(sqlex.getMessage());
throw new MyTimeException(sqlex.getMessage());
} finally {
if (null != connection) {
connection.close();
statement.close();
resultSet.close();
}
}
return result;
}
private File fetchRemoteFilesAndCopyToLocal() throws MyTimeException {
File Finalfile = null;
try {
if (Boolean.TRUE.equals(isRemoteFileTransfer)) {
SmbFile[] smbFiles = new SmbFile(remotePath).listFiles();
for (SmbFile file : smbFiles) {
if (file.getCanonicalPath().contains(mdbFile)) {
Finalfile = new File(localFileDirectory + file.getName());
try (InputStream in = file.getInputStream();
FileOutputStream out = new FileOutputStream(Finalfile)) {
IOUtils.copy(in, out);
}
}
}
} else {
File dir = new File(remoteFilesDirectory);
for (File file : dir.listFiles()) {
if (file.getCanonicalPath().contains(mdbFile)) {
Finalfile = new File(file.getCanonicalPath());
}
}
}
} catch (Exception e) {
MyTimeLogger.getInstance().error(e.getMessage());
throw new MyTimeException(e.getMessage());
}
return Finalfile;
}
public List<EmpLoginData> fetchEmployeeLoginsBasedOnDates(long employeeId, String fromDate, String toDate) public List<EmpLoginData> fetchEmployeeLoginsBasedOnDates(long employeeId, String fromDate, String toDate)
throws MyTimeException { throws MyTimeException {
long start_ms = System.currentTimeMillis(); long start_ms = System.currentTimeMillis();
Query query = null; String querys="select emp.EmployeeCode,emp.FirstName,MIN(tr.aDateTime) AS FirstLogin,MAX(tr.aDateTime) AS LastLogin\n" +
"from Transactions as tr,EmployeeMaster as emp\n" +
"where tr.EmployeemasterID=emp.EmployeeMasterID and \n" +
"replace(convert(varchar,tr.aDateTime, 111), '/', '-')>='"+fromDate+"' and \n" +
"replace(convert(varchar,tr.aDateTime, 111), '/', '-')<='"+toDate+"' and emp.EmployeeCode="+employeeId+"\n" +
"group by convert(varchar,tr.aDateTime, 111),emp.EmployeeCode,emp.FirstName";
int countHours = 0; int countHours = 0;
List<EmpLoginData> listOfEmpLoginData = new ArrayList<>(); List<EmpLoginData> listOfEmpLoginData = new ArrayList<>();
try { try {
if (employeeId > 0) { if (employeeId > 0) {
BasicDBObject gtQuery = new BasicDBObject(); String dbURL = MyTimeUtils.driverUrl;
gtQuery.put(MyTimeUtils.ID, new BasicDBObject("$gte", employeeId + MyTimeUtils.HYPHEN + fromDate) MyTimeLogger.getInstance().info(dbURL);
.append("$lte", employeeId + MyTimeUtils.HYPHEN + toDate)); connection = DbConnection.getDBConnection(dbURL);
System.out.println("Connection established");
cursor = mongoTemplate.getCollection(MyTimeUtils.EMPLOYEE_COLLECTION).find(gtQuery) statement = connection.createStatement();
.sort(new BasicDBObject(MyTimeUtils.DATE_OF_LOGIN, -1)); resultSet = statement.executeQuery(querys.toString());
while (resultSet.next()) {
while (cursor.hasNext()) {
DBObject dbObject = cursor.next();
EmpLoginData empLoginData = new EmpLoginData(); EmpLoginData empLoginData = new EmpLoginData();
empLoginData.setEmployeeId(dbObject.get(MyTimeUtils.EMPLOYEE_ID).toString()); empLoginData.setEmployeeId(resultSet.getString(1));
empLoginData.setEmployeeName(dbObject.get(MyTimeUtils.EMPLOYEE_NAME).toString()); empLoginData.setEmployeeName(resultSet.getString(2));
empLoginData.setDateOfLogin(dbObject.get(MyTimeUtils.DATE_OF_LOGIN).toString()); empLoginData.setDateOfLogin(resultSet.getDate(3).toString());
empLoginData.setFirstLogin(dbObject.get(MyTimeUtils.FIRST_LOGIN).toString()); empLoginData.setFirstLogin(resultSet.getTime(3).toString());
empLoginData.setLastLogout(dbObject.get(MyTimeUtils.LAST_LOGOUT).toString()); empLoginData.setLastLogout(resultSet.getTime(4).toString());
empLoginData.setTotalLoginTime(dbObject.get(MyTimeUtils.TOTAL_LOGIN_TIME).toString()); Time from = resultSet.getTime(3);
Time to = resultSet.getTime(4);
long milliseconds=to.getTime() - from.getTime();
int seconds = (int) milliseconds / 1000;
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
seconds = (seconds % 3600) % 60;
empLoginData.setTotalLoginTime(hours+":"+minutes+":"+seconds);
empLoginData.setTotalLoginTime(hours+":"+minutes+":"+seconds);
Date d = MyTimeUtils.tdf.parse(empLoginData.getTotalLoginTime()); Date d = MyTimeUtils.tdf.parse(empLoginData.getTotalLoginTime());
countHours += d.getTime(); countHours += d.getTime();
listOfEmpLoginData.add(empLoginData); listOfEmpLoginData.add(empLoginData);
...@@ -341,11 +84,8 @@ public class EmployeeDataService { ...@@ -341,11 +84,8 @@ public class EmployeeDataService {
+ (System.currentTimeMillis() - start_ms)); + (System.currentTimeMillis() - start_ms));
} else if (employeeId == 0) { } else if (employeeId == 0) {
query = new Query(Criteria.where(MyTimeUtils.DATE_OF_LOGIN).gte(fromDate).lte(toDate));
query.with(new Sort(new Order(Direction.ASC, MyTimeUtils.EMPLOYEE_ID),
new Order(Direction.DESC, MyTimeUtils.DATE_OF_LOGIN)));
listOfEmpLoginData = mongoTemplate.find(query, EmpLoginData.class); listOfEmpLoginData = null;
MyTimeLogger.getInstance().info("Time Taken for with fecth All Employees data based on Dates ::: " MyTimeLogger.getInstance().info("Time Taken for with fecth All Employees data based on Dates ::: "
+ (System.currentTimeMillis() - start_ms)); + (System.currentTimeMillis() - start_ms));
...@@ -357,137 +97,4 @@ public class EmployeeDataService { ...@@ -357,137 +97,4 @@ public class EmployeeDataService {
return listOfEmpLoginData; return listOfEmpLoginData;
} }
private void calculatingEachEmployeeLoginsByDate(List<EmpLoginData> loginsData, Map<String, EmpLoginData> empMap)
throws MyTimeException {
boolean first = true;
List<String> dates = new ArrayList<>();
List<String> firstAndLastLoginDates = new ArrayList<>();
Map<String, EmpLoginData> internalEmpMap = new HashMap<>();
Collections.sort(loginsData, new DateCompare());
int count = 0;
String employeeId = loginsData.get(0).getEmployeeId();
try {
for (EmpLoginData empLoginData : loginsData) {
count++;
if (first) {
firstLoginAndLastRecordAdding(empLoginData, dates, firstAndLastLoginDates, internalEmpMap);
if (count == loginsData.size()) {
ifCountEqListSize(empLoginData, dates, firstAndLastLoginDates, internalEmpMap, employeeId,
empMap);
}
first = false;
} else {
empDatestr = empLoginData.getFirstLogin();
Date dt = MyTimeUtils.df.parse(empDatestr);
String timeOnly = MyTimeUtils.tdf.format(dt);
if (dt.after(currentDay) && dt.before(nextCurrentDay)) {
dates.add(timeOnly);
firstAndLastLoginDates.add(MyTimeUtils.df.parse(empDatestr) + StringUtils.EMPTY);
if (count == loginsData.size()) {
ifCountEqListSize(empLoginData, dates, firstAndLastLoginDates, internalEmpMap, employeeId,
empMap);
}
} else {
EmpLoginData empLoginData1 = internalEmpMap.get(dateOnly);
ifCountEqListSize(empLoginData1, dates, firstAndLastLoginDates, internalEmpMap, employeeId,
empMap);
firstLoginAndLastRecordAdding(empLoginData, dates, firstAndLastLoginDates, internalEmpMap);
if (count == loginsData.size()) {
ifCountEqListSize(empLoginData, dates, firstAndLastLoginDates, internalEmpMap, employeeId,
empMap);
}
}
}
}
} catch (Exception e) {
MyTimeLogger.getInstance().error(e.getMessage());
throw new MyTimeException(e.getMessage());
}
}
private void ifCountEqListSize(EmpLoginData empLoginData, List<String> dates, List<String> firstAndLastLoginDates,
Map<String, EmpLoginData> internalEmpMap, String employeeId, Map<String, EmpLoginData> empMap)
throws MyTimeException {
addingEmpDatesBasedonLogins(empLoginData, dates, firstAndLastLoginDates, internalEmpMap);
internalEmpMap.get(dateOnly).setId(employeeId + MyTimeUtils.HYPHEN + dateOnly);
empMap.put(employeeId + MyTimeUtils.HYPHEN + dateOnly, internalEmpMap.get(dateOnly));
}
private void firstLoginAndLastRecordAdding(EmpLoginData empLoginData, List<String> dates,
List<String> firstAndLastLoginDates, Map<String, EmpLoginData> internalEmpMap) throws MyTimeException {
try {
empDatestr = empLoginData.getFirstLogin();
Date dt;
dt = MyTimeUtils.df.parse(empDatestr);
String timeOnly = MyTimeUtils.tdf.format(dt);
dateOnly = MyTimeUtils.dfmt.format(dt);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
6, 00, 00);
currentDay = calendar.getTime();
nextCurrentDay = DateUtils.addHours(currentDay, 24);
if (dt.after(currentDay) && dt.before(nextCurrentDay)) {
empLoginData.setDateOfLogin(dateOnly);
dates.add(timeOnly);
firstAndLastLoginDates.add(MyTimeUtils.df.parse(empDatestr) + StringUtils.EMPTY);
}
internalEmpMap.put(dateOnly, empLoginData);
} catch (ParseException e) {
MyTimeLogger.getInstance().error(e.getMessage());
throw new MyTimeException(e.getMessage());
}
}
private EmpLoginData addingEmpDatesBasedonLogins(EmpLoginData empLoginData, List<String> dates,
List<String> firstAndLastLoginDates, Map<String, EmpLoginData> empMap) throws MyTimeException {
String roundingMinutes = null;
try {
if (!dates.isEmpty()) {
String min = dates.get(0);
String max = dates.get(dates.size() - 1);
empLoginData.setFirstLogin(min);
empLoginData.setLastLogout(max);
dates.clear();
}
if (!firstAndLastLoginDates.isEmpty()) {
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date calMinDt = (Date) formatter.parse(firstAndLastLoginDates.get(0));
Date calMaxDt = (Date) formatter.parse(firstAndLastLoginDates.get(firstAndLastLoginDates.size() - 1));
long calDtDiffHours = (calMaxDt.getTime() - calMinDt.getTime());
int seconds = ((int) calDtDiffHours) / 1000;
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
if (minutes < 10) {
roundingMinutes = MyTimeUtils.ZERO + minutes;
empLoginData.setTotalLoginTime(hours + MyTimeUtils.COLON + roundingMinutes);
} else {
empLoginData.setTotalLoginTime(hours + MyTimeUtils.COLON + minutes);
}
firstAndLastLoginDates.clear();
}
empLoginData.setDateOfLogin(dateOnly);
empMap.put(dateOnly, empLoginData);
} catch (Exception e) {
MyTimeLogger.getInstance().error(e.getMessage());
throw new MyTimeException(e.getMessage());
}
return empLoginData;
}
private void getSingleEmploginData(List<EmpLoginData> loginsData, Map<String, List<EmpLoginData>> map,
EmpLoginData empLoginData) throws ParseException {
List<EmpLoginData> singleEmpLogindata = new ArrayList<>();
Iterator<EmpLoginData> iter = loginsData.iterator();
while (iter.hasNext()) {
EmpLoginData empLoginData1 = iter.next();
if (empLoginData.getEmployeeId().equals(empLoginData1.getEmployeeId())) {
singleEmpLogindata.add(empLoginData1);
}
}
map.put(empLoginData.getEmployeeId(), singleEmpLogindata);
}
} }
\ No newline at end of file
...@@ -85,8 +85,9 @@ public class UserServiceImpl implements UserService { ...@@ -85,8 +85,9 @@ public class UserServiceImpl implements UserService {
@Override @Override
public Boolean fetchEmployeesData(String perticularDate, public Boolean fetchEmployeesData(String perticularDate,
boolean resynchFlag) throws MyTimeException { boolean resynchFlag) throws MyTimeException {
return employeeDataBaseService.fetchEmployeesData(perticularDate, /* return employeeDataBaseService.fetchEmployeesData(perticularDate,
resynchFlag); resynchFlag);*/
return true;
} }
@Override @Override
......
...@@ -62,6 +62,7 @@ myApp.controller("attendanceReportController", function($scope, $http, myFactory ...@@ -62,6 +62,7 @@ myApp.controller("attendanceReportController", function($scope, $http, myFactory
$scope.gridOptions.data = []; $scope.gridOptions.data = [];
$scope.getEmployeePresent = function(type){ $scope.getEmployeePresent = function(type){
$scope.attendenceType="both";
$mdDialog.hide(); $mdDialog.hide();
if(type == "onload"){ if(type == "onload"){
showProgressDialog("Fetching data please wait..."); showProgressDialog("Fetching data please wait...");
...@@ -80,10 +81,24 @@ myApp.controller("attendanceReportController", function($scope, $http, myFactory ...@@ -80,10 +81,24 @@ myApp.controller("attendanceReportController", function($scope, $http, myFactory
if(response.data.length == 0){ if(response.data.length == 0){
$timeout(function(){showAlert('No data available');},600); $timeout(function(){showAlert('No data available');},600);
$scope.refreshPage(); $scope.refreshPage();
$scope.attendenceType="both";
}else{ }else{
$scope.attendenceType="both";
$scope.totalAttendanceArray=response.data;
$scope.gridOptions.data = response.data; $scope.gridOptions.data = response.data;
$scope.totalPresent = response.data[0].totalPresent; $scope.presentArray=[];
$scope.totalAbsent = response.data[0].totalAbsent; $scope.absentArray=[];
angular.forEach(response.data, function(attendance) {
if(attendance.ifPresent =='P'){
$scope.presentArray.push(attendance);
}else if(attendance.ifPresent =='A'){
$scope.absentArray.push(attendance);
}
});
$scope.totalPresent = $scope.presentArray.length;
$scope.totalAbsent = $scope.absentArray.length;
} }
}, function myError(response) { }, function myError(response) {
showAlert("Something went wrong while fetching data!!!"); showAlert("Something went wrong while fetching data!!!");
...@@ -134,4 +149,20 @@ myApp.controller("attendanceReportController", function($scope, $http, myFactory ...@@ -134,4 +149,20 @@ myApp.controller("attendanceReportController", function($scope, $http, myFactory
function ProgressController($scope, dataToPass) { function ProgressController($scope, dataToPass) {
$scope.progressText = dataToPass; $scope.progressText = dataToPass;
} }
$scope.getAttendanceReport = function(value){
if(value == 'both'){
$scope.attendenceType=value;
$scope.gridOptions.data=$scope.totalAttendanceArray;
}else if (value == 'present'){
$scope.present=value;
$scope.gridOptions.data=$scope.presentArray;
}else if (value == 'absent'){
$scope.absent=value;
$scope.gridOptions.data=$scope.absentArray;
}
}
}); });
...@@ -34,18 +34,29 @@ ...@@ -34,18 +34,29 @@
</div> </div>
<div class="row col-lg-12" style="height: 15px;"></div> <div class="row col-lg-12" style="height: 15px;"></div>
<div class="row col-lg-12"> <div class="row col-lg-12">
<div class="col-lg-3"></div> <div class="col-lg-8">
<div class="col-lg-2 col-xs-12"> <div class="col-lg-2 col-xs-12">
</div>
<div class=" col-lg-offset-2 col-lg-3 col-xs-12">
<p> <p>
<b>Total Present:</b> {{totalPresent}} <b>Total Present:</b> {{totalPresent}}
</p> </p>
</div> </div>
<div class="col-lg-2 col-xs-12"> <div class="col-lg-3 col-xs-12">
<p> <p>
<b>Total Absent:</b> {{totalAbsent}} <b>Total Absent:</b> {{totalAbsent}}
</p> </p>
</div> </div>
<div class="col-lg-5"></div> </div>
<div class=" cocol-lg-4 ">
<p><input type="radio" name="attend" ng-model="attendenceType" value="both" ng-click="getAttendanceReport(attendenceType)"> All
<input type="radio" name="attend" ng-model="attendenceType" value="present" ng-click="getAttendanceReport(attendenceType)"> Present
<input type="radio" name="attend" ng-model="attendenceType" value="absent" ng-click="getAttendanceReport(attendenceType)"> Absence
</p>
</div>
</div> </div>
<div class="row col-lg-12" style="height: 15px;"></div> <div class="row col-lg-12" style="height: 15px;"></div>
</div> </div>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment