breakhours-transform/api/jobs.js
2024-10-03 13:55:18 +02:00

85 lines
2.7 KiB
JavaScript

import express from 'express';
import fetch from 'node-fetch';
import { promises as fs } from 'fs';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import { convertToAmsterdamTime } from './utils.js';
import { PauzeManager } from '../services/PauzeManager.js';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const router = express.Router();
export const getJobs = async (req, res) => {
const apiKey = req.body.apiKey;
const apiProdUrl = `https://api.fleks.works/v1/jobs/?limit=100000&page=1&start_date=2024-06-26&isArchived=false`;
try {
const timeTableData = await fs.readFile(path.join('data', 'colorcrew_data_transformed_prod.json'), 'utf8');
const timeTable = JSON.parse(timeTableData);
const response = await fetch(apiProdUrl, {
headers: {
'x-api-key': apiKey
}
});
const data = await response.json();
const pauzeManager = new PauzeManager();
const updatedJobs = await pauzeManager.updateJobsWithPauze(data.results, timeTable, convertToAmsterdamTime);
await pauzeManager.updateJobsInDatabase(37, updatedJobs)
res.json({ amountOfJobs: updatedJobs.length, updatedJobs: updatedJobs });
} catch (error) {
console.log(error);
res.status(500).json({ error: 'Error fetching data' });
}
};
export const processAndUpdateJobs = async (req, res) => {
const { tenantId, jobs } = req.body;
if (!tenantId) {
return res.status(400).json({ error: 'Tenant ID is required' });
}
if (!jobs || !Array.isArray(jobs)) {
return res.status(400).json({ error: 'Error with fetching Jobs' });
}
try {
const timeTableData = await fs.readFile(path.join(__dirname, 'data', 'colorcrew_data_transformed_prod.json'), 'utf8');
const timeTable = JSON.parse(timeTableData);
const pauzeManager = new PauzeManager();
const updatedJobs = pauzeManager.updateJobsWithPauze(jobs, timeTable, convertToAmsterdamTime);
const result = await pauzeManager.updateJobsInDatabase(tenantId, updatedJobs);
res.json({ message: 'Jobs updated successfully.', result });
} catch (error) {
console.error('Error updating jobs:', error);
res.status(500).json({ error: 'Error updating jobs' });
}
};
export const removePauzeFromJobs = async (req, res) => {
const pauzeManager = new PauzeManager();
try {
await pauzeManager.removePauzeFromDatabase(8);
res.json({ message: 'Pauze removed from job descriptions successfully.' });
} catch (error) {
console.error('Error removing pauze from job descriptions:', error);
res.status(500).json({ error: 'Error removing pauze from job descriptions' });
}
};
export default router;