From 3a4c8bfeb0b7872f28974a7e8b4c6e18f16a09cb Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 12 May 2025 05:11:47 +0700 Subject: [PATCH] simpan histori --- backend/.env | 12 ++-- backend/controller/diagnosaController.js | 62 ++++++++++++++++- backend/middleware/roleMiddleware.js | 7 ++ .../20250511153136-create-histori.js | 66 +++++++++++++++++++ backend/models/histori.js | 66 +++++++++++++++++++ backend/routes/diagnosaRoutes.js | 5 +- 6 files changed, 210 insertions(+), 8 deletions(-) create mode 100644 backend/migrations/20250511153136-create-histori.js create mode 100644 backend/models/histori.js diff --git a/backend/.env b/backend/.env index a6d84d0..d688bd8 100644 --- a/backend/.env +++ b/backend/.env @@ -4,9 +4,9 @@ DB_USER=root DB_NAME=sibayam API_URL=http://localhost:5000 JWT_SECRET=2c5t0ny38989t03cr4ny904r8xy12jc -EMAIL_HOST=email_host -EMAIL_PORT=2525 -EMAIL_USER=email_user -EMAIL_PASS=email_pass -SENDGRID_API_KEY=your_send_grid_api_key -EMAIL_FROM=sibayam52@gmail.com \ No newline at end of file +EMAIL_HOST=sandbox.smtp.mailtrap.io +EMAIL_PORT="" +EMAIL_USER="" +EMAIL_PASS="" +SENDGRID_API_KEY="" +EMAIL_FROM="" \ No newline at end of file diff --git a/backend/controller/diagnosaController.js b/backend/controller/diagnosaController.js index 985e8ae..2029f71 100644 --- a/backend/controller/diagnosaController.js +++ b/backend/controller/diagnosaController.js @@ -1,7 +1,10 @@ -const { Rule_penyakit, Rule_hama, Gejala, Penyakit, Hama } = require('../models'); +const { Rule_penyakit, Rule_hama, Gejala, Penyakit, Hama, Histori } = require('../models'); +const moment = require('moment'); exports.diagnosa = async (req, res) => { const { gejala } = req.body; // array of id_gejala + const userId = req.user?.id; // Use optional chaining to avoid errors if req.user is undefined + const tanggal_diagnosa = moment().format('YYYY-MM-DD'); if (!gejala || !Array.isArray(gejala)) { return res.status(400).json({ message: 'Gejala harus berupa array' }); @@ -196,6 +199,63 @@ exports.diagnosa = async (req, res) => { attributes: ['id', 'kode', 'nama'] }); + if (!userId) { + console.error('ID user tidak ditemukan pada request. Histori tidak dapat disimpan.'); + } else { + const idGejalaDipilih = gejala; + const semuaHasil = [...hasilPenyakit, ...hasilHama]; + + if (semuaHasil.length > 0) { + const hasilTerbesar = semuaHasil.reduce((max, current) => { + return current.probabilitas > max.probabilitas ? current : max; + }); + + // Base histori data without id_gejala + const baseHistoriData = { + userId: userId, + tanggal_diagnosa: tanggal_diagnosa, + hasil: hasilTerbesar.probabilitas + }; + + if (hasilTerbesar.id_penyakit) { + baseHistoriData.id_penyakit = hasilTerbesar.id_penyakit; + } else if (hasilTerbesar.id_hama) { + baseHistoriData.id_hama = hasilTerbesar.id_hama; + } + + try { + // Option 1: Store only the first gejala ID if we're limited to one record + // if (idGejalaDipilih.length > 0) { + // await Histori.create({ + // ...baseHistoriData, + // id_gejala: parseInt(idGejalaDipilih[0]) // Store as integer + // }, { timestamps: false }); + // console.log('Histori berhasil disimpan dengan gejala utama'); + // } + + // Option 2 (Uncomment if you want to create multiple records): + + // Create multiple records - one for each gejala + const historiPromises = idGejalaDipilih.map(gejalaId => { + return Histori.create({ + ...baseHistoriData, + id_gejala: parseInt(gejalaId) // Store as integer + }, { timestamps: false }); + }); + + await Promise.all(historiPromises); + console.log(`Histori berhasil disimpan untuk ${idGejalaDipilih.length} gejala`); + + + } catch (error) { + console.error('Gagal menyimpan histori:', error.message); + } + } else { + console.log('Tidak ada hasil untuk disimpan ke histori.'); + } + } + + // Kirim hasil perhitungan sebagai respons res.json({ input_gejala: gejalaSummary, diff --git a/backend/middleware/roleMiddleware.js b/backend/middleware/roleMiddleware.js index 117aa6d..942d2a1 100644 --- a/backend/middleware/roleMiddleware.js +++ b/backend/middleware/roleMiddleware.js @@ -11,10 +11,16 @@ const roleMiddleware = (roles) => { } try { + // Log token untuk memastikan diterima + console.log('Token diterima:', token); + // Verify the token const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; + // Log decoded token + console.log('Decoded Token:', decoded); + // Check if the user has one of the allowed roles if (roles.includes(req.user.role)) { next(); @@ -27,4 +33,5 @@ const roleMiddleware = (roles) => { }; }; + module.exports = roleMiddleware; \ No newline at end of file diff --git a/backend/migrations/20250511153136-create-histori.js b/backend/migrations/20250511153136-create-histori.js new file mode 100644 index 0000000..e7dc079 --- /dev/null +++ b/backend/migrations/20250511153136-create-histori.js @@ -0,0 +1,66 @@ +'use strict'; +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('histori', { + id: { + allowNull: false, + autoIncrement: true, + primaryKey: true, + type: Sequelize.INTEGER + }, + userId: { + type: Sequelize.INTEGER, + allowNull: false, + references: { + model: 'users', // sesuaikan dengan nama tabel Users kamu + key: 'id' + }, + onUpdate: 'CASCADE', + onDelete: 'CASCADE' + }, + id_gejala: { + type: Sequelize.INTEGER, + allowNull: false, + references: { + model: 'gejala', // sesuaikan dengan nama tabel Gejalas kamu + key: 'id' + }, + onUpdate: 'CASCADE', + onDelete: 'CASCADE' + }, + id_penyakit: { + type: Sequelize.INTEGER, + allowNull: true, + references: { + model: 'penyakit', + key: 'id' + }, + onUpdate: 'CASCADE', + onDelete: 'SET NULL' + }, + id_hama: { + type: Sequelize.INTEGER, + allowNull: true, + references: { + model: 'hama', + key: 'id' + }, + onUpdate: 'CASCADE', + onDelete: 'SET NULL' + }, + tanggal_diagnosa: { + type: Sequelize.DATE, + allowNull: false + }, + hasil: { + type: Sequelize.FLOAT, + allowNull: false + }, + }); + }, + + async down(queryInterface, Sequelize) { + await queryInterface.dropTable('histori'); + } +}; diff --git a/backend/models/histori.js b/backend/models/histori.js new file mode 100644 index 0000000..4adc691 --- /dev/null +++ b/backend/models/histori.js @@ -0,0 +1,66 @@ +'use strict'; +const { Model, DataTypes } = require('sequelize'); + +module.exports = (sequelize) => { + class Histori extends Model { + static associate(models) { + // Relasi ke User + Histori.belongsTo(models.User, { + foreignKey: 'userId', + as: 'user' + }); + + // Relasi ke Gejala (satu gejala per baris) + Histori.belongsTo(models.Gejala, { + foreignKey: 'id_gejala', + as: 'gejala' + }); + + // Relasi ke Penyakit (opsional) + Histori.belongsTo(models.Penyakit, { + foreignKey: 'id_penyakit', + as: 'penyakit' + }); + + // Relasi ke Hama (opsional) + Histori.belongsTo(models.Hama, { + foreignKey: 'id_hama', + as: 'hama' + }); + } + } + + Histori.init({ + userId: { + type: DataTypes.INTEGER, + allowNull: false + }, + id_gejala: { + type: DataTypes.INTEGER, + allowNull: false + }, + id_penyakit: { + type: DataTypes.INTEGER, + allowNull: true + }, + id_hama: { + type: DataTypes.INTEGER, + allowNull: true + }, + tanggal_diagnosa: { + type: DataTypes.DATE, + allowNull: false + }, + hasil: { + type: DataTypes.FLOAT, + allowNull: false + } + }, { + sequelize, + modelName: 'Histori', + tableName: 'histori', + timestamps: false // kalau kamu pakai kolom createdAt & updatedAt + }); + + return Histori; +}; diff --git a/backend/routes/diagnosaRoutes.js b/backend/routes/diagnosaRoutes.js index 0e64e48..e73d001 100644 --- a/backend/routes/diagnosaRoutes.js +++ b/backend/routes/diagnosaRoutes.js @@ -1,6 +1,7 @@ const express = require('express'); const router = express.Router(); const { diagnosa } = require('../controller/diagnosaController'); +const roleMiddleware = require('../middleware/roleMiddleware'); console.log('Diagnosa function:', diagnosa); /** @@ -9,6 +10,8 @@ console.log('Diagnosa function:', diagnosa); * post: * summary: Melakukan diagnosa penyakit dan hama menggunakan Teorema Bayes * tags: [Diagnosa] + * security: + * - BearerAuth: [] * requestBody: * required: true * content: @@ -152,6 +155,6 @@ console.log('Diagnosa function:', diagnosa); * 500: * description: Terjadi kesalahan pada server */ -router.post('/', diagnosa); +router.post('/', roleMiddleware(['user', 'admin']), diagnosa); module.exports = router; \ No newline at end of file