### Start Development Server Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Launch the local development server. ```bash npm run dev ``` -------------------------------- ### Client-side Usage Example Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md Example implementation using the Fetch API to initiate the password reset process. ```typescript const response = await fetch('/api/auth/login/forgot-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'user@example.com' }) }) const result = await response.json() console.log('Password reset email sent') ``` -------------------------------- ### Client-side Usage Example Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md Example of how to call the endpoint using the Fetch API. ```typescript const response = await fetch('/api/auth/register/resend-email-verification', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'user@example.com' }) }) const result = await response.json() if (response.status === 200) { console.log('Verification email resent') } ``` -------------------------------- ### Install Dependencies Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Install required project packages using npm or yarn. ```bash npm install # or yarn install ``` -------------------------------- ### Register User Example Usage Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md Demonstrates how to encrypt a password using AES and perform the registration request via fetch. ```typescript import cryptoAES from '@/utils/cryptoAES' const plainPassword = 'securePassword123' const aesKey = 'your-aes-key' const encryptedPassword = cryptoAES.clientSideAESEncrypt(plainPassword, aesKey) const response = await fetch('/api/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ fullname: 'John Doe', email: 'john@example.com', password: encryptedPassword }) }) if (response.status === 201) { console.log('User registered. Check email for verification link.') } ``` -------------------------------- ### Response Examples Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/02-api-reference-diagnosis.md JSON response structures for successful deletion and not found scenarios. ```json { "code": 200, "message": "Berhasil menghapus riwayat diagnosis sebelumnya" } ``` ```json { "code": 404, "message": "Riwayat diagnosis tidak ditemukan" } ``` -------------------------------- ### Client-side Login Implementation Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md Example of encrypting a password and performing the login request using the fetch API. ```typescript // Client-side encryption import cryptoAES from '@/utils/cryptoAES' const plainPassword = 'userPassword123' const encryptedPassword = cryptoAES.clientSideAESEncrypt(plainPassword, aesKey) // API request const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'user@example.com', password: encryptedPassword }) }) const { data } = await response.json() console.log(data.authToken) // Use for subsequent authenticated requests ``` -------------------------------- ### Password Reset Usage Example Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md Demonstrates how to encrypt a new password and submit the reset request to the API. ```typescript import cryptoAES from '@/utils/cryptoAES' const plainPassword = 'newPassword123' const aesKey = 'your-aes-key' const encrypted = cryptoAES.clientSideAESEncrypt(plainPassword, aesKey) const response = await fetch('/api/auth/login/forgot-password/next-step', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: 't-uuid-from-email', password: encrypted, passwordConfirm: encrypted }) }) if (response.status === 200) { console.log('Password reset successful. Please log in again.') } ``` -------------------------------- ### Example usage of loggedInUserDataType Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/05-types.md Example object conforming to the loggedInUserDataType structure. ```typescript const user: loggedInUserDataType = { id: "550e8400-e29b-41d4-a716-446655440000", role: "user", email: "john@example.com", fullname: "John Doe", authToken: "at-abc12345def67890" } ``` -------------------------------- ### Update Pest or Disease Record Example Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/03-api-reference-admin.md Example usage of the fetch API to perform a PUT request for updating a record. ```typescript const response = await fetch('/api/admin/pests-deseases', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ pestOrDeseaseCode: 42, data: { name: 'Fruit Fly (Updated)', solution: 'Improved solution with better efficacy...', activeIngredient: 'Pyrethrin + Neem Oil' } }) }) const result = await response.json() console.log('Pest/disease updated successfully') ``` -------------------------------- ### Database Connection URL Format Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Standard format for MySQL connection strings and a specific example for PlanetScale integration. ```text mysql://[user[:password]@][host][:port][/database] ``` ```text mysql://user:pscale_pw_xxxxx@us-east.connect.psdb.cloud/sipbuk_db?sslaccept=strict ``` -------------------------------- ### Example of TUserInputData usage Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/05-types.md Demonstrates how to initialize the user input object with symptom codes and certainty values. ```typescript const userInput: TUserInputData = { "1": 0.8, // 80% confident of symptom 1 "5": 0.6, // 60% confident of symptom 5 "12": 0.95 // 95% confident of symptom 12 } ``` -------------------------------- ### Delete Pests and Diseases Usage Example Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/03-api-reference-admin.md Example of how to call the deletion endpoint using the fetch API. ```typescript const response = await fetch('/api/admin/pests-deseases', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ selectedPestsDeseases: [42, 43, 44] }) }) const result = await response.json() console.log(`Deleted ${result.data.count} pest/disease records`) ``` -------------------------------- ### Success Response Examples Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md JSON response structures for successful verification email resend requests. ```json { "code": 200, "message": "Kami telah mengirimkan email verifikasi ke email user@example.com", "data": { "id": "user-uuid", "email": "user@example.com", "fullname": "User Name", "verifyToken": "vt-uuid", "isVerified": false } } ``` ```json { "code": 201, "message": "Daftar Berhasil! Silahkan cek email anda untuk melakukan verifikasi akun. Jika tidak ada di inbox, silahkan cek di folder spam atau promosi." } ``` -------------------------------- ### Example structure of TMixedKnowledgeBaseWithUserCFInput Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/05-types.md Shows the structure of a pest record after merging with user certainty factors. ```typescript { code: 1, name: "Fruit Fly", solution: "...", PestsAndDeseasesHasSymptoms: [ { id: 1, symptomCode: 5, expertCF: 0.9, userCF: 0.8, // Added after mixing symptoms: { ... } } ] } ``` -------------------------------- ### Diagnosis history response examples Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/02-api-reference-diagnosis.md JSON response structures for successful updates and not found errors. ```json { "code": 200, "message": "Berhasil menyimpan riwayat diagnosis sebelumnya", "data": [ { "id": "dh-uuid", "userId": "user-uuid", "pestAndDeseaseCode": 1, "finalCF": 0.85, "userInputData": "{\"1\":0.8,\"2\":0.6}", "createdAt": "2023-06-15T10:30:00Z", "updatedAt": "2023-06-15T10:30:00Z", "pestsAndDeseases": { "code": 1, "name": "Bacterial Wilt", "solution": "...", "activeIngredient": "..." } } ] } ``` ```json { "code": 404, "message": "Riwayat diagnosis tidak ditemukan" } ``` -------------------------------- ### GET /api/auth/register/account-activation Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/08-endpoints.md Verifies a user's email address using a provided token. ```APIDOC ## GET /api/auth/register/account-activation ### Description Verifies user email via token and activates account. ### Method GET ### Endpoint /api/auth/register/account-activation ### Parameters #### Query Parameters - **token** (string) - Required - Email verification token (vt-{uuid}) ### Response - 302 redirect to `/register/email-verification` ``` -------------------------------- ### Set Knowledge Base Rules Request Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/08-endpoints.md Example JSON payload for configuring symptom-pest associations with expert certainty factor values. ```json { "data": [ { "pestAndDeseaseCode": 1, "symptomCode": 5, "expertCF": 0.9 }, { "pestAndDeseaseCode": 1, "symptomCode": 8, "expertCF": 0.75 } ], "pestAndDeseaseCode": 1 } ``` -------------------------------- ### GET /api/generateOGImage Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/08-endpoints.md Generates an Open Graph preview image from a provided URL screenshot. ```APIDOC ## GET /api/generateOGImage ### Description Generates Open Graph preview image from URL screenshot. ### Method GET ### Endpoint /api/generateOGImage ### Parameters #### Query Parameters - **url** (string) - Required - Page URL to render - **width** (number) - Optional - Image width (px) - **height** (number) - Optional - Image height (px) ### Response #### Success Response (200) - **Content-Type** (image/jpeg) - JPEG image buffer ``` -------------------------------- ### Example usage of getServerSidePropsType Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/05-types.md Implementation of getServerSideProps using the defined context type. ```typescript import { getServerSidePropsType } from '@/types' export async function getServerSideProps(context: getServerSidePropsType) { const { req, res } = context const userCookie = getCookie('user', { req, res }) if (!userCookie) { return { redirect: { destination: '/login' } } } return { props: {} } } ``` -------------------------------- ### POST /api/inference-engine Request Example Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/08-endpoints.md Submit symptom codes and their corresponding Certainty Factor values along with a user UUID to perform a diagnosis. ```json { "data": { "1": 0.8, "5": 0.6, "12": 0.95 }, "userId": "user-uuid-here" } ``` -------------------------------- ### Create Pest/Disease Record via Fetch Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/03-api-reference-admin.md Example usage of the POST endpoint using the Fetch API to submit a new pest or disease entry. ```typescript const response = await fetch('/api/admin/pests-deseases', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Mealybug', solution: 'Spray with pyrethrin-based insecticide every 7 days', activeIngredient: 'Pyrethrin' }) }) const result = await response.json() console.log(`Created pest/disease with code: ${result.data.code}`) ``` -------------------------------- ### Example of TCalculatedSingleRuleCF data Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/05-types.md Displays the calculated certainty factors for multiple symptoms associated with a pest. ```typescript { code: 1, name: "Fruit Fly", calculatedSingleRuleCF: [0.72, 0.45, 0.95], // 3 symptoms PestsAndDeseasesHasSymptoms: [ { symptomCode: 5, expertCF: 0.9, userCF: 0.8 }, { symptomCode: 8, expertCF: 0.75, userCF: 0.6 }, { symptomCode: 12, expertCF: 0.95, userCF: 1.0 } ] } ``` -------------------------------- ### Generate Open Graph Image Request Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/08-endpoints.md Example URL for requesting an Open Graph image generation with specific dimensions. ```http GET /api/generateOGImage?url=https://example.com/page&width=1200&height=630 ``` -------------------------------- ### Example userInputData JSON Format Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Expected structure for the userInputData field, mapping symptom codes to certainty factors. ```json { "1": 0.8, "5": 0.6, "12": 0.95 } ``` -------------------------------- ### Set Rules via Fetch API Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/03-api-reference-admin.md Example usage of the endpoint using the browser's fetch API to update symptom associations for a specific pest. ```typescript const response = await fetch('/api/admin/pests-deseases/set-rule', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: [ { pestAndDeseaseCode: 1, symptomCode: 5, expertCF: 0.9 }, { pestAndDeseaseCode: 1, symptomCode: 8, expertCF: 0.75 }, { pestAndDeseaseCode: 1, symptomCode: 12, expertCF: 0.65 } ], pestAndDeseaseCode: 1 }) }) const result = await response.json() console.log('Rules saved and user histories regenerated') ``` -------------------------------- ### Associate diagnosis history via fetch Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/02-api-reference-diagnosis.md Example usage for associating a list of diagnosis IDs with a user account using the fetch API. ```typescript // User logs in and wants to associate previous diagnoses const diagnosisIds = ['dh-xyz1', 'dh-xyz2', 'dh-xyz3'] const userId = 'user-abc123' const response = await fetch('/api/dashboard/diagnoses-history', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ diagnosesId: diagnosisIds, userId: userId }) }) const result = await response.json() if (response.status === 200) { console.log(`${result.data.length} diagnoses associated with account`) } ``` -------------------------------- ### Delete Diagnosis History Usage Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/02-api-reference-diagnosis.md Example of using the fetch API to send a DELETE request with diagnosis IDs and user ID. ```typescript // User wants to delete specific diagnoses from history const diagnosisIds = ['dh-old1', 'dh-old2'] const userId = 'user-abc123' const response = await fetch('/api/dashboard/diagnoses-history', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ diagnosesId: diagnosisIds, userId: userId }) }) if (response.status === 200) { console.log('Diagnoses deleted successfully') } ``` -------------------------------- ### Prisma Foreign Key Constraint Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Example of a Prisma relation field definition enforcing referential integrity with cascade deletion. ```prisma // Relation fields enforce referential integrity user User @relation(fields: [userId], references: [id], onDelete: Cascade) ``` -------------------------------- ### Menjalankan Aplikasi Source: https://github.com/deri-kurniawan/sipbuk/blob/main/pages/docs/installation-guide.mdx Perintah untuk memulai server pengembangan. ```bash npm run dev ``` -------------------------------- ### Open Prisma Studio Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Launch the Prisma GUI for database management. ```bash npm run db:studio ``` -------------------------------- ### Initialize Database Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Push the database schema and generate the Prisma client. ```bash # Push schema to database npm run db:push # Generate Prisma client npm run db:generate ``` -------------------------------- ### Navigasi Folder dan Instalasi Dependensi Source: https://github.com/deri-kurniawan/sipbuk/blob/main/pages/docs/installation-guide.mdx Masuk ke direktori proyek dan menginstal paket yang diperlukan dari package.json. ```bash cd sipbuk ``` ```bash npm install ``` -------------------------------- ### Akses Aplikasi Source: https://github.com/deri-kurniawan/sipbuk/blob/main/pages/docs/installation-guide.mdx Alamat URL untuk mengakses aplikasi di browser. ```bash http://localhost:3000 ``` -------------------------------- ### Clone the Repository Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Download the project source code and navigate into the directory. ```bash git clone https://github.com/deri-kurniawan/sipbuk.git cd sipbuk ``` -------------------------------- ### Konfigurasi Environment Variables Source: https://github.com/deri-kurniawan/sipbuk/blob/main/pages/docs/installation-guide.mdx Contoh isi file .env untuk konfigurasi aplikasi dan koneksi database. ```bash # Nama Aplikasi APP_NAME=SIPBUK # URL Aplikasi untuk development dan production APP_URL=http://localhost:3000 # Database URL jika menggunakan MySQL secara online DATABASE_URL=mysql://username:password@host:port/database_name?sslaccept=mode # Akun Google Untuk Pengiriman Email NODEMAILER_SERVICE=gmail NODEMAILER_USER=name@domain.com NODEMAILER_PASS=kata_sandi # Secret Key untuk enkripsi data dapat diisi dengan string random AES_KEY=secret_key ``` -------------------------------- ### List Database Files Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/00-INDEX.md Core database configuration and schema definition files. ```text prisma/index.ts prisma/schema.prisma ``` -------------------------------- ### Kloning Repositori SIPBUK Source: https://github.com/deri-kurniawan/sipbuk/blob/main/pages/docs/installation-guide.mdx Mengunduh kode sumber aplikasi dari repositori GitHub. ```bash git clone https://github.com/deri-kurniawan/sipbuk.git ``` -------------------------------- ### Seed Database Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Populate the database with initial data. ```bash npm run db:seed ``` -------------------------------- ### Informasi Akun Default Source: https://github.com/deri-kurniawan/sipbuk/blob/main/pages/docs/installation-guide.mdx Kredensial login bawaan untuk pengguna dan admin. ```bash # Akun Pengguna Email: user@sipbuk.com Password: user123 # Akun Admin Email: admin@sipbuk.com Password: admin123 ``` -------------------------------- ### Seeding Data Knowledge Base Source: https://github.com/deri-kurniawan/sipbuk/blob/main/pages/docs/installation-guide.mdx Memasukkan data awal ke dalam database dari folder prisma/data. ```bash npm run db:seed ``` ```bash npx prisma db seed ``` -------------------------------- ### Sinkronisasi Database dengan Prisma Source: https://github.com/deri-kurniawan/sipbuk/blob/main/pages/docs/installation-guide.mdx Perintah untuk membuat skema tabel pada database. ```bash npm run db:push ``` ```bash npx prisma db push ``` -------------------------------- ### List Utility Modules Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/00-INDEX.md A directory of utility scripts including cryptography, certainty factor calculations, and email transport configurations. ```text utils/certaintyFactor.ts utils/cryptoAES.ts utils/regexp.ts utils/synchronizeUsersDiagnosesHistories.ts utils/nodemailer/transporter.ts utils/nodemailer/options/verificationEmailOptions.ts utils/nodemailer/options/passwordResetEmailOptions.ts utils/nodemailer/options/passwordChangedEmail.ts ``` -------------------------------- ### Define package.json scripts Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Lists the available npm scripts for development, production builds, and database management via Prisma. ```json { "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "db:push": "prisma db push", "db:generate": "prisma generate", "db:studio": "prisma studio" } } ``` -------------------------------- ### Configure Node.js Environment Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Sets the runtime environment for the application. ```text NODE_ENV=production ``` -------------------------------- ### Configure Database URL Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Defines the MySQL connection string for the application database. ```text DATABASE_URL=mysql://user:password@host:port/database ``` ```text DATABASE_URL=mysql://root:password123@localhost:3306/sipbuk_db ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Templates for .env.local files used to configure database, application, email, encryption, and environment settings. ```bash # Database DATABASE_URL=mysql://user:pass@host:3306/sipbuk # Application APP_URL=https://sipbuk.example.com APP_NAME=SIPBUK # Email NODEMAILER_SERVICE=gmail NODEMAILER_USER=noreply@example.com NODEMAILER_PASS=your-app-password # Encryption AES_KEY=ServerEncryptionKey12345 NEXT_PUBLIC_AES_KEY=ClientEncryptionKey1234 # Image Generation CHROMIUM_PATH=/usr/bin/chromium-browser # Node NODE_ENV=production ``` ```bash DATABASE_URL=mysql://root:password@localhost:3306/sipbuk_dev APP_URL=http://localhost:3000 APP_NAME=SIPBUK NODEMAILER_SERVICE=gmail NODEMAILER_USER=your-email@gmail.com NODEMAILER_PASS=your-app-password AES_KEY=dev-encryption-key-16chars NEXT_PUBLIC_AES_KEY=dev-client-key-123 CHROMIUM_PATH=/usr/bin/chromium-browser NODE_ENV=development ``` -------------------------------- ### Initialize and Run Certainty Factor Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/10-quick-reference.md Demonstrates two methods for executing the Certainty Factor calculation: chained promise-based execution or a single method call. ```typescript import CertaintyFactor from '@/utils/certaintyFactor' const userInputData = { '1': 0.8, '5': 0.6 } const cf = new CertaintyFactor(userInputData) // Method 1: Chain methods const result = await cf .generateKnowledgeBase() .then(c => c.mixKnowledgeBaseWithUserCFInput()) .then(c => c.calculateSingleRuleCF()) .then(c => c.calculateCombinationRule()) .then(c => c.generateConclusion()) // Method 2: Call all at once await cf.generateConclusion() const diagnosis = cf.conclusion[0] console.log(`Diagnosis: ${diagnosis.name}`) console.log(`Confidence: ${diagnosis.finalCF}`) console.log(`Solution: ${diagnosis.solution}`) ``` -------------------------------- ### Import Prisma Client Types Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/05-types.md Import the necessary Prisma client and model types for use in the application. ```typescript import { PrismaClient } from '@prisma/client' import type { User, PestsAndDeseases, Symptoms, PestsAndDeseasesHasSymptoms, UsersDiagnoseHistory } from '@prisma/client' ``` -------------------------------- ### Configure Email Authentication Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Sets the credentials for the email service provider. ```text NODEMAILER_USER=noreply@example.com ``` ```text NODEMAILER_PASS=your-app-password-here ``` -------------------------------- ### Configure Application URLs Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Sets the base URL for the application, used for links and API generation. ```text APP_URL=https://example.com ``` ```text APP_URL=https://sipbuk.example.com APP_URL=http://localhost:3000 ``` -------------------------------- ### POST /api/auth/register Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md Creates a new user account and sends an email verification link. The user must verify their email address before they can log in. ```APIDOC ## POST /api/auth/register ### Description Creates a new user account and sends an email verification link. User must verify email before login. ### Method POST ### Endpoint /api/auth/register ### Parameters #### Request Body - **fullname** (string) - Required - User full name (2-30 characters, alphabetic only) - **email** (string) - Required - User email address - **password** (string) - Required - AES-encrypted password (minimum 6 characters when decrypted) ### Request Example { "fullname": "John Doe", "email": "john@example.com", "password": "encrypted_password_string" } ### Response #### Success Response (201) - **code** (number) - Status code - **message** (string) - Success message #### Response Example { "code": 201, "message": "Berhasil mendaftar! Cek email untuk verifikasi. Jika tidak di inbox, cek spam atau promosi." } ``` -------------------------------- ### Configure Application Name Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Sets the display name for the application in email templates. ```text APP_NAME=SIPBUK ``` -------------------------------- ### Configure Client-side Encryption Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Sets the public key for client-side password encryption. ```text NEXT_PUBLIC_AES_KEY=public-encryption-key-for-browser ``` ```text NEXT_PUBLIC_AES_KEY=ClientKey123456 ``` -------------------------------- ### Handle 404 Not Found Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/07-errors.md Log the error message when a requested resource does not exist in the database. ```typescript if (response.status === 404) { const error = await response.json() console.error(`Not found: ${error.message}`) } ``` -------------------------------- ### Create Pest or Disease Record Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Insert a new entry into the PestsAndDeseases table. ```prisma await prisma.pestsAndDeseases.create({ data: { name: "Fruit Fly", solution: "Apply neem oil...", activeIngredient: "Azadirachtin" } }) ``` -------------------------------- ### POST /api/auth/login Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md Authenticates a user with their email and an AES-encrypted password. Returns an authentication token upon successful verification. ```APIDOC ## POST /api/auth/login ### Description Authenticates a user with email and AES-encrypted password. Returns an authentication token on successful login. ### Method POST ### Endpoint /api/auth/login ### Parameters #### Request Body - **email** (string) - Required - User email address - **password** (string) - Required - AES-encrypted password hash (CryptoJS.AES.encrypt format) ### Request Example { "email": "user@example.com", "password": "encrypted_password_string" } ### Response #### Success Response (200) - **code** (number) - Status code - **message** (string) - Success message - **data** (object) - User authentication data including id, role, email, fullname, and authToken #### Response Example { "code": 200, "message": "Selamat datang User Name!", "data": { "id": "user-uuid", "role": "user", "email": "user@example.com", "fullname": "User Name", "authToken": "at-uuid" } } ``` -------------------------------- ### List Type Definitions Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/00-INDEX.md Location of the project's global type declarations. ```text types/index.d.ts ``` -------------------------------- ### Configure Chromium Path Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Specifies the path to the Chromium executable for Puppeteer. ```text CHROMIUM_PATH=/usr/bin/chromium-browser ``` ```text CHROMIUM_PATH=/var/task/.chromium/chromium ``` -------------------------------- ### Query PestsAndDeseases with Symptoms Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Retrieve all records including their associated symptoms via the relation table. ```prisma await prisma.pestsAndDeseases.findMany({ include: { PestsAndDeseasesHasSymptoms: { include: { symptoms: true } } } }) ``` -------------------------------- ### List API Endpoints Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/00-INDEX.md A directory of available API routes for authentication, inference, dashboard, and administrative tasks. ```text pages/api/auth/login/index.ts pages/api/auth/register/index.ts pages/api/auth/register/account-activation.ts pages/api/auth/register/resend-email-verification.ts pages/api/auth/login/forgot-password/index.ts pages/api/auth/login/forgot-password/next-step.ts pages/api/inference-engine/index.ts pages/api/dashboard/diagnoses-history.ts pages/api/admin/pests-deseases/index.ts pages/api/admin/pests-deseases/set-rule.ts pages/api/regenerateUsersDiagnosesHistories.ts pages/api/generateOGImage.ts ``` -------------------------------- ### Create Diagnosis Record Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Creates a new diagnosis entry with a generated UUID and stringified JSON input data. ```prisma await prisma.usersDiagnoseHistory.create({ data: { id: `dh-${uuidv4()}`, userId: userId, pestAndDeseaseCode: 1, finalCF: 0.85, userInputData: JSON.stringify({ "1": 0.8, "5": 0.6 }) } }) ``` -------------------------------- ### Configure Server-side Encryption Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Sets the secret key for AES encryption of passwords. ```text AES_KEY=your-secret-encryption-key-min-16-chars ``` ```text AES_KEY=SuperSecret1234567890Key ``` -------------------------------- ### Successful Login Response Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md The JSON structure returned upon successful authentication. ```json { "code": 200, "message": "Selamat datang [fullname]!", "data": { "id": "user-uuid", "role": "user", "email": "user@example.com", "fullname": "User Name", "authToken": "at-uuid" } } ``` -------------------------------- ### Query User by Email Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Retrieves a unique user record based on their email address. ```prisma await prisma.user.findUnique({ where: { email } }) ``` -------------------------------- ### Registration Success Response Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md The JSON response returned upon successful user creation and email dispatch. ```json { "code": 201, "message": "Berhasil mendaftar! Cek email untuk verifikasi. Jika tidak di inbox, cek spam atau promosi." } ``` -------------------------------- ### Success Response JSON Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/03-api-reference-admin.md The expected JSON structure returned upon successful rule saving. ```json { "code": 200, "message": "Berhasil menyimpan rule", "data": { "data": [ { "pestAndDeseaseCode": 1, "symptomCode": 5, "expertCF": 0.85 } ], "pestAndDeseaseCode": 1 } } ``` -------------------------------- ### POST /api/auth/login/forgot-password/next-step Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md Completes the password reset process by validating the provided token and updating the user's password with the encrypted values. ```APIDOC ## POST /api/auth/login/forgot-password/next-step ### Description Completes password reset by validating token and updating password. ### Method POST ### Endpoint /api/auth/login/forgot-password/next-step ### Parameters #### Request Body - **token** (string) - Required - Password reset token from email - **password** (string) - Required - AES-encrypted new password (minimum 6 characters) - **passwordConfirm** (string) - Required - AES-encrypted password confirmation (must match password) ### Response #### Success Response (200) - **code** (number) - Status code - **message** (string) - Success message #### Response Example { "code": 200, "message": "Password berhasil diubah, silahkan masuk kembali!" } ``` -------------------------------- ### Registration Server Error Response Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md The JSON response returned when the user is created but the verification email fails to send. ```json { "code": 500, "message": "Daftar Berhasil! Email verifikasi gagal dikirim karena kesalahan server" } ``` -------------------------------- ### Knowledge Base Structure Representation Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/03-api-reference-admin.md A visual representation of how symptoms map to a pest/disease with specific certainty factors. ```text Pest/Disease (code 1) ├─ Symptom 5 with expertCF 0.9 (90% of fruit flies show this symptom) ├─ Symptom 8 with expertCF 0.75 (75% of fruit flies show this) └─ Symptom 12 with expertCF 0.65 (65% of fruit flies show this) ``` -------------------------------- ### POST /api/admin/pests-deseases/set-rule Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/08-endpoints.md Sets knowledge base rules for pest-symptom associations. ```APIDOC ## POST /api/admin/pests-deseases/set-rule ### Description Sets knowledge base rules (pest-symptom associations with CF values). ### Method POST ### Endpoint /api/admin/pests-deseases/set-rule ### Request Body - **data** (array) - Required - Array of symptom-pest associations - **data[].pestAndDeseaseCode** (number) - Required - Pest/disease code - **data[].symptomCode** (number) - Required - Symptom code - **data[].expertCF** (number) - Required - Expert CF value (0-1) - **pestAndDeseaseCode** (number) - Required - For cleanup (delete unmapped symptoms) ### Request Example { "data": [ { "pestAndDeseaseCode": 1, "symptomCode": 5, "expertCF": 0.9 }, { "pestAndDeseaseCode": 1, "symptomCode": 8, "expertCF": 0.75 } ], "pestAndDeseaseCode": 1 } ### Response #### Success Response (200) - **code** (number) - 200 - **message** (string) - Berhasil menyimpan rule - **data** (object) - Echo of request data ``` -------------------------------- ### Query User by Auth Token Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Retrieves a unique user record based on their authentication token. ```prisma await prisma.user.findUnique({ where: { authToken } }) ``` -------------------------------- ### Success Response Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md The JSON response returned upon a successful password update. ```json { "code": 200, "message": "Password berhasil diubah, silahkan masuk kembali!" } ``` -------------------------------- ### Define User Model Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Schema definition for the User entity, including authentication fields and relations. ```prisma model User { id String @id @default(uuid()) role String @default("user") fullname String @db.VarChar(255) email String @unique password String isVerified Boolean @default(false) verifyToken String? @unique authToken String? @unique passwordResetToken String? @unique createdAt DateTime @default(now()) updatedAt DateTime @updatedAt UsersDiagnoseHistory UsersDiagnoseHistory[] } ``` -------------------------------- ### Query User with Diagnosis History Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Retrieves a user record including their associated diagnosis history records. ```prisma await prisma.user.findUnique({ where: { id }, include: { UsersDiagnoseHistory: true } }) ``` -------------------------------- ### Success Response JSON Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/03-api-reference-admin.md The structure of the JSON response returned upon a successful update. ```json { "code": 200, "message": "Berhasil mengubah Hama dan Penyakit", "data": { "code": 42, "name": "Updated Fruit Fly", "solution": "New solution text...", "activeIngredient": "Updated ingredients", "createdAt": "2023-06-10T00:00:00Z", "updatedAt": "2023-06-15T10:30:00Z" } } ``` -------------------------------- ### User to Diagnosis Relationship Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Visual representation of the one-to-many relationship between users and their diagnosis history. ```text User (1) ──→ (many) UsersDiagnoseHistory ``` -------------------------------- ### Prisma Schema Configuration Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Defines the Prisma generator and datasource settings for the MySQL database connection. ```prisma generator client { provider = "prisma-client-js" } datasource db { provider = "mysql" url = env("DATABASE_URL") relationMode = "prisma" } ``` -------------------------------- ### Diagnosis to Pest and Disease Relationship Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Visual representation of the many-to-one relationship between diagnosis history and pests/diseases. ```text UsersDiagnoseHistory (many) ──→ (1) PestsAndDeseases ``` -------------------------------- ### Query and Modify PestsAndDeseasesHasSymptoms Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Common Prisma operations for querying, creating, updating, and deleting records in the junction table. ```prisma await prisma.pestsAndDeseasesHasSymptoms.findFirst({ where: { pestAndDeseaseCode: 1, symptomCode: 5 } }) ``` ```prisma await prisma.pestsAndDeseasesHasSymptoms.findMany({ where: { pestAndDeseaseCode: 1 }, include: { symptoms: true } }) ``` ```prisma await prisma.pestsAndDeseasesHasSymptoms.update({ where: { id }, data: { expertCF: 0.85 } }) ``` ```prisma await prisma.pestsAndDeseasesHasSymptoms.create({ data: { pestAndDeseaseCode: 1, symptomCode: 5, expertCF: 0.9 } }) ``` ```prisma await prisma.pestsAndDeseasesHasSymptoms.deleteMany({ where: { pestAndDeseaseCode: 1 } }) ``` -------------------------------- ### Retrieve User Diagnosis History Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/10-quick-reference.md Fetches a unique user record along with their associated diagnosis history and pest/disease details. ```typescript const user = await prisma.user.findUnique({ where: { id: userId }, include: { UsersDiagnoseHistory: { include: { pestsAndDeseases: true } } } }) ``` -------------------------------- ### Authentication Errors Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/07-errors.md Validation and authentication errors for the login endpoint. ```APIDOC ## POST /api/auth/login ### Description Returns 400 status for various authentication failures including missing fields, invalid formats, or incorrect credentials. ### Errors - **Email harus diisi!** (Email field is empty) - **Format email salah!** (Email fails regexp validation) - **Kata sandi harus diisi!** (Password field is empty) - **Kata sandi kurang dari 6 karakter!** (Password length < 6) - **Email tidak terdaftar!** (User account not found) - **Password salah!** (Decrypted password mismatch) - **Halo [fullname]! Email anda belum terverifikasi. Silakan periksa kotak masuk dan folder spam email anda.** (User email not verified) ``` -------------------------------- ### Define Symptoms model in Prisma Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Defines the structure of the Symptoms table including primary key, metadata fields, and relationship definitions. ```prisma model Symptoms { code Int @id @default(autoincrement()) info String @db.VarChar(255) imageUrl String @db.VarChar(255) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt pestsAndDeseases PestsAndDeseases[] @relation("PestsAndDeseasesHasSymptoms") PestsAndDeseasesHasSymptoms PestsAndDeseasesHasSymptoms[] } ``` -------------------------------- ### Handle 401 Unauthorized Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/07-errors.md Clear local session data and redirect the user to the login page when authentication fails. ```typescript if (response.status === 401) { // Clear user session localStorage.removeItem('user') // Redirect to login window.location.href = '/login' } ``` -------------------------------- ### Retrieve Pests and Diseases with Symptoms Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/10-quick-reference.md Fetches all records from the pestsAndDeseases table including nested symptom relations. ```typescript import prisma from '@/prisma' const data = await prisma.pestsAndDeseases.findMany({ include: { PestsAndDeseasesHasSymptoms: { include: { symptoms: true } } } }) await prisma.$disconnect() ``` -------------------------------- ### Define User Model Type Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/05-types.md Structure for user account information, including authentication and verification fields. ```typescript type User = { id: string // UUID role: string // "user" | "admin" fullname: string // Name (varchar 255) email: string // Unique email password: string // AES-encrypted isVerified: boolean // Email verification status verifyToken: string | null // Email verification token authToken: string | null // Authentication token passwordResetToken: string | null createdAt: Date updatedAt: Date } ``` -------------------------------- ### Authentication Endpoint Signature Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md The HTTP method and path for the login endpoint. ```typescript POST /api/auth/login ``` -------------------------------- ### Configure Email Service Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/06-configuration.md Specifies the email provider name for Nodemailer. ```text NODEMAILER_SERVICE=gmail ``` -------------------------------- ### Query Symptoms data Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Common Prisma operations for retrieving symptom records and their associated relationships. ```prisma await prisma.symptoms.findUnique({ where: { code }, include: { PestsAndDeseasesHasSymptoms: true } }) ``` ```prisma await prisma.symptoms.findMany() ``` -------------------------------- ### API Endpoint Signature Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/03-api-reference-admin.md The HTTP method and path for the rule configuration endpoint. ```typescript POST /api/admin/pests-deseases/set-rule ``` -------------------------------- ### POST /api/inference-engine Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/08-endpoints.md Performs a diagnosis based on provided symptom codes and their corresponding Certainty Factor values. ```APIDOC ## POST /api/inference-engine ### Description Performs diagnosis using Certainty Factor algorithm. ### Method POST ### Endpoint /api/inference-engine ### Request Body - **data** (object) - Required - Symptom code to CF value mapping - **userId** (string) - Required - User UUID ### Request Example { "data": { "1": 0.8, "5": 0.6, "12": 0.95 }, "userId": "user-uuid-here" } ### Response #### Success Response (200) - **diagnoseId** (string) - Diagnosis history ID ``` -------------------------------- ### Define PestsAndDeseasesHasSymptoms Model Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Schema definition for the junction table linking pests/diseases to symptoms with certainty factors. ```prisma model PestsAndDeseasesHasSymptoms { id Int @id @default(autoincrement()) pestAndDeseaseCode Int symptomCode Int expertCF Float @default(0) pestsAndDeseases PestsAndDeseases @relation(fields: [pestAndDeseaseCode], references: [code]) symptoms Symptoms @relation(fields: [symptomCode], references: [code]) @@index([symptomCode]) @@index([pestAndDeseaseCode]) } ``` -------------------------------- ### Register API Endpoint Signature Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/01-api-reference-authentication.md The HTTP method and path for the registration endpoint. ```typescript POST /api/auth/register ``` -------------------------------- ### Handle 400 Bad Request Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/07-errors.md Use this pattern to capture and display validation errors when the client sends malformed data. ```typescript const response = await fetch('/api/endpoint', { ... }) if (response.status === 400) { const error = await response.json() console.error(`Validation error: ${error.message}`) // Display error to user } ``` -------------------------------- ### Create Diagnosis Record Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/10-quick-reference.md Inserts a new diagnosis history entry with a generated ID and serialized user input data. ```typescript await prisma.usersDiagnoseHistory.create({ data: { id: `dh-${uuidv4()}`, userId: userId, pestAndDeseaseCode: conclusion.code, finalCF: conclusion.finalCF, userInputData: JSON.stringify(userInputData) } }) ``` -------------------------------- ### Cascade Deletion Flow Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Visual representation of the cascade deletion process when a user is removed. ```text User (delete) → CASCADE → UsersDiagnoseHistory (deleted) ``` -------------------------------- ### Define Symptoms Model Type Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/05-types.md Structure for symptom descriptions and associated image references. ```typescript type Symptoms = { code: number // Auto-increment PK info: string // Description (varchar 255) imageUrl: string // Image URL (varchar 255) createdAt: Date updatedAt: Date } ``` -------------------------------- ### Define PestsAndDeseases Model Type Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/05-types.md Structure for pest and disease information, including solution and active ingredient details. ```typescript type PestsAndDeseases = { code: number // Auto-increment PK name: string // Name (varchar 255) solution: string // Text blob activeIngredient: string // Text blob createdAt: Date updatedAt: Date } ``` -------------------------------- ### Verify Admin Status in API Route Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/10-quick-reference.md Validates user session cookies and cross-references the authentication token with the database to ensure admin privileges. ```typescript import { getCookie } from 'cookies-next' export default async function adminHandler(req, res) { const isCookieExist = getCookie('user', { req, res }) const userCookie = isCookieExist ? JSON.parse(getCookie('user', { req, res })) : null // Check if admin if (!userCookie || userCookie.role !== 'admin') { return res.status(401).json({ code: 401, message: 'Unauthorized' }) } // Verify token matches database const foundUser = await prisma.user.findUnique({ where: { authToken: userCookie.authToken } }) if (!foundUser || foundUser.role !== 'admin') { deleteCookie('user', { req, res }) return res.status(401).json({ code: 401, message: 'Unauthorized' }) } // Admin verified, proceed with operation } ``` -------------------------------- ### POST /api/admin/pests-deseases Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/03-api-reference-admin.md Creates a new pest or disease record. This endpoint is restricted to users with an admin role. ```APIDOC ## POST /api/admin/pests-deseases ### Description Creates a new pest or disease record. Restricted to admin users only. ### Method POST ### Endpoint /api/admin/pests-deseases ### Parameters #### Request Body - **name** (string) - Required - Pest/disease name (max 255 characters) - **solution** (string) - Required - Treatment solution (text, no length limit) - **activeIngredient** (string) - Required - Active chemical/organic ingredients (text, no length limit) ### Request Example { "name": "Mealybug", "solution": "Spray with pyrethrin-based insecticide every 7 days", "activeIngredient": "Pyrethrin" } ### Response #### Success Response (200) - **code** (number) - Status code - **message** (string) - Success message - **data** (object) - Created record details #### Response Example { "code": 200, "message": "Berhasil menyimpan riwayat diagnosis sebelumnya", "data": { "code": 42, "name": "Fruit Fly", "solution": "Apply neem oil weekly...", "activeIngredient": "Azadirachtin", "createdAt": "2023-06-15T10:30:00Z", "updatedAt": "2023-06-15T10:30:00Z" } } ``` -------------------------------- ### Retrieve Specific Diagnosis Source: https://github.com/deri-kurniawan/sipbuk/blob/main/_autodocs/09-database-schema.md Fetches a single diagnosis record by its unique ID. ```prisma await prisma.usersDiagnoseHistory.findUnique({ where: { id: "dh-uuid" }, include: { pestsAndDeseases: true } }) ```