phase 1 backend
This commit is contained in:
parent
a0897c2d38
commit
9653e55453
26 changed files with 3225 additions and 0 deletions
130
README.md
Normal file
130
README.md
Normal file
|
@ -0,0 +1,130 @@
|
||||||
|
# JobIA - Votre plateforme de recherche d'emploi intelligente
|
||||||
|
|
||||||
|
[](https://opensource.org/licenses/MIT)
|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
**JobIA** est une plateforme de recherche d'emploi innovante qui vous aide à trouver les opportunités parfaites en exploitant la puissance de l'intelligence artificielle. En intégrant les offres de France Travail et des outils d'IA avancés, JobIA simplifie votre recherche d'emploi et vous accompagne dans la création de candidatures percutantes.
|
||||||
|
|
||||||
|
## Fonctionnalités principales (MVP)
|
||||||
|
|
||||||
|
* **Recherche et filtrage avancés :** Trouvez facilement des offres grâce à une recherche intuitive et des filtres précis (localisation, type de contrat, secteur, etc.).
|
||||||
|
* **Gestion des utilisateurs :** Créez un compte, connectez-vous et gérez votre profil.
|
||||||
|
* **Sauvegarde des offres favorites :** Conservez les offres qui vous intéressent pour ne pas les perdre.
|
||||||
|
* **Alertes email personnalisées :** Soyez informé des nouvelles offres correspondant à vos critères de recherche.
|
||||||
|
* **Note de compatibilité IA :** Évaluez la pertinence d'une offre par rapport à votre profil grâce à une analyse intelligente basée sur Gemini ou Mistral.
|
||||||
|
* **Espace personnel :** Gérez vos offres favorites et vos alertes en un seul endroit.
|
||||||
|
* **Aide à la rédaction de lettre de motivation IA :** Générez des lettres de motivation personnalisées et efficaces en quelques clics grâce à l'IA.
|
||||||
|
|
||||||
|
## Technologies utilisées
|
||||||
|
|
||||||
|
* **Frontend (`frontend` dossier) :** [Next.js](https://nextjs.org/) (framework React pour le rendu côté serveur et les applications web), [TypeScript](https://www.typescriptlang.org/) (sur-ensemble typé de JavaScript), [Tailwind CSS](https://tailwindcss.com/) (framework CSS utilitaire), [Zustand](https://zustand.pmnd.rs/) (bibliothèque de gestion d'état simple et rapide).
|
||||||
|
* **Backend (`backend` dossier) :** [Node.js](https://nodejs.org/en/) (environnement d'exécution JavaScript côté serveur), [Express](https://expressjs.com/) ou (frameworks Node.js pour la création d'API), [TypeScript](https://www.typescriptlang.org/).
|
||||||
|
* **Base de données :** [PostgreSQL](https://www.postgresql.org/).
|
||||||
|
* **ORM (Optionnel) :** [Prisma](https://www.prisma.io/)(pour faciliter l'interaction avec la base de données).
|
||||||
|
* **Intégration API :**
|
||||||
|
* [API France Travail](https://www.francetravail.fr/emploi/offres/) (pour la récupération des offres d'emploi).
|
||||||
|
* [API Gemini](https://ai.google.dev/products/gemini) ou [API Mistral](https://mistral.ai/) (pour les fonctionnalités d'IA).
|
||||||
|
|
||||||
|
## Installation (pour le développement local)
|
||||||
|
|
||||||
|
1. **Cloner le repository :**
|
||||||
|
```bash
|
||||||
|
git clone <URL_DU_REPOSITORY>
|
||||||
|
cd jobia
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Installer les dépendances du backend :**
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npm install
|
||||||
|
# ou
|
||||||
|
yarn install
|
||||||
|
# ou
|
||||||
|
pnpm install
|
||||||
|
cd ..
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Installer les dépendances du frontend :**
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
# ou
|
||||||
|
yarn install
|
||||||
|
# ou
|
||||||
|
pnpm install
|
||||||
|
cd ..
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Configurer les variables d'environnement :**
|
||||||
|
Créez un fichier `.env.local` dans chaque dossier (`backend` et `frontend`) et configurez les variables d'environnement nécessaires.
|
||||||
|
|
||||||
|
**`backend/.env.local` :**
|
||||||
|
```env
|
||||||
|
DATABASE_URL=votre_url_postgresql
|
||||||
|
FRANCE_TRAVAIL_CLIENT_ID=votre_client_id_france_travail
|
||||||
|
FRANCE_TRAVAIL_CLIENT_SECRET=votre_client_secret_france_travail
|
||||||
|
GEMINI_API_KEY=votre_cle_api_gemini # ou MISTRAL_API_KEY=votre_cle_api_mistral
|
||||||
|
# ... autres variables backend
|
||||||
|
```
|
||||||
|
|
||||||
|
**`frontend/.env.local` :**
|
||||||
|
```env
|
||||||
|
NEXT_PUBLIC_BACKEND_URL=http://localhost:8000/api # L'URL de votre backend
|
||||||
|
NEXTAUTH_SECRET=un_secret_aleatoire_pour_nextauth
|
||||||
|
NEXTAUTH_URL=http://localhost:3000 # ou l'URL de votre environnement frontend
|
||||||
|
# ... autres variables frontend
|
||||||
|
```
|
||||||
|
**Important :** Assurez-vous de sécuriser vos clés API et autres informations sensibles.
|
||||||
|
|
||||||
|
5. **Lancer les serveurs de développement :**
|
||||||
|
|
||||||
|
**Backend :**
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npm run dev # ou yarn dev ou pnpm dev (la commande peut varier selon votre configuration backend)
|
||||||
|
cd ..
|
||||||
|
```
|
||||||
|
(Assurez-vous que votre serveur backend s'exécute sur le port spécifié dans `NEXT_PUBLIC_BACKEND_URL` ou ajustez la variable en conséquence).
|
||||||
|
|
||||||
|
**Frontend :**
|
||||||
|
```bash
|
||||||
|
cd frontend
|
||||||
|
npm run dev
|
||||||
|
# ou
|
||||||
|
yarn dev
|
||||||
|
# ou
|
||||||
|
pnpm dev
|
||||||
|
cd ..
|
||||||
|
```
|
||||||
|
|
||||||
|
Ouvrez votre navigateur sur `http://localhost:3000` pour voir l'application frontend.
|
||||||
|
|
||||||
|
## Déploiement
|
||||||
|
|
||||||
|
Les instructions de déploiement dépendront de la plateforme que vous choisissez pour le frontend (Vercel, Netlify, etc.) et le backend (Heroku, AWS, etc.). Consultez la documentation de chaque plateforme pour plus d'informations. Assurez-vous de configurer correctement les variables d'environnement dans vos environnements de production respectifs.
|
||||||
|
|
||||||
|
## Contribution
|
||||||
|
|
||||||
|
Les contributions sont les bienvenues ! Si vous souhaitez contribuer au projet, veuillez suivre les étapes suivantes :
|
||||||
|
|
||||||
|
1. Fork le repository.
|
||||||
|
2. Créez une branche pour votre fonctionnalité (`git checkout -b feature/nouvelle-fonctionnalite`).
|
||||||
|
3. Commitez vos changements (`git commit -m 'Ajout de la nouvelle fonctionnalité'`).
|
||||||
|
4. Pushez la branche (`git push origin feature/nouvelle-fonctionnalite`).
|
||||||
|
5. Ouvrez une pull request.
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
Ce projet est sous licence [MIT](https://opensource.org/licenses/MIT).
|
||||||
|
|
||||||
|
## Contact
|
||||||
|
|
||||||
|
Pour toute question ou suggestion, n'hésitez pas à ouvrir une issue sur ce repository.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**JobIA - Trouvez l'emploi qui vous correspond, intelligemment.**
|
3
backend/.gitignore
vendored
Normal file
3
backend/.gitignore
vendored
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
node_modules
|
||||||
|
# Keep environment variables out of version control
|
||||||
|
.env
|
45
backend/dist/controllers/jobIngestionController.js
vendored
Normal file
45
backend/dist/controllers/jobIngestionController.js
vendored
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.ingestJobOffers = void 0;
|
||||||
|
const client_1 = require("@prisma/client");
|
||||||
|
const FranceTravailService_1 = __importDefault(require("../services/FranceTravailService"));
|
||||||
|
const prisma = new client_1.PrismaClient();
|
||||||
|
const ingestJobOffers = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const jobOffers = await FranceTravailService_1.default.getJobOffers({ range: '0-149' });
|
||||||
|
for (const offre of jobOffers.resultats) {
|
||||||
|
const mappedOffer = {
|
||||||
|
id: offre.id,
|
||||||
|
title: offre.intitule,
|
||||||
|
description: offre.description,
|
||||||
|
publicationDate: new Date(offre.dateCreation),
|
||||||
|
romeCode: offre.romeCode,
|
||||||
|
romeLabel: offre.romeLibelle,
|
||||||
|
locationLabel: offre.lieuTravail?.libelle || null,
|
||||||
|
postalCode: offre.lieuTravail?.codePostal || null,
|
||||||
|
departmentCode: offre.lieuTravail?.codeDepartement || null,
|
||||||
|
cityName: offre.lieuTravail?.ville || null,
|
||||||
|
companyName: offre.entreprise?.nom || null,
|
||||||
|
contractType: offre.typeContrat,
|
||||||
|
contractLabel: offre.libelleTypeContrat,
|
||||||
|
};
|
||||||
|
await prisma.jobOffer.upsert({
|
||||||
|
where: { id: mappedOffer.id },
|
||||||
|
update: mappedOffer,
|
||||||
|
create: mappedOffer,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
res.status(200).json({
|
||||||
|
message: 'Job offers ingested successfully',
|
||||||
|
count: jobOffers.resultats.length,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.error('Error ingesting job offers:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to ingest job offers' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
exports.ingestJobOffers = ingestJobOffers;
|
71
backend/dist/controllers/jobSearchController.js
vendored
Normal file
71
backend/dist/controllers/jobSearchController.js
vendored
Normal file
|
@ -0,0 +1,71 @@
|
||||||
|
"use strict";
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.searchLocalJobOffers = void 0;
|
||||||
|
const client_1 = require("@prisma/client");
|
||||||
|
const prisma = new client_1.PrismaClient();
|
||||||
|
const searchLocalJobOffers = async (req, res) => {
|
||||||
|
try {
|
||||||
|
const page = parseInt(req.query.page) || 1;
|
||||||
|
const limit = parseInt(req.query.limit) || 10;
|
||||||
|
const skip = (page - 1) * limit;
|
||||||
|
const take = limit;
|
||||||
|
const sortBy = req.query.sortBy || 'publicationDate';
|
||||||
|
const sortOrder = req.query.sortOrder || 'desc';
|
||||||
|
const keyword = req.query.keyword;
|
||||||
|
const location = req.query.location;
|
||||||
|
const contractType = req.query.contractType;
|
||||||
|
console.log('Keyword:', keyword);
|
||||||
|
console.log('Location:', location);
|
||||||
|
const where = {};
|
||||||
|
if (keyword) {
|
||||||
|
where.OR = [
|
||||||
|
{ title: { contains: keyword, mode: 'insensitive' } },
|
||||||
|
{ description: { contains: keyword, mode: 'insensitive' } },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (location) {
|
||||||
|
where.AND = [
|
||||||
|
...(where.AND || []),
|
||||||
|
{
|
||||||
|
OR: [
|
||||||
|
{ locationLabel: { contains: location, mode: 'insensitive' } },
|
||||||
|
{ postalCode: { contains: location, mode: 'insensitive' } },
|
||||||
|
{ cityName: { contains: location, mode: 'insensitive' } },
|
||||||
|
{ departmentCode: { contains: location, mode: 'insensitive' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (contractType) {
|
||||||
|
where.AND = [
|
||||||
|
...(where.AND || []),
|
||||||
|
{ contractType: contractType },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
const orderBy = {};
|
||||||
|
if (sortBy) {
|
||||||
|
orderBy[sortBy] = sortOrder === 'asc' ? 'asc' : 'desc';
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
orderBy.publicationDate = 'desc'; // Tri par défaut
|
||||||
|
}
|
||||||
|
const jobs = await prisma.jobOffer.findMany({
|
||||||
|
skip,
|
||||||
|
take,
|
||||||
|
where,
|
||||||
|
orderBy,
|
||||||
|
});
|
||||||
|
const total = await prisma.jobOffer.count({ where });
|
||||||
|
res.status(200).json({
|
||||||
|
jobs,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.error('Error searching job offers:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to search job offers' });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
exports.searchLocalJobOffers = searchLocalJobOffers;
|
18
backend/dist/index.js
vendored
Normal file
18
backend/dist/index.js
vendored
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const express_1 = __importDefault(require("express"));
|
||||||
|
const dotenv_1 = __importDefault(require("dotenv"));
|
||||||
|
const jobIngestionRoutes_1 = __importDefault(require("./routes/jobIngestionRoutes"));
|
||||||
|
const jobSearchRoutes_1 = __importDefault(require("./routes/jobSearchRoutes"));
|
||||||
|
dotenv_1.default.config();
|
||||||
|
const app = (0, express_1.default)();
|
||||||
|
const PORT = process.env.PORT || 3000;
|
||||||
|
app.use(express_1.default.json());
|
||||||
|
app.use(jobIngestionRoutes_1.default);
|
||||||
|
app.use(jobSearchRoutes_1.default);
|
||||||
|
app.listen(PORT, () => {
|
||||||
|
console.log(`Server is running on port ${PORT}`);
|
||||||
|
});
|
10
backend/dist/routes/jobIngestionRoutes.js
vendored
Normal file
10
backend/dist/routes/jobIngestionRoutes.js
vendored
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const express_1 = __importDefault(require("express"));
|
||||||
|
const jobIngestionController_1 = require("../controllers/jobIngestionController");
|
||||||
|
const router = express_1.default.Router();
|
||||||
|
router.post('/api/ingest-jobs', jobIngestionController_1.ingestJobOffers);
|
||||||
|
exports.default = router;
|
10
backend/dist/routes/jobSearchRoutes.js
vendored
Normal file
10
backend/dist/routes/jobSearchRoutes.js
vendored
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const express_1 = __importDefault(require("express"));
|
||||||
|
const jobSearchController_1 = require("../controllers/jobSearchController");
|
||||||
|
const router = express_1.default.Router();
|
||||||
|
router.get('/api/jobs', jobSearchController_1.searchLocalJobOffers);
|
||||||
|
exports.default = router;
|
67
backend/dist/services/FranceTravailService.js
vendored
Normal file
67
backend/dist/services/FranceTravailService.js
vendored
Normal file
|
@ -0,0 +1,67 @@
|
||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const axios_1 = __importDefault(require("axios"));
|
||||||
|
class FranceTravailService {
|
||||||
|
constructor() {
|
||||||
|
this.accessToken = null;
|
||||||
|
this.tokenExpiration = null;
|
||||||
|
this.realm = '/partenaire';
|
||||||
|
this.clientId = process.env.FRANCE_TRAVAIL_CLIENT_ID || '';
|
||||||
|
this.clientSecret = process.env.FRANCE_TRAVAIL_CLIENT_SECRET || '';
|
||||||
|
this.tokenUrl = process.env.FRANCE_TRAVAIL_TOKEN_URL || '';
|
||||||
|
this.apiUrl = process.env.FRANCE_TRAVAIL_API_URL || '';
|
||||||
|
this.scope = process.env.FRANCE_TRAVAIL_SCOPE || '';
|
||||||
|
}
|
||||||
|
async authenticate() {
|
||||||
|
try {
|
||||||
|
const response = await axios_1.default.post(this.tokenUrl, null, {
|
||||||
|
params: {
|
||||||
|
realm: this.realm,
|
||||||
|
grant_type: 'client_credentials',
|
||||||
|
client_id: this.clientId,
|
||||||
|
client_secret: this.clientSecret,
|
||||||
|
scope: this.scope,
|
||||||
|
},
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.accessToken = response.data.access_token;
|
||||||
|
this.tokenExpiration = Date.now() + response.data.expires_in * 1000;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
const axiosError = error;
|
||||||
|
console.error('Authentication failed:', axiosError.response?.data || axiosError.message);
|
||||||
|
throw new Error('Failed to authenticate with France Travail API');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async ensureValidToken() {
|
||||||
|
if (!this.accessToken || (this.tokenExpiration && Date.now() >= this.tokenExpiration)) {
|
||||||
|
await this.authenticate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async getJobOffers(params) {
|
||||||
|
await this.ensureValidToken();
|
||||||
|
try {
|
||||||
|
const response = await axios_1.default.get(this.apiUrl, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${this.accessToken}`,
|
||||||
|
},
|
||||||
|
params: {
|
||||||
|
...params,
|
||||||
|
range: params?.range || '0-9', // Default range for pagination
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
const axiosError = error;
|
||||||
|
console.error('Failed to fetch job offers:', axiosError.response?.data || axiosError.message);
|
||||||
|
throw new Error('Failed to fetch job offers from France Travail API');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.default = new FranceTravailService();
|
2154
backend/package-lock.json
generated
Normal file
2154
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
28
backend/package.json
Normal file
28
backend/package.json
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
{
|
||||||
|
"name": "backend",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "",
|
||||||
|
"main": "index.js",
|
||||||
|
"scripts": {
|
||||||
|
"start": "ts-node-dev --respawn --transpile-only src/index.ts",
|
||||||
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
|
},
|
||||||
|
"keywords": [],
|
||||||
|
"author": "",
|
||||||
|
"license": "ISC",
|
||||||
|
"type": "commonjs",
|
||||||
|
"dependencies": {
|
||||||
|
"typescript": "^5.8.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@prisma/client": "^6.8.2",
|
||||||
|
"@types/express": "^5.0.2",
|
||||||
|
"@types/node": "^22.15.21",
|
||||||
|
"axios": "^1.9.0",
|
||||||
|
"dotenv": "^16.5.0",
|
||||||
|
"express": "^5.1.0",
|
||||||
|
"pg": "^8.16.0",
|
||||||
|
"prisma": "^6.8.2",
|
||||||
|
"ts-node-dev": "^2.0.0"
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "User" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"name" TEXT,
|
||||||
|
|
||||||
|
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "JobOffer" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"description" TEXT NOT NULL,
|
||||||
|
"dateCreation" TIMESTAMP(3) NOT NULL,
|
||||||
|
"romeCode" TEXT,
|
||||||
|
"romeLabel" TEXT,
|
||||||
|
"lieuTravailLibelle" TEXT,
|
||||||
|
"postalCode" TEXT,
|
||||||
|
"departmentCode" TEXT,
|
||||||
|
"cityName" TEXT,
|
||||||
|
"entrepriseNom" TEXT,
|
||||||
|
"contractType" TEXT,
|
||||||
|
"contractLabel" TEXT,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "JobOffer_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "JobOffer_id_key" ON "JobOffer"("id");
|
3
backend/prisma/migrations/migration_lock.toml
Normal file
3
backend/prisma/migrations/migration_lock.toml
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "postgresql"
|
56
backend/prisma/schema.prisma
Normal file
56
backend/prisma/schema.prisma
Normal file
|
@ -0,0 +1,56 @@
|
||||||
|
// This is your Prisma schema file,
|
||||||
|
// learn more about it in the docs: https://pris.ly/d/prisma-schema
|
||||||
|
|
||||||
|
// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
|
||||||
|
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "postgresql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
model User {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
email String @unique
|
||||||
|
name String?
|
||||||
|
}
|
||||||
|
|
||||||
|
model JobOffer {
|
||||||
|
// Identifiant unique de l'offre (celui de l'API France Travail)
|
||||||
|
id String @id @unique
|
||||||
|
|
||||||
|
// Informations principales
|
||||||
|
title String
|
||||||
|
description String @db.Text // Utiliser Text pour de longues descriptions
|
||||||
|
publicationDate DateTime @map("dateCreation") // La date de création de l'offre, mappée du champ de l'API
|
||||||
|
romeCode String? // Code ROME (peut être optionnel si non toujours présent)
|
||||||
|
romeLabel String? // Libellé du code ROME
|
||||||
|
|
||||||
|
// Informations sur le lieu de travail
|
||||||
|
locationLabel String? @map("lieuTravailLibelle") // ex: "Paris (75)" ou "Lyon (69)"
|
||||||
|
postalCode String?
|
||||||
|
departmentCode String?
|
||||||
|
cityName String?
|
||||||
|
|
||||||
|
// Informations sur l'entreprise
|
||||||
|
companyName String? @map("entrepriseNom") // Nom de l'entreprise (peut être non renseigné)
|
||||||
|
|
||||||
|
// Type de contrat
|
||||||
|
contractType String?
|
||||||
|
contractLabel String? // Libellé du type de contrat
|
||||||
|
|
||||||
|
// Autres champs pertinents si tu les as identifiés dans l'API et que tu souhaites les stocker
|
||||||
|
// Par exemple:
|
||||||
|
// duration String? // Durée du contrat
|
||||||
|
// offerUrl String? // URL directe de l'offre sur France Travail
|
||||||
|
|
||||||
|
// Champs de métadonnées pour notre base de données
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
// Tu pourras ajouter des relations ici plus tard (ex: avec un modèle User ou Favorite)
|
||||||
|
}
|
55
backend/src/controllers/jobIngestionController.js
Normal file
55
backend/src/controllers/jobIngestionController.js
Normal file
|
@ -0,0 +1,55 @@
|
||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.ingestJobOffers = void 0;
|
||||||
|
const client_1 = require("@prisma/client");
|
||||||
|
const FranceTravailService_1 = __importDefault(require("../services/FranceTravailService"));
|
||||||
|
const prisma = new client_1.PrismaClient();
|
||||||
|
const ingestJobOffers = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||||
|
var _a, _b, _c, _d, _e;
|
||||||
|
try {
|
||||||
|
const jobOffers = yield FranceTravailService_1.default.getJobOffers({ range: '0-149' });
|
||||||
|
for (const offre of jobOffers.resultats) {
|
||||||
|
const mappedOffer = {
|
||||||
|
id: offre.id,
|
||||||
|
title: offre.intitule,
|
||||||
|
description: offre.description,
|
||||||
|
publicationDate: new Date(offre.dateCreation),
|
||||||
|
romeCode: offre.romeCode,
|
||||||
|
romeLabel: offre.romeLibelle,
|
||||||
|
locationLabel: ((_a = offre.lieuTravail) === null || _a === void 0 ? void 0 : _a.libelle) || null,
|
||||||
|
postalCode: ((_b = offre.lieuTravail) === null || _b === void 0 ? void 0 : _b.codePostal) || null,
|
||||||
|
departmentCode: ((_c = offre.lieuTravail) === null || _c === void 0 ? void 0 : _c.codeDepartement) || null,
|
||||||
|
cityName: ((_d = offre.lieuTravail) === null || _d === void 0 ? void 0 : _d.ville) || null,
|
||||||
|
companyName: ((_e = offre.entreprise) === null || _e === void 0 ? void 0 : _e.nom) || null,
|
||||||
|
contractType: offre.typeContrat,
|
||||||
|
contractLabel: offre.libelleTypeContrat,
|
||||||
|
};
|
||||||
|
yield prisma.jobOffer.upsert({
|
||||||
|
where: { id: mappedOffer.id },
|
||||||
|
update: mappedOffer,
|
||||||
|
create: mappedOffer,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
res.status(200).json({
|
||||||
|
message: 'Job offers ingested successfully',
|
||||||
|
count: jobOffers.resultats.length,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.error('Error ingesting job offers:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to ingest job offers' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
exports.ingestJobOffers = ingestJobOffers;
|
43
backend/src/controllers/jobIngestionController.ts
Normal file
43
backend/src/controllers/jobIngestionController.ts
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import FranceTravailService from '../services/FranceTravailService';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
export const ingestJobOffers = async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const jobOffers = await FranceTravailService.getJobOffers({ range: '0-149' });
|
||||||
|
|
||||||
|
for (const offre of jobOffers.resultats) {
|
||||||
|
const mappedOffer = {
|
||||||
|
id: offre.id,
|
||||||
|
title: offre.intitule,
|
||||||
|
description: offre.description,
|
||||||
|
publicationDate: new Date(offre.dateCreation),
|
||||||
|
romeCode: offre.romeCode,
|
||||||
|
romeLabel: offre.romeLibelle,
|
||||||
|
locationLabel: offre.lieuTravail?.libelle || null,
|
||||||
|
postalCode: offre.lieuTravail?.codePostal || null,
|
||||||
|
departmentCode: offre.lieuTravail?.codeDepartement || null,
|
||||||
|
cityName: offre.lieuTravail?.ville || null,
|
||||||
|
companyName: offre.entreprise?.nom || null,
|
||||||
|
contractType: offre.typeContrat,
|
||||||
|
contractLabel: offre.libelleTypeContrat,
|
||||||
|
};
|
||||||
|
|
||||||
|
await prisma.jobOffer.upsert({
|
||||||
|
where: { id: mappedOffer.id },
|
||||||
|
update: mappedOffer,
|
||||||
|
create: mappedOffer,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
message: 'Job offers ingested successfully',
|
||||||
|
count: jobOffers.resultats.length,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error ingesting job offers:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to ingest job offers' });
|
||||||
|
}
|
||||||
|
};
|
78
backend/src/controllers/jobSearchController.js
Normal file
78
backend/src/controllers/jobSearchController.js
Normal file
|
@ -0,0 +1,78 @@
|
||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.searchLocalJobOffers = void 0;
|
||||||
|
const client_1 = require("@prisma/client");
|
||||||
|
const prisma = new client_1.PrismaClient();
|
||||||
|
const searchLocalJobOffers = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
||||||
|
try {
|
||||||
|
const page = parseInt(req.query.page) || 1;
|
||||||
|
const limit = parseInt(req.query.limit) || 10;
|
||||||
|
const skip = (page - 1) * limit;
|
||||||
|
const take = limit;
|
||||||
|
const sortBy = req.query.sortBy || 'publicationDate';
|
||||||
|
const sortOrder = req.query.sortOrder || 'desc';
|
||||||
|
const keyword = req.query.keyword;
|
||||||
|
const location = req.query.location;
|
||||||
|
const contractType = req.query.contractType;
|
||||||
|
const where = {};
|
||||||
|
if (keyword) {
|
||||||
|
where.OR = [
|
||||||
|
{ title: { contains: keyword, mode: 'insensitive' } },
|
||||||
|
{ description: { contains: keyword, mode: 'insensitive' } },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (location) {
|
||||||
|
where.AND = [
|
||||||
|
...(where.AND || []),
|
||||||
|
{
|
||||||
|
OR: [
|
||||||
|
{ locationLabel: { contains: location, mode: 'insensitive' } },
|
||||||
|
{ postalCode: { contains: location, mode: 'insensitive' } },
|
||||||
|
{ cityName: { contains: location, mode: 'insensitive' } },
|
||||||
|
{ departmentCode: { contains: location, mode: 'insensitive' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (contractType) {
|
||||||
|
where.AND = [
|
||||||
|
...(where.AND || []),
|
||||||
|
{ contractType: contractType },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
const orderBy = {};
|
||||||
|
if (sortBy) {
|
||||||
|
orderBy[sortBy] = sortOrder === 'asc' ? 'asc' : 'desc';
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
orderBy.publicationDate = 'desc'; // Tri par défaut
|
||||||
|
}
|
||||||
|
const jobs = yield prisma.jobOffer.findMany({
|
||||||
|
skip,
|
||||||
|
take,
|
||||||
|
where,
|
||||||
|
orderBy,
|
||||||
|
});
|
||||||
|
const total = yield prisma.jobOffer.count({ where });
|
||||||
|
res.status(200).json({
|
||||||
|
jobs,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.error('Error searching job offers:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to search job offers' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
exports.searchLocalJobOffers = searchLocalJobOffers;
|
74
backend/src/controllers/jobSearchController.ts
Normal file
74
backend/src/controllers/jobSearchController.ts
Normal file
|
@ -0,0 +1,74 @@
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
export const searchLocalJobOffers = async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const page = parseInt(req.query.page as string) || 1;
|
||||||
|
const limit = parseInt(req.query.limit as string) || 10;
|
||||||
|
const skip = (page - 1) * limit;
|
||||||
|
const take = limit;
|
||||||
|
const sortBy = req.query.sortBy as string || 'publicationDate';
|
||||||
|
const sortOrder = req.query.sortOrder as string || 'desc';
|
||||||
|
const keyword = req.query.keyword as string;
|
||||||
|
const location = req.query.location as string;
|
||||||
|
const contractType = req.query.contractType as string;
|
||||||
|
|
||||||
|
console.log('Keyword:', keyword);
|
||||||
|
console.log('Location:', location);
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
if (keyword) {
|
||||||
|
where.OR = [
|
||||||
|
{ title: { contains: keyword, mode: 'insensitive' } },
|
||||||
|
{ description: { contains: keyword, mode: 'insensitive' } },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (location) {
|
||||||
|
where.AND = [
|
||||||
|
...(where.AND || []),
|
||||||
|
{
|
||||||
|
OR: [
|
||||||
|
{ locationLabel: { contains: location, mode: 'insensitive' } },
|
||||||
|
{ postalCode: { contains: location, mode: 'insensitive' } },
|
||||||
|
{ cityName: { contains: location, mode: 'insensitive' } },
|
||||||
|
{ departmentCode: { contains: location, mode: 'insensitive' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
if (contractType) {
|
||||||
|
where.AND = [
|
||||||
|
...(where.AND || []),
|
||||||
|
{ contractType: contractType },
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const orderBy: any = {};
|
||||||
|
if (sortBy) {
|
||||||
|
orderBy[sortBy] = sortOrder === 'asc' ? 'asc' : 'desc';
|
||||||
|
} else {
|
||||||
|
orderBy.publicationDate = 'desc'; // Tri par défaut
|
||||||
|
}
|
||||||
|
|
||||||
|
const jobs = await prisma.jobOffer.findMany({
|
||||||
|
skip,
|
||||||
|
take,
|
||||||
|
where,
|
||||||
|
orderBy,
|
||||||
|
});
|
||||||
|
|
||||||
|
const total = await prisma.jobOffer.count({ where });
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
jobs,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error searching job offers:', error);
|
||||||
|
res.status(500).json({ error: 'Failed to search job offers' });
|
||||||
|
}
|
||||||
|
};
|
18
backend/src/index.js
Normal file
18
backend/src/index.js
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const express_1 = __importDefault(require("express"));
|
||||||
|
const dotenv_1 = __importDefault(require("dotenv"));
|
||||||
|
const jobIngestionRoutes_1 = __importDefault(require("./routes/jobIngestionRoutes"));
|
||||||
|
const jobSearchRoutes_1 = __importDefault(require("./routes/jobSearchRoutes"));
|
||||||
|
dotenv_1.default.config();
|
||||||
|
const app = (0, express_1.default)();
|
||||||
|
const PORT = process.env.PORT || 3000;
|
||||||
|
app.use(express_1.default.json());
|
||||||
|
app.use(jobIngestionRoutes_1.default);
|
||||||
|
app.use(jobSearchRoutes_1.default);
|
||||||
|
app.listen(PORT, () => {
|
||||||
|
console.log(`Server is running on port ${PORT}`);
|
||||||
|
});
|
18
backend/src/index.ts
Normal file
18
backend/src/index.ts
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
import express from 'express';
|
||||||
|
import dotenv from 'dotenv';
|
||||||
|
import jobIngestionRoutes from './routes/jobIngestionRoutes';
|
||||||
|
import jobSearchRoutes from './routes/jobSearchRoutes';
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
const PORT = process.env.PORT || 3000;
|
||||||
|
|
||||||
|
app.use(express.json());
|
||||||
|
|
||||||
|
app.use(jobIngestionRoutes);
|
||||||
|
app.use(jobSearchRoutes);
|
||||||
|
|
||||||
|
app.listen(PORT, () => {
|
||||||
|
console.log(`Server is running on port ${PORT}`);
|
||||||
|
});
|
10
backend/src/routes/jobIngestionRoutes.js
Normal file
10
backend/src/routes/jobIngestionRoutes.js
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const express_1 = __importDefault(require("express"));
|
||||||
|
const jobIngestionController_1 = require("../controllers/jobIngestionController");
|
||||||
|
const router = express_1.default.Router();
|
||||||
|
router.post('/api/ingest-jobs', jobIngestionController_1.ingestJobOffers);
|
||||||
|
exports.default = router;
|
8
backend/src/routes/jobIngestionRoutes.ts
Normal file
8
backend/src/routes/jobIngestionRoutes.ts
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
import express from 'express';
|
||||||
|
import { ingestJobOffers } from '../controllers/jobIngestionController';
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.post('/api/ingest-jobs', ingestJobOffers);
|
||||||
|
|
||||||
|
export default router;
|
10
backend/src/routes/jobSearchRoutes.js
Normal file
10
backend/src/routes/jobSearchRoutes.js
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const express_1 = __importDefault(require("express"));
|
||||||
|
const jobSearchController_1 = require("../controllers/jobSearchController");
|
||||||
|
const router = express_1.default.Router();
|
||||||
|
router.get('/api/jobs', jobSearchController_1.searchLocalJobOffers);
|
||||||
|
exports.default = router;
|
8
backend/src/routes/jobSearchRoutes.ts
Normal file
8
backend/src/routes/jobSearchRoutes.ts
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
import express from 'express';
|
||||||
|
import { searchLocalJobOffers } from '../controllers/jobSearchController';
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.get('/api/jobs', searchLocalJobOffers);
|
||||||
|
|
||||||
|
export default router;
|
81
backend/src/services/FranceTravailService.js
Normal file
81
backend/src/services/FranceTravailService.js
Normal file
|
@ -0,0 +1,81 @@
|
||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const axios_1 = __importDefault(require("axios"));
|
||||||
|
class FranceTravailService {
|
||||||
|
constructor() {
|
||||||
|
this.accessToken = null;
|
||||||
|
this.tokenExpiration = null;
|
||||||
|
this.realm = '/partenaire';
|
||||||
|
this.clientId = process.env.FRANCE_TRAVAIL_CLIENT_ID || '';
|
||||||
|
this.clientSecret = process.env.FRANCE_TRAVAIL_CLIENT_SECRET || '';
|
||||||
|
this.tokenUrl = process.env.FRANCE_TRAVAIL_TOKEN_URL || '';
|
||||||
|
this.apiUrl = process.env.FRANCE_TRAVAIL_API_URL || '';
|
||||||
|
this.scope = process.env.FRANCE_TRAVAIL_SCOPE || '';
|
||||||
|
}
|
||||||
|
authenticate() {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
var _a;
|
||||||
|
try {
|
||||||
|
const response = yield axios_1.default.post(this.tokenUrl, null, {
|
||||||
|
params: {
|
||||||
|
realm: this.realm,
|
||||||
|
grant_type: 'client_credentials',
|
||||||
|
client_id: this.clientId,
|
||||||
|
client_secret: this.clientSecret,
|
||||||
|
scope: this.scope,
|
||||||
|
},
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.accessToken = response.data.access_token;
|
||||||
|
this.tokenExpiration = Date.now() + response.data.expires_in * 1000;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
const axiosError = error;
|
||||||
|
console.error('Authentication failed:', ((_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.data) || axiosError.message);
|
||||||
|
throw new Error('Failed to authenticate with France Travail API');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
ensureValidToken() {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
if (!this.accessToken || (this.tokenExpiration && Date.now() >= this.tokenExpiration)) {
|
||||||
|
yield this.authenticate();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
getJobOffers(params) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
var _a;
|
||||||
|
yield this.ensureValidToken();
|
||||||
|
try {
|
||||||
|
const response = yield axios_1.default.get(this.apiUrl, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${this.accessToken}`,
|
||||||
|
},
|
||||||
|
params: Object.assign(Object.assign({}, params), { range: (params === null || params === void 0 ? void 0 : params.range) || '0-9' }),
|
||||||
|
});
|
||||||
|
return response.data;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
const axiosError = error;
|
||||||
|
console.error('Failed to fetch job offers:', ((_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.data) || axiosError.message);
|
||||||
|
throw new Error('Failed to fetch job offers from France Travail API');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exports.default = new FranceTravailService();
|
74
backend/src/services/FranceTravailService.ts
Normal file
74
backend/src/services/FranceTravailService.ts
Normal file
|
@ -0,0 +1,74 @@
|
||||||
|
import axios, { AxiosError } from 'axios';
|
||||||
|
|
||||||
|
class FranceTravailService {
|
||||||
|
private clientId: string;
|
||||||
|
private clientSecret: string;
|
||||||
|
private tokenUrl: string;
|
||||||
|
private apiUrl: string;
|
||||||
|
private scope: string;
|
||||||
|
private accessToken: string | null = null;
|
||||||
|
private tokenExpiration: number | null = null;
|
||||||
|
private realm: string = '/partenaire';
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.clientId = process.env.FRANCE_TRAVAIL_CLIENT_ID || '';
|
||||||
|
this.clientSecret = process.env.FRANCE_TRAVAIL_CLIENT_SECRET || '';
|
||||||
|
this.tokenUrl = process.env.FRANCE_TRAVAIL_TOKEN_URL || '';
|
||||||
|
this.apiUrl = process.env.FRANCE_TRAVAIL_API_URL || '';
|
||||||
|
this.scope = process.env.FRANCE_TRAVAIL_SCOPE || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
private async authenticate(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const response = await axios.post(this.tokenUrl, null, {
|
||||||
|
params: {
|
||||||
|
realm: this.realm,
|
||||||
|
grant_type: 'client_credentials',
|
||||||
|
client_id: this.clientId,
|
||||||
|
client_secret: this.clientSecret,
|
||||||
|
scope: this.scope,
|
||||||
|
},
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
this.accessToken = response.data.access_token;
|
||||||
|
this.tokenExpiration = Date.now() + response.data.expires_in * 1000;
|
||||||
|
} catch (error) {
|
||||||
|
const axiosError = error as AxiosError;
|
||||||
|
console.error('Authentication failed:', axiosError.response?.data || axiosError.message);
|
||||||
|
throw new Error('Failed to authenticate with France Travail API');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async ensureValidToken(): Promise<void> {
|
||||||
|
if (!this.accessToken || (this.tokenExpiration && Date.now() >= this.tokenExpiration)) {
|
||||||
|
await this.authenticate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getJobOffers(params?: any): Promise<any> {
|
||||||
|
await this.ensureValidToken();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await axios.get(this.apiUrl, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${this.accessToken}`,
|
||||||
|
},
|
||||||
|
params: {
|
||||||
|
...params,
|
||||||
|
range: params?.range || '0-9', // Default range for pagination
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
const axiosError = error as AxiosError;
|
||||||
|
console.error('Failed to fetch job offers:', axiosError.response?.data || axiosError.message);
|
||||||
|
throw new Error('Failed to fetch job offers from France Travail API');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default new FranceTravailService();
|
118
backend/tsconfig.json
Normal file
118
backend/tsconfig.json
Normal file
|
@ -0,0 +1,118 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||||
|
|
||||||
|
/* Projects */
|
||||||
|
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||||
|
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||||
|
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||||
|
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||||
|
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||||
|
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||||
|
|
||||||
|
/* Language and Environment */
|
||||||
|
"target": "ES2020",
|
||||||
|
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||||
|
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||||
|
// "libReplacement": true, /* Enable lib replacement. */
|
||||||
|
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||||
|
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||||
|
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||||
|
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||||
|
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||||
|
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||||
|
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||||
|
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||||
|
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||||
|
|
||||||
|
/* Modules */
|
||||||
|
"module": "commonjs",
|
||||||
|
"outDir": "./dist",
|
||||||
|
"rootDir": "./src",
|
||||||
|
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||||
|
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||||
|
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||||
|
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||||
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||||
|
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||||
|
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||||
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||||
|
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||||
|
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||||
|
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
|
||||||
|
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||||
|
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||||
|
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||||
|
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
|
||||||
|
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||||
|
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||||
|
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||||
|
|
||||||
|
/* JavaScript Support */
|
||||||
|
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||||
|
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||||
|
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||||
|
|
||||||
|
/* Emit */
|
||||||
|
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||||
|
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||||
|
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||||
|
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||||
|
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||||
|
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||||
|
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||||
|
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
||||||
|
// "removeComments": true, /* Disable emitting comments. */
|
||||||
|
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||||
|
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||||
|
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||||
|
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||||
|
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||||
|
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||||
|
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||||
|
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||||
|
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||||
|
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||||
|
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||||
|
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||||
|
|
||||||
|
/* Interop Constraints */
|
||||||
|
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||||
|
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||||
|
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
|
||||||
|
// "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */
|
||||||
|
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||||
|
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||||
|
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"strict": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
/* Type Checking */
|
||||||
|
"strict": true, /* Enable all strict type-checking options. */
|
||||||
|
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||||
|
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||||
|
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||||
|
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||||
|
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||||
|
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
|
||||||
|
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||||
|
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||||
|
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||||
|
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||||
|
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||||
|
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||||
|
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||||
|
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||||
|
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||||
|
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||||
|
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||||
|
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||||
|
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||||
|
|
||||||
|
/* Completeness */
|
||||||
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
|
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||||
|
}
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue