Skip to content

Commit

Permalink
feat(timeclock): refactor and add cron
Browse files Browse the repository at this point in the history
  • Loading branch information
nandinboldn committed Dec 30, 2022
1 parent 5fe5c91 commit 46c7faf
Show file tree
Hide file tree
Showing 17 changed files with 446 additions and 160 deletions.
129 changes: 0 additions & 129 deletions packages/plugin-timeclock-api/cronjobs/timelock.ts

This file was deleted.

3 changes: 2 additions & 1 deletion packages/plugin-timeclock-api/package.json
Expand Up @@ -8,6 +8,7 @@
"start": "cd .erxes/dist/plugin-timeclock-api/.erxes && node src"
},
"dependencies": {
"mysql2": "^2.3.3"
"mysql2": "^2.3.3",
"dayjs": "1.8.15"
}
}
9 changes: 5 additions & 4 deletions packages/plugin-timeclock-api/src/configs.ts
Expand Up @@ -4,8 +4,7 @@ import resolvers from './graphql/resolvers';
import { initBroker } from './messageBroker';
import { getSubdomain } from '@erxes/api-utils/src/core';
import { generateModels } from './connectionResolver';
import { connectToMysql } from '../cronjobs/timelock';
import * as cors from 'cors';
import cronjobs from './cronjobs/timelock';

export let mainDb;
export let debug;
Expand All @@ -23,6 +22,10 @@ export default {
};
},

meta: {
cronjobs
},

apolloServerContext: async (context, req) => {
const subdomain = getSubdomain(req);
const models = await generateModels(subdomain);
Expand All @@ -37,8 +40,6 @@ export default {
mainDb = options.db;
const app = options.app;

app.get('/mysql', connectToMysql);

initBroker(options.messageBrokerClient);

graphqlPubsub = options.pubsubClient;
Expand Down
29 changes: 29 additions & 0 deletions packages/plugin-timeclock-api/src/cronjobs/timelock.ts
@@ -0,0 +1,29 @@
import * as dayjs from 'dayjs';
import { getEnv } from '@erxes/api-utils/src';
import { connectAndQueryFromMySql } from '../utils';

const connectAndImportFromMysql = async (subdomain: string) => {
const MYSQL_TABLE = getEnv({ name: 'MYSQL_TABLE' });

// get time data from yesterday till now
const format = 'YYYY-MM-DD HH:mm:ss';
const NOW = dayjs(Date.now());
const YESTERDAY = NOW.add(-1, 'day');

const query =
'SELECT * FROM `' +
MYSQL_TABLE +
'` WHERE authDateTime >= "' +
YESTERDAY.format(format) +
'" AND authDateTime <= "' +
NOW.format(format) +
'" ORDER by ID, authDateTime';

return await connectAndQueryFromMySql(subdomain, query);
};

export default {
handleDailyJob: async ({ subdomain }) => {
await connectAndImportFromMysql(subdomain);
}
};
30 changes: 18 additions & 12 deletions packages/plugin-timeclock-api/src/graphql/resolvers/mutations.ts
Expand Up @@ -7,7 +7,7 @@ import {
ITimeClock,
IAbsenceType
} from '../../models/definitions/timeclock';
import { findBranches } from './utils';
import { connectAndImportFromMysql, findBranches } from './utils';

interface ITimeClockEdit extends ITimeClock {
_id: string;
Expand Down Expand Up @@ -40,15 +40,15 @@ const timeclockMutations = {
*/
async timeclockStart(
_root,
{ userId, longitude, latitude },
{ userId, longitude, latitude, deviceType },
{ models, user, subdomain }: IContext
) {
// convert long, lat into radians
const longRad = (Math.PI * longitude) / 180;
const latRad = (latitude * Math.PI) / 180;

let insideCoordinate = false;

let getBranchName;
const EARTH_RADIUS = 6378.14;
const branches = await findBranches(subdomain, user._id);

Expand Down Expand Up @@ -76,6 +76,7 @@ const timeclockMutations = {
// if user's coordinate is within the radius
if (dist * 1000 <= branch.radius) {
insideCoordinate = true;
getBranchName = branch.title;
}
}

Expand All @@ -85,7 +86,9 @@ const timeclockMutations = {
timeclock = await models.Timeclocks.createTimeClock({
shiftStart: new Date(),
shiftActive: true,
userId: userId ? `${userId}` : user._id
userId: userId ? `${userId}` : user._id,
branchName: getBranchName,
deviceType: `${deviceType}`
});
} else {
throw new Error('User not in the coordinate');
Expand All @@ -96,7 +99,7 @@ const timeclockMutations = {

async timeclockStop(
_root,
{ _id, userId, longitude, latitude, ...doc }: ITimeClockEdit,
{ _id, userId, longitude, latitude, deviceType, ...doc }: ITimeClockEdit,
{ models, subdomain, user }: IContext
) {
const timeclock = await models.Timeclocks.findOne({
Expand Down Expand Up @@ -144,9 +147,14 @@ const timeclockMutations = {
let updated;

if (insideCoordinate) {
const getShiftStartDeviceType = (
await models.Timeclocks.getTimeClock(_id)
).deviceType;

updated = await models.Timeclocks.updateTimeClock(_id, {
shiftEnd: new Date(),
shiftActive: false,
deviceType: getShiftStartDeviceType + ' + ' + deviceType,
...doc
});
} else {
Expand Down Expand Up @@ -384,13 +392,6 @@ const timeclockMutations = {
{ _id, name, startDate, endDate, doc },
{ models }: IContext
) {
// const updated = models.Absences.updateAbsence(_id, {
// holidayName: name,
// startTime: startDate,
// endTime: endDate,
// status: 'Holiday',
// ...doc
// });
return models.Absences.updateAbsence(_id, {
holidayName: name,
startTime: startDate,
Expand All @@ -402,6 +403,11 @@ const timeclockMutations = {

holidayRemove(_root, { _id }, { models }: IContext) {
return models.Absences.removeAbsence(_id);
},

async extractAllDataFromMySQL(_root, {}, { subdomain }: IContext) {
const ret = await connectAndImportFromMysql(subdomain);
return ret;
}
};

Expand Down
9 changes: 9 additions & 0 deletions packages/plugin-timeclock-api/src/graphql/resolvers/utils.ts
@@ -1,6 +1,8 @@
import { IModels } from '../../connectionResolver';
import { sendCoreMessage } from '../../messageBroker';
import { connectAndQueryFromMySql } from '../../utils';
import { IUserReport } from '../../models/definitions/timeclock';
import { getEnv } from '@erxes/api-utils/src';

export const findDepartment = async (subdomain: string, target) => {
const department = await sendCoreMessage({
Expand Down Expand Up @@ -216,3 +218,10 @@ export const returnReportByUserIds = async (
groupTotalMinsScheduled
];
};

export const connectAndImportFromMysql = async (subdomain: string) => {
const MYSQL_TABLE = getEnv({ name: 'MYSQL_TABLE' });
const query = 'select * from `' + MYSQL_TABLE + '` order by ID, authDateTime';

return await connectAndQueryFromMySql(subdomain, query);
};
7 changes: 7 additions & 0 deletions packages/plugin-timeclock-api/src/graphql/schema.ts
Expand Up @@ -16,6 +16,11 @@ export const types = `
shiftStart: Date
shiftEnd: Date
shiftActive: Boolean
employeeUserName: String
branchName: String
deviceName: String
employeeId: Int
deviceType: String
}
type Absence {
Expand Down Expand Up @@ -123,6 +128,7 @@ const params = `
_id: String
longitude: Float
latitude: Float
deviceType: String
`;

const absence_params = `
Expand Down Expand Up @@ -166,4 +172,5 @@ export const mutations = `
holidayRemove(_id: String): JSON
scheduleRemove(_id: String): JSON
scheduleShiftRemove(_id: String): JSON
extractAllDataFromMySQL: [Timeclock]
`;
11 changes: 11 additions & 0 deletions packages/plugin-timeclock-api/src/messageBroker.ts
Expand Up @@ -16,6 +16,17 @@ export const sendCoreMessage = async (args: ISendMessageArgs): Promise<any> => {
});
};

export const sendFormsMessage = async (
args: ISendMessageArgs
): Promise<any> => {
return sendMessage({
client,
serviceDiscovery,
serviceName: 'forms',
...args
});
};

export default function() {
return client;
}

0 comments on commit 46c7faf

Please sign in to comment.