Skip to content

Commit

Permalink
[Bug]: #10 Employees page is taking too much time for loading .
Browse files Browse the repository at this point in the history
  • Loading branch information
Basi-mohd committed Nov 18, 2024
1 parent 48f6276 commit d6c86eb
Show file tree
Hide file tree
Showing 9 changed files with 387 additions and 206 deletions.
512 changes: 328 additions & 184 deletions server/package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon src/index.ts",
"dev": "nodemon --ignore src/common/exchangeRate.json src/index.ts",
"start": "npm run build && node ./dist/index.js",
"build": "rimraf ./dist && tsc",
"tsc": "tsc --watch"
Expand All @@ -17,6 +17,7 @@
"@aws-sdk/s3-request-presigner": "^3.688.0",
"@types/jsonwebtoken": "^9.0.6",
"aws-sdk": "^2.1692.0",
"axios": "^1.7.7",
"bcrypt": "^5.1.1",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
Expand All @@ -39,4 +40,4 @@
"ts-node": "^10.9.2",
"typescript": "^5.3.3"
}
}
}
1 change: 1 addition & 0 deletions server/src/common/exchangeRate.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"rate":3.64,"timestamp":1731926357882}
42 changes: 38 additions & 4 deletions server/src/common/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ObjectId } from "mongodb";
import { Filters } from "../interface/dashboard.interface";
import fs from 'fs';
import path from 'path';
import axios from "axios";


export const calculateDiscountPrice = (quotation: any, items: any): number => {
Expand Down Expand Up @@ -229,10 +230,15 @@ export const lastRangedMonths = (dateRange: any) => {


export async function getUSDRated() {
const url = 'https://latest.currency-api.pages.dev/v1/currencies/usd.min.json';
const response = await fetch(url);
const jsonResponse = await response.json();
return jsonResponse;
let rate = getCachedRate();

if (!rate) {
rate = await fetchExchangeRate();
} else {
console.log('Using cached exchange rate:', rate);
}

return rate;
}

export const removeFile = (fileName: string) => {
Expand All @@ -246,3 +252,31 @@ export const removeFile = (fileName: string) => {
}
});
};

const CACHE_FILE = path.join(__dirname, 'exchangeRate.json');
const API_URL = 'https://latest.currency-api.pages.dev/v1/currencies/usd.min.json'; // Replace with your actual API endpoint

export async function fetchExchangeRate() {
try {
const response = await axios.get(API_URL);
const rate = response.data.usd.qar;
cacheExchangeRate(rate);
return rate;
} catch (error) {
console.error('Error fetching exchange rate:', error);
return null;
}
}

function cacheExchangeRate(rate) {
const data = { rate, timestamp: Date.now() };
fs.writeFileSync(CACHE_FILE, JSON.stringify(data));
}

function getCachedRate() {
if (fs.existsSync(CACHE_FILE)) {
const data = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8'));
return data.rate;
}
return null;
}
16 changes: 6 additions & 10 deletions server/src/controllers/dashboard.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,7 @@ const getRevenueAchieved = async (access: string, userId: string, filters: Filte
break;
}

const USDRates = await getUSDRated();
const qatarUsdRate = USDRates.usd.qar;
const qatarUsdRate = await getUSDRated();

const currentDate = new Date();
const sevenDaysAgo = new Date(currentDate);
Expand Down Expand Up @@ -350,8 +349,7 @@ const getQuotations = async (access: string, userId: string, filters: Filters) =
const sevenDaysAgo = new Date(currentDate);
sevenDaysAgo.setDate(currentDate.getDate() - 7);

const USDRates = await getUSDRated();
const qatarUsdRate = USDRates.usd.qar;
const qatarUsdRate = await getUSDRated();

const quoteTotal = await quotationModel.aggregate([
{
Expand Down Expand Up @@ -539,8 +537,7 @@ const getAssignedJobs = async (access: string, userId: string, filters: Filters)
}


const USDRates = await getUSDRated();
const qatarUsdRate = USDRates.usd.qar;
const qatarUsdRate = await getUSDRated();


const assignedJobAwarded = await jobModel.aggregate([
Expand Down Expand Up @@ -675,8 +672,7 @@ export const getRevenuePerSalesperson = async (req: Request, res: Response, next
}


const USDRates = await getUSDRated();
const qatarUsdRates = USDRates.usd.qar;
const qatarUsdRates = await getUSDRated();


const jobTotal = await jobModel.aggregate([
Expand Down Expand Up @@ -789,8 +785,8 @@ export const getGrossProfitForLastSevenMonths = async (req: Request, res: Respon

const dateRange = getDateRange(filters.fromDate,filters.toDate)

const USDRates = await getUSDRated();
const qatarUsdRate = USDRates.usd.qar;
const qatarUsdRate = await getUSDRated();

let jobGrossProfit = [];
if(privileges.jobSheet.viewReport && privileges.jobSheet.viewReport !== 'none'){
jobGrossProfit = await jobModel.aggregate([
Expand Down
3 changes: 1 addition & 2 deletions server/src/controllers/employee.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,7 @@ export const getFilteredEmployees = async (req: Request, res: Response, next: Ne
}
})

const USDRates = await getUSDRated();
const qatarUsdRate = USDRates.usd.qar;
const qatarUsdRate = await getUSDRated();

const employeeData = await Employee.aggregate([
{
Expand Down
3 changes: 1 addition & 2 deletions server/src/controllers/job.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ export const jobList = async (req: Request, res: Response, next: NextFunction) =



const USDRates = await getUSDRated();
const qatarUsdRate = USDRates.usd.qar;
const qatarUsdRate = await getUSDRated();

const jobData = await jobModel.aggregate([
{
Expand Down
3 changes: 1 addition & 2 deletions server/src/controllers/quotation.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -991,9 +991,8 @@ export const getReportDetails = async (req: Request, res: Response) => {
value: totalValues.statusCounts[status]
}));

const USDRates = await getUSDRated();
const qatarUsdRates = await getUSDRated();

const qatarUsdRates = USDRates.usd.qar;
const tatalValue = totalValues.totalQARValue + (totalValues.totalUSDValue * qatarUsdRates);
const totalWonValue = totalValues.totalQARValue + (totalValues.totalUSDWonValue * qatarUsdRates);
const totalLossValue = totalValues.totalQARLossValue + (totalValues.totalUSDLossValue * qatarUsdRates);
Expand Down
8 changes: 8 additions & 0 deletions server/src/service/cronService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import employeeModel from "../models/employee.model";
import announcementModel from "../models/announcement.model";
import { fetchExchangeRate } from "../common/util";
const cron = require('node-cron');

const processEmployeeEvent = async (element, eventType) => {
Expand Down Expand Up @@ -84,6 +85,13 @@ const startCronJob = () => {
console.error('Cron job error:', error.message);
}
}).start();

fetchExchangeRate();

cron.schedule('0 */4 * * *', () => {
console.log('Updating exchange rate...');
fetchExchangeRate();
}).start();
};

export default startCronJob

0 comments on commit d6c86eb

Please sign in to comment.