refactor: rewrite ke codebase lama
This commit is contained in:
-69
@@ -1,69 +0,0 @@
|
||||
import path from 'path';
|
||||
import express, { Request, Response, NextFunction } from 'express';
|
||||
import cors from 'cors';
|
||||
import helmet from 'helmet';
|
||||
import morgan from 'morgan';
|
||||
import routes from './routes';
|
||||
import { errorHandler, CustomError } from './middleware/errorHandler';
|
||||
import { setupSwaggerDocs } from './docs/swagger';
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use(helmet({
|
||||
crossOriginResourcePolicy: { policy: 'cross-origin' }
|
||||
}));
|
||||
app.use(cors({
|
||||
origin: true,
|
||||
credentials: true,
|
||||
}));
|
||||
|
||||
app.use(morgan('dev'));
|
||||
|
||||
// File upload statis biar bisa diakses lewat /uploads atau /api/uploads
|
||||
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
|
||||
app.use('/api/uploads', express.static(path.join(__dirname, '../uploads')));
|
||||
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /:
|
||||
* get:
|
||||
* summary: Endpoint root API
|
||||
* description: Endpoint dasar.
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Informasi umum API berhasil diambil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: Welcome to the Internify API
|
||||
* documentation:
|
||||
* type: string
|
||||
* example: Check /api/health untuk status
|
||||
*/
|
||||
app.get('/', (_req: Request, res: Response) => {
|
||||
res.status(200).json({
|
||||
message: 'Welcome to the Internify API',
|
||||
documentation: 'Check /api/health untuk status',
|
||||
});
|
||||
});
|
||||
|
||||
app.use('/api', routes);
|
||||
|
||||
setupSwaggerDocs(app);
|
||||
|
||||
app.use((req: Request, _res: Response, next: NextFunction) => {
|
||||
const error: CustomError = new Error(`Not Found - ${req.originalUrl}`);
|
||||
error.statusCode = 404;
|
||||
next(error);
|
||||
});
|
||||
|
||||
app.use(errorHandler);
|
||||
|
||||
export default app;
|
||||
Executable
BIN
Binary file not shown.
|
After Width: | Height: | Size: 412 KiB |
Executable
+111
@@ -0,0 +1,111 @@
|
||||
|
||||
CREATE TABLE `admin` (
|
||||
`id` bigint(20) NOT NULL,
|
||||
`nama_depan` varchar(255) NOT NULL,
|
||||
`nama_belakang` varchar(255) NOT NULL,
|
||||
`role` enum('admin') NOT NULL,
|
||||
`email` varchar(255) NOT NULL,
|
||||
`password` text NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
|
||||
CREATE TABLE `hasil_research` (
|
||||
`id` bigint(20) NOT NULL,
|
||||
`image_path` text NOT NULL,
|
||||
`nama_project` varchar(255) NOT NULL,
|
||||
`deskripsi` varchar(255) NOT NULL,
|
||||
`link_project` text NOT NULL,
|
||||
`created_at` datetime NOT NULL DEFAULT current_timestamp()
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
|
||||
CREATE TABLE `lamaran_magang` (
|
||||
`id` bigint(20) NOT NULL,
|
||||
`id_mahasiswa` bigint(20) NOT NULL,
|
||||
`id_lowongan_magang` varchar(255) NOT NULL,
|
||||
`status` enum('diterima','diproses','ditolak') NOT NULL,
|
||||
`created_at` datetime NOT NULL,
|
||||
`update_at` datetime NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
|
||||
CREATE TABLE `lowongan_magang` (
|
||||
`id` varchar(255) NOT NULL,
|
||||
`posisi` varchar(255) NOT NULL,
|
||||
`kelompok_peminatan` varchar(255) NOT NULL,
|
||||
`image_path` text NOT NULL,
|
||||
`jobdesk` text NOT NULL,
|
||||
`lokasi` varchar(255) NOT NULL,
|
||||
`kualifikasi` text NOT NULL,
|
||||
`benefit` text NOT NULL,
|
||||
`durasi_awal` date NOT NULL,
|
||||
`durasi_akhir` date NOT NULL,
|
||||
`status_lowongan` enum('dibuka','ditutup') NOT NULL,
|
||||
`paid` enum('paid','unpaid') NOT NULL,
|
||||
`created_at` datetime NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
|
||||
CREATE TABLE `mahasiswa` (
|
||||
`id` bigint(20) NOT NULL,
|
||||
`nama_depan` varchar(255) NOT NULL,
|
||||
`nama_belakang` varchar(255) DEFAULT NULL,
|
||||
`email` varchar(255) NOT NULL,
|
||||
`kontak` varchar(255) NOT NULL,
|
||||
`jurusan` varchar(255) NOT NULL,
|
||||
`role` enum('student') NOT NULL,
|
||||
`cv_path` text NOT NULL,
|
||||
`portofolio_path` text NOT NULL,
|
||||
`motivasi` text NOT NULL,
|
||||
`relevant_skills` varchar(255) NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
|
||||
CREATE TABLE `partnership` (
|
||||
`id` bigint(20) NOT NULL,
|
||||
`nama_partner` varchar(255) NOT NULL,
|
||||
`image_path` text NOT NULL,
|
||||
`created_at` datetime NOT NULL DEFAULT current_timestamp()
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
|
||||
ALTER TABLE `admin`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
ALTER TABLE `hasil_research`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
ALTER TABLE `lamaran_magang`
|
||||
ADD PRIMARY KEY (`id`),
|
||||
ADD KEY `lamaran_magang_id_mahasiswa_foreign` (`id_mahasiswa`),
|
||||
ADD KEY `lamaran_magang_id_lowongan_magang_foreign` (`id_lowongan_magang`);
|
||||
|
||||
ALTER TABLE `lowongan_magang`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
ALTER TABLE `mahasiswa`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
ALTER TABLE `partnership`
|
||||
ADD PRIMARY KEY (`id`);
|
||||
|
||||
ALTER TABLE `admin`
|
||||
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
|
||||
|
||||
ALTER TABLE `hasil_research`
|
||||
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
|
||||
|
||||
ALTER TABLE `lamaran_magang`
|
||||
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
|
||||
|
||||
ALTER TABLE `mahasiswa`
|
||||
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
|
||||
|
||||
ALTER TABLE `partnership`
|
||||
MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;
|
||||
|
||||
ALTER TABLE `lamaran_magang`
|
||||
ADD CONSTRAINT `lamaran_magang_id_lowongan_magang_foreign` FOREIGN KEY (`id_lowongan_magang`) REFERENCES `lowongan_magang` (`id`),
|
||||
ADD CONSTRAINT `lamaran_magang_id_mahasiswa_foreign` FOREIGN KEY (`id_mahasiswa`) REFERENCES `mahasiswa` (`id`);
|
||||
COMMIT;
|
||||
|
||||
|
||||
Executable
+180
@@ -0,0 +1,180 @@
|
||||
const swaggerJsDoc = require("swagger-jsdoc");
|
||||
const swaggerUi = require("swagger-ui-express");
|
||||
|
||||
const path = require('path');
|
||||
|
||||
const swaggerOptions = {
|
||||
definition: {
|
||||
openapi: "3.0.0",
|
||||
info: {
|
||||
title: "Internify by HUMIC Engineering APIs",
|
||||
version: "1.2.0",
|
||||
description: "Comprehensive REST API for managing internship applications, job postings, partnerships, and feedback for the Internify web application. This API provides endpoints for admin management, authentication, internship vacancy management, application processing, student data, partnerships, research results, FAQs, feedback, and batch management. Created by Ramadhana & Yohanes",
|
||||
contact: {
|
||||
name: "HUMIC Engineering",
|
||||
url: "https://humic.dev"
|
||||
}
|
||||
},
|
||||
servers: [
|
||||
{
|
||||
url: process.env.NODE_ENV === 'production'
|
||||
? 'https://internify-ruddy.vercel.app/'
|
||||
: `http://localhost:${process.env.EXPRESS_PORT || 9000}`,
|
||||
description: process.env.NODE_ENV === 'production' ? 'Production server' : 'Development server'
|
||||
}
|
||||
],
|
||||
tags: [
|
||||
{
|
||||
name: "Auth",
|
||||
description: "Authentication endpoints for admin login and profile retrieval"
|
||||
},
|
||||
{
|
||||
name: "Admin",
|
||||
description: "Admin account management endpoints"
|
||||
},
|
||||
{
|
||||
name: "Batch",
|
||||
description: "Batch management for organizing internship cohorts"
|
||||
},
|
||||
{
|
||||
name: "Lowongan Magang",
|
||||
description: "Internship vacancy/job posting management endpoints"
|
||||
},
|
||||
{
|
||||
name: "Lamaran Magang",
|
||||
description: "Internship application management and statistics endpoints"
|
||||
},
|
||||
{
|
||||
name: "Mahasiswa",
|
||||
description: "Student data management endpoints"
|
||||
},
|
||||
{
|
||||
name: "Partnership",
|
||||
description: "Partner organization management endpoints"
|
||||
},
|
||||
{
|
||||
name: "Hasil Research",
|
||||
description: "Internship research results and project showcase endpoints"
|
||||
},
|
||||
{
|
||||
name: "FAQ",
|
||||
description: "Frequently Asked Questions management endpoints"
|
||||
},
|
||||
{
|
||||
name: "Feedback",
|
||||
description: "Internship feedback and testimonial management endpoints"
|
||||
}
|
||||
],
|
||||
components: {
|
||||
securitySchemes: {
|
||||
bearerAuth: {
|
||||
type: "http",
|
||||
scheme: "bearer",
|
||||
bearerFormat: "JWT",
|
||||
description: "JWT token obtained from the /auth-api/login endpoint"
|
||||
},
|
||||
},
|
||||
responses: {
|
||||
UnauthorizedError: {
|
||||
description: "Access token is missing or invalid",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message: {
|
||||
type: "string",
|
||||
example: "Unauthorized access"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
ForbiddenError: {
|
||||
description: "User does not have permission to access this resource",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message: {
|
||||
type: "string",
|
||||
example: "Access denied: Admin only"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
NotFoundError: {
|
||||
description: "The requested resource was not found",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message: {
|
||||
type: "string",
|
||||
example: "Resource not found"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
ValidationError: {
|
||||
description: "Request validation failed",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message: {
|
||||
type: "string",
|
||||
example: "Validation error"
|
||||
},
|
||||
errors: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
InternalServerError: {
|
||||
description: "Internal server error",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
message: {
|
||||
type: "string",
|
||||
example: "Internal server error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
apis: [
|
||||
path.join(__dirname, '../routes/*.js'),
|
||||
path.join(__dirname, '../controllers/*.js'),
|
||||
],
|
||||
};
|
||||
|
||||
const swaggerSpec = swaggerJsDoc(swaggerOptions);
|
||||
|
||||
const setupSwaggerDocs = (app) => {
|
||||
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));
|
||||
console.log("Swagger UI available at /api-docs");
|
||||
};
|
||||
|
||||
module.exports = setupSwaggerDocs;
|
||||
@@ -1,211 +0,0 @@
|
||||
import path from 'path';
|
||||
import type { Application } from 'express';
|
||||
|
||||
const swaggerJsdoc = require('swagger-jsdoc');
|
||||
const swaggerUi = require('swagger-ui-express');
|
||||
|
||||
const port = process.env.PORT || '5000';
|
||||
|
||||
const swaggerOptions = {
|
||||
definition: {
|
||||
openapi: '3.0.0',
|
||||
info: {
|
||||
title: 'Internify LMS API - HUMIC Engineering',
|
||||
version: '1.0.0',
|
||||
description: 'Dokumentasi REST API Internify LMS untuk autentikasi, pengelolaan lowongan magang, lamaran, dan konten platform.',
|
||||
contact: {
|
||||
name: 'HUMIC Engineering',
|
||||
url: 'https://humic.telkomuniversity.ac.id/'
|
||||
}
|
||||
},
|
||||
servers: [
|
||||
{
|
||||
url: process.env.NODE_ENV === 'production'
|
||||
? 'https://your-production-domain.example.com'
|
||||
: `http://localhost:${port}`,
|
||||
description: process.env.NODE_ENV === 'production'
|
||||
? 'Prod'
|
||||
: 'Dev'
|
||||
}
|
||||
],
|
||||
tags: [
|
||||
{
|
||||
name: 'Auth',
|
||||
description: 'Endpoint autentikasi untuk login admin/peserta dan profil pengguna.'
|
||||
},
|
||||
{
|
||||
name: 'Admin',
|
||||
description: 'Endpoint utilitas dan pengelolaan sistem yang terkait admin.'
|
||||
},
|
||||
{
|
||||
name: 'Batch',
|
||||
description: 'Endpoint pengelolaan batch/angkatan magang.'
|
||||
},
|
||||
{
|
||||
name: 'Lowongan Magang',
|
||||
description: 'Endpoint pengelolaan lowongan magang.'
|
||||
},
|
||||
{
|
||||
name: 'Lamaran Magang',
|
||||
description: 'Endpoint pengelolaan lamaran magang.'
|
||||
},
|
||||
{
|
||||
name: 'Mahasiswa',
|
||||
description: 'Endpoint pengelolaan data mahasiswa/peserta.'
|
||||
},
|
||||
{
|
||||
name: 'Partnership',
|
||||
description: 'Endpoint pengelolaan data mitra/partnership.'
|
||||
},
|
||||
{
|
||||
name: 'Hasil Research',
|
||||
description: 'Endpoint pengelolaan hasil research/proyek.'
|
||||
},
|
||||
{
|
||||
name: 'FAQ',
|
||||
description: 'Endpoint pengelolaan FAQ (pertanyaan yang sering diajukan).'
|
||||
},
|
||||
{
|
||||
name: 'Feedback',
|
||||
description: 'Endpoint pengelolaan feedback/testimoni peserta.'
|
||||
}
|
||||
],
|
||||
components: {
|
||||
securitySchemes: {
|
||||
bearerAuth: {
|
||||
type: 'http',
|
||||
scheme: 'bearer',
|
||||
bearerFormat: 'JWT',
|
||||
description: 'Token JWT yang diperoleh dari endpoint /api/auth/login'
|
||||
}
|
||||
},
|
||||
responses: {
|
||||
UnauthorizedError: {
|
||||
description: 'Token akses tidak ada atau tidak valid',
|
||||
content: {
|
||||
'application/json': {
|
||||
examples: {
|
||||
tokenMissing: {
|
||||
value: {
|
||||
status: 'error',
|
||||
statusCode: 401,
|
||||
message: 'Not authorized to access this route, token is missing'
|
||||
}
|
||||
},
|
||||
tokenInvalid: {
|
||||
value: {
|
||||
status: 'error',
|
||||
statusCode: 401,
|
||||
message: 'Not authorized to access this route, token is invalid or expired'
|
||||
}
|
||||
},
|
||||
userNotExist: {
|
||||
value: {
|
||||
status: 'error',
|
||||
statusCode: 401,
|
||||
message: 'User belonging to this token no longer exists'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
ForbiddenError: {
|
||||
description: 'Pengguna tidak memiliki izin untuk mengakses resource ini',
|
||||
content: {
|
||||
'application/json': {
|
||||
example: {
|
||||
status: 'error',
|
||||
statusCode: 403,
|
||||
message: 'You do not have permission to perform this action'
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
NotFoundError: {
|
||||
description: 'Resource yang diminta tidak ditemukan',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
status: {
|
||||
type: 'string',
|
||||
example: 'error'
|
||||
},
|
||||
statusCode: {
|
||||
type: 'integer',
|
||||
example: 404
|
||||
},
|
||||
message: {
|
||||
type: 'string',
|
||||
example: 'Not Found - /api/endpoint-yang-tidak-ada'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
ValidationError: {
|
||||
description: 'Validasi request gagal',
|
||||
content: {
|
||||
'application/json': {
|
||||
example: {
|
||||
status: 'error',
|
||||
statusCode: 400,
|
||||
message: 'Mohon lengkapi semua field wajib yang diperlukan'
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
InternalServerError: {
|
||||
description: 'Terjadi kesalahan pada server internal',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
status: {
|
||||
type: 'string',
|
||||
example: 'error'
|
||||
},
|
||||
statusCode: {
|
||||
type: 'integer',
|
||||
example: 500
|
||||
},
|
||||
message: {
|
||||
type: 'string',
|
||||
example: 'Internal Server Error'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
apis: [
|
||||
path.join(__dirname, '../app.ts').replace(/\\/g, '/'),
|
||||
path.join(__dirname, '../app.js').replace(/\\/g, '/'),
|
||||
path.join(__dirname, '../routes/*.ts').replace(/\\/g, '/'),
|
||||
path.join(__dirname, '../controllers/*.ts').replace(/\\/g, '/'),
|
||||
path.join(__dirname, '../routes/*.js').replace(/\\/g, '/'),
|
||||
path.join(__dirname, '../controllers/*.js').replace(/\\/g, '/')
|
||||
]
|
||||
};
|
||||
|
||||
const swaggerSpec = swaggerJsdoc(swaggerOptions);
|
||||
|
||||
export const setupSwaggerDocs = (app: Application) => {
|
||||
const swaggerEnabledValue = process.env.SWAGGER_ENABLE ?? process.env.SWAGGER_ENABLE ?? 'true';
|
||||
const isSwaggerEnabled = swaggerEnabledValue.toLowerCase() === 'true';
|
||||
if (!isSwaggerEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
|
||||
console.log('Swagger UI available at /api/docs');
|
||||
};
|
||||
|
||||
export default setupSwaggerDocs;
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
const { PrismaClient } = require('../../generated/prisma');
|
||||
|
||||
const prisma = new PrismaClient({
|
||||
log: ['query', 'info', 'warn', 'error'],
|
||||
});
|
||||
|
||||
module.exports = prisma
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
const { PrismaClient } = require("generated/prisma/index.js");
|
||||
|
||||
const prisma = new PrismaClient({
|
||||
log: [
|
||||
{
|
||||
emit: 'event',
|
||||
level: 'query',
|
||||
},
|
||||
{
|
||||
emit: 'stdout',
|
||||
level: 'error',
|
||||
},
|
||||
{
|
||||
emit: 'stdout',
|
||||
level: 'info',
|
||||
},
|
||||
{
|
||||
emit: 'stdout',
|
||||
level: 'warn',
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
module.exports = { prisma };
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const CommonError = require('./common_error');
|
||||
|
||||
class BadRequestError extends CommonError {
|
||||
constructor(message) {
|
||||
super(message || 'Bad Request');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = BadRequestError;
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
class CommonError extends Error {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CommonError;
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const CommonError = require('./common_error');
|
||||
|
||||
class ConflictError extends CommonError {
|
||||
constructor(message) {
|
||||
super(message || 'Conflict');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ConflictError;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
const CommonError = require('./common_error');
|
||||
|
||||
class ExpectationFailedError extends CommonError {
|
||||
constructor(message) {
|
||||
super(message || 'Expectation Failed');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ExpectationFailedError;
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const CommonError = require('./common_error');
|
||||
|
||||
class ForbiddenError extends CommonError {
|
||||
constructor(message) {
|
||||
super(message || 'Forbidden');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ForbiddenError;
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const CommonError = require('./common_error');
|
||||
|
||||
class GatewayTimeoutError extends CommonError {
|
||||
constructor(message) {
|
||||
super(message || 'Gateway Timeout');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = GatewayTimeoutError;
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
const ConflictError = require('./conflict_error');
|
||||
const ExpectationFailedError = require('./expectation_failed_error');
|
||||
const ForbiddenError = require('./forbidden_error');
|
||||
const InternalServerError = require('./internal_server_error');
|
||||
const NotFoundError = require('./not_found_error');
|
||||
const UnauthorizedError = require('./unauthorized_error');
|
||||
const ServiceUnavailableError = require('./service_unavailable_error');
|
||||
const GatewayTimeoutError = require('./gateway_timeout_error');
|
||||
const BadRequestError = require('./bad_request_error');
|
||||
const ValidationError = require('./validation_error');
|
||||
|
||||
module.exports = {
|
||||
ConflictError,
|
||||
ExpectationFailedError,
|
||||
ForbiddenError,
|
||||
InternalServerError,
|
||||
NotFoundError,
|
||||
UnauthorizedError,
|
||||
ServiceUnavailableError,
|
||||
GatewayTimeoutError,
|
||||
BadRequestError,
|
||||
ValidationError
|
||||
};
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const CommonError = require('./common_error');
|
||||
|
||||
class InternalServerError extends CommonError {
|
||||
constructor(message) {
|
||||
super(message || 'Internal Server Error');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InternalServerError;
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const CommonError = require('./common_error');
|
||||
|
||||
class NotFoundError extends CommonError {
|
||||
constructor(message) {
|
||||
super(message || 'Not Found');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = NotFoundError;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
const CommonError = require('./common_error');
|
||||
|
||||
class ServiceUnavailableError extends CommonError {
|
||||
constructor(message) {
|
||||
super(message || 'Service Unavailable');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ServiceUnavailableError;
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const CommonError = require('./common_error');
|
||||
|
||||
class Unauthorized extends CommonError {
|
||||
constructor(message) {
|
||||
super(message || 'Unauthorized');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Unauthorized;
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
class ValidationError extends Error {
|
||||
constructor(message, errors) {
|
||||
super(message || 'Validation Error');
|
||||
this.errors = errors
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ValidationError;
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
const ERROR = {
|
||||
'BAD_REQUEST': 400,
|
||||
'NOT_FOUND': 404,
|
||||
'INTERNAL_ERROR': 500,
|
||||
'CONFLICT': 409,
|
||||
'EXPECTATION_FAILED': 417,
|
||||
'FORBIDDEN': 403,
|
||||
'UNAUTHORIZED': 401,
|
||||
'SERVICE_UNAVAILABLE': 503,
|
||||
'GATEWAY_TIMEOUT': 504
|
||||
};
|
||||
|
||||
const SUCCESS = {
|
||||
'OK': 200,
|
||||
'CREATED': 201
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
ERROR,
|
||||
SUCCESS
|
||||
};
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
const dotnev = require('dotenv');
|
||||
|
||||
dotnev.config({ path: '.env' })
|
||||
|
||||
const config = {
|
||||
port: process.env.EXPRESS_PORT,
|
||||
jwtPrivateKey: process.env.JWT_PRIVATE_KEY,
|
||||
jwtPublicKey: process.env.JWT_PUBLIC_KEY,
|
||||
nodeEnv: process.env.NODE_ENV,
|
||||
mysqlConfig: {
|
||||
host: process.env.MYSQL_HOST,
|
||||
user: process.env.MYSQL_USER,
|
||||
password: process.env.MYSQL_PASSWORD,
|
||||
database: process.env.MYSQL_DATABASE,
|
||||
dialect: 'mysql',
|
||||
logging: false
|
||||
},
|
||||
nodemailerConfig: {
|
||||
email: process.env.NODEMAILER_EMAIL,
|
||||
password: process.env.NODEMAILER_PASSWORD
|
||||
},
|
||||
cloudinaryConfig: {
|
||||
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
|
||||
api_key: process.env.CLOUDINARY_API_KEY,
|
||||
api_secret: process.env.CLOUDINARY_API_SECRET,
|
||||
secure: true
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { config };
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
const path = require('path');
|
||||
const fs = require('fs').promises;
|
||||
const fsSync = require('fs');
|
||||
|
||||
async function deleteFileIfExists(fileName) {
|
||||
try {
|
||||
const uploadDir = process.env.NODE_ENV === 'production'
|
||||
? '/tmp/uploads'
|
||||
: path.join(__dirname, '..', '..', 'uploads');
|
||||
|
||||
const fullPath = path.join(uploadDir, fileName);
|
||||
await fs.access(fullPath);
|
||||
await fs.unlink(fullPath);
|
||||
console.log(`File dihapus: ${fullPath}`);
|
||||
} catch (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
console.warn(`File tidak ditemukan: ${fileName}`);
|
||||
} else {
|
||||
console.error(`Gagal menghapus file (${fileName}):`, err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function checkFileExists(filePath) {
|
||||
try {
|
||||
if (!filePath) return false;
|
||||
|
||||
const uploadDir = process.env.NODE_ENV === 'production'
|
||||
? '/tmp/uploads'
|
||||
: path.join(__dirname, '..', '..', 'uploads');
|
||||
|
||||
const fileName = path.basename(filePath);
|
||||
const fullPath = path.join(uploadDir, fileName);
|
||||
|
||||
return fsSync.existsSync(fullPath);
|
||||
} catch (err) {
|
||||
console.error(`Error checking file existence: ${err.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function validateImagePath(imagePath) {
|
||||
if (!imagePath) return null;
|
||||
|
||||
const fileExists = checkFileExists(imagePath);
|
||||
return fileExists ? imagePath : null;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
deleteFileIfExists,
|
||||
checkFileExists,
|
||||
validateImagePath
|
||||
};
|
||||
Executable
+57
@@ -0,0 +1,57 @@
|
||||
const { BadRequestError } = require('../error');
|
||||
|
||||
class ImageUploadHelper {
|
||||
uploadImage(file) {
|
||||
if (!file) {
|
||||
throw new BadRequestError('Please upload an image!');
|
||||
}
|
||||
return `/uploads/${file.filename}`;
|
||||
}
|
||||
|
||||
uploadCV(file) {
|
||||
if (!file) {
|
||||
throw new BadRequestError('Please upload your CV');
|
||||
}
|
||||
return `/uploads/${file.filename}`;
|
||||
}
|
||||
|
||||
uploadPortofolio(file) {
|
||||
if (!file) {
|
||||
throw new BadRequestError('Please upload your portfolio');
|
||||
}
|
||||
return `/uploads/${file.filename}`;
|
||||
}
|
||||
|
||||
validateImage(file) {
|
||||
if (!file) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
|
||||
return allowedTypes.includes(file.mimetype);
|
||||
}
|
||||
|
||||
validatePDF(file) {
|
||||
if (!file) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const allowedTypes = ['application/pdf'];
|
||||
return allowedTypes.includes(file.mimetype);
|
||||
}
|
||||
|
||||
validateDocument(file) {
|
||||
if (!file) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const allowedTypes = [
|
||||
'application/pdf',
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|
||||
];
|
||||
return allowedTypes.includes(file.mimetype);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new ImageUploadHelper();
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
require('dotenv').config();
|
||||
const nodemailer = require('nodemailer');
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
service: 'gmail',
|
||||
auth: {
|
||||
user: process.env.AUTH_EMAIL,
|
||||
pass: process.env.AUTH_PASSWORD,
|
||||
},
|
||||
});
|
||||
|
||||
transporter.verify((error) => {
|
||||
if (error) {
|
||||
console.log('Error setup email:', error);
|
||||
} else {
|
||||
console.log('Server siap mengirim email');
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = transporter;
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
const wrapper = require('./wrapper');
|
||||
const { ValidationError } = require('../error');
|
||||
|
||||
const isValidPayload = (payload, model) => {
|
||||
const { value, error } = model.validate(payload, {
|
||||
abortEarly: false,
|
||||
allowUnknown: true,
|
||||
stripUnknown: true,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
let errors = {};
|
||||
error.details.forEach(element => {
|
||||
errors[element.path[0]] = element.message;
|
||||
});
|
||||
|
||||
return wrapper.error(new ValidationError('Validation Error', errors));
|
||||
}
|
||||
|
||||
return { err: null, data: value };
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
isValidPayload,
|
||||
};
|
||||
Executable
+95
@@ -0,0 +1,95 @@
|
||||
const {
|
||||
NotFoundError,
|
||||
InternalServerError,
|
||||
BadRequestError,
|
||||
ConflictError,
|
||||
ExpectationFailedError,
|
||||
ForbiddenError,
|
||||
GatewayTimeoutError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError
|
||||
} = require('../error');
|
||||
const { ERROR: httpError } = require('../http-status/status_code');
|
||||
|
||||
const response = (res, type, result, message = '', code = 200) => {
|
||||
let status = true;
|
||||
let data = result?.data ?? null;
|
||||
|
||||
if (type === 'fail') {
|
||||
status = false;
|
||||
data = null;
|
||||
message = result.err instanceof ValidationError ? result.err.errors : result.err?.message || message;
|
||||
code = checkErrorCode(result.err);
|
||||
}
|
||||
|
||||
res.status(code).json({
|
||||
status,
|
||||
data,
|
||||
message,
|
||||
code,
|
||||
});
|
||||
};
|
||||
|
||||
const paginationResponse = (res, type, result, message = '', code = 200) => {
|
||||
let status = true;
|
||||
let data = result?.data ?? null;
|
||||
let meta = result?.meta ?? null;
|
||||
if (type === 'fail') {
|
||||
status = false;
|
||||
data = '';
|
||||
message = result.err instanceof ValidationError ? { errors: result.err.errors } : result.err?.message || message;
|
||||
code = checkErrorCode(result.err);
|
||||
}
|
||||
|
||||
console.log(typeof message)
|
||||
|
||||
res.status(code).json({
|
||||
status: status,
|
||||
data,
|
||||
meta,
|
||||
message,
|
||||
code,
|
||||
});
|
||||
}
|
||||
|
||||
const checkErrorCode = (error) => {
|
||||
switch (error.constructor) {
|
||||
case BadRequestError:
|
||||
return httpError.BAD_REQUEST;
|
||||
case ConflictError:
|
||||
return httpError.CONFLICT;
|
||||
case ExpectationFailedError:
|
||||
return httpError.EXPECTATION_FAILED;
|
||||
case ForbiddenError:
|
||||
return httpError.FORBIDDEN;
|
||||
case GatewayTimeoutError:
|
||||
return httpError.GATEWAY_TIMEOUT;
|
||||
case InternalServerError:
|
||||
return httpError.INTERNAL_ERROR;
|
||||
case NotFoundError:
|
||||
return httpError.NOT_FOUND;
|
||||
case ServiceUnavailableError:
|
||||
return httpError.SERVICE_UNAVAILABLE;
|
||||
case UnauthorizedError:
|
||||
return httpError.UNAUTHORIZED;
|
||||
case ValidationError:
|
||||
return httpError.BAD_REQUEST;
|
||||
default:
|
||||
return httpError.INTERNAL_ERROR;
|
||||
}
|
||||
};
|
||||
|
||||
const data = (data) => ({ err: null, data });
|
||||
|
||||
const paginationData = (data, meta) => ({ err: null, data, meta });
|
||||
|
||||
const error = (err) => ({ err, data: null });
|
||||
|
||||
module.exports = {
|
||||
data,
|
||||
paginationData,
|
||||
error,
|
||||
response,
|
||||
paginationResponse
|
||||
};
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
require('dotenv').config();
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const path = require('path');
|
||||
const adminRoutes = require('./routes/admin.routes');
|
||||
const authRoutes = require('./routes/auth.routes');
|
||||
const lowonganMagangRoutes = require('./routes/lowonganMagang.routes');
|
||||
const lamaranMagangRoutes = require('./routes/lamaranMagang.routes');
|
||||
const mahasiswaRoutes = require('./routes/mahasiswa.routes');
|
||||
const partnershipRoutes = require('./routes/partnership.routes');
|
||||
const hasilResearchRoutes = require('./routes/hasilResearch.routes');
|
||||
const faqRoutes = require('./routes/faq.routes');
|
||||
const feedbackRoutes = require('./routes/feedback.routes');
|
||||
const batchRoutes = require('./routes/batch.routes');
|
||||
const setupSwaggerDocs = require('./docs/swagger');
|
||||
|
||||
const PORT = process.env.PORT;
|
||||
const app = express();
|
||||
|
||||
const corsOptions = {
|
||||
origin: true,
|
||||
methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE", "OPTIONS"],
|
||||
credentials: true,
|
||||
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With", "Accept"],
|
||||
exposedHeaders: ["Content-Range", "X-Content-Range"],
|
||||
optionsSuccessStatus: 200,
|
||||
};
|
||||
|
||||
const uploadDir = process.env.NODE_ENV === 'production'
|
||||
? '/tmp/uploads'
|
||||
: path.join(__dirname, 'uploads');
|
||||
|
||||
app.options('*', cors(corsOptions));
|
||||
|
||||
app.use(express.json());
|
||||
app.use(cors(corsOptions));
|
||||
|
||||
app.use("/uploads", express.static(uploadDir), (req, res, next) => {
|
||||
if (!res.headersSent) {
|
||||
res.status(404).json({
|
||||
status: false,
|
||||
message: `File not found: ${req.path}`,
|
||||
code: 404
|
||||
});
|
||||
}
|
||||
});
|
||||
app.use("/admin-api", adminRoutes);
|
||||
app.use("/auth-api", authRoutes);
|
||||
app.use("/lowongan-magang-api", lowonganMagangRoutes);
|
||||
app.use("/lamaran-magang-api", lamaranMagangRoutes);
|
||||
app.use("/mahasiswa-api", mahasiswaRoutes);
|
||||
app.use("/partnership-api", partnershipRoutes);
|
||||
app.use("/hasil-research-api", hasilResearchRoutes);
|
||||
app.use("/faq-api", faqRoutes);
|
||||
app.use("/feedback-api", feedbackRoutes);
|
||||
app.use("/batch-api", batchRoutes);
|
||||
|
||||
setupSwaggerDocs(app);
|
||||
|
||||
app.use((req, res) => {
|
||||
res.status(404).json({
|
||||
status: false,
|
||||
message: `Route not found: ${req.method} ${req.path}`,
|
||||
code: 404
|
||||
});
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
app.listen(PORT, () => {
|
||||
console.log(`listening at http://localhost:${PORT}`);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = app;
|
||||
|
||||
/*
|
||||
NOTE : saran saya untuk penamaan variabel untuk setiap response dibuat konsisten menjadi inggris, tolong komunikasi aja ke fe 😁
|
||||
*/
|
||||
@@ -1,31 +0,0 @@
|
||||
import dotenv from 'dotenv';
|
||||
dotenv.config();
|
||||
|
||||
import app from './app';
|
||||
|
||||
const PORT = process.env.PORT || 5000;
|
||||
const NODE_ENV = process.env.NODE_ENV || 'development';
|
||||
|
||||
const server = app.listen(PORT, () => {
|
||||
console.log(`=========================================`);
|
||||
console.log(` Server jalanin di ${PORT} `);
|
||||
console.log(` Environment: ${NODE_ENV} `);
|
||||
console.log(` API base: http://localhost:${PORT}/api `);
|
||||
console.log(`=========================================`);
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (err: Error) => {
|
||||
console.error(`[Unhandled Rejection] Shutting down...`);
|
||||
console.error(err.name, err.message);
|
||||
server.close(() => {
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
|
||||
process.on('uncaughtException', (err: Error) => {
|
||||
console.error(`[Uncaught Exception] Shutting down...`);
|
||||
console.error(err.name, err.message);
|
||||
server.close(() => {
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +0,0 @@
|
||||
import { PrismaClient } from '../generated/prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
export default prisma;
|
||||
@@ -1,67 +0,0 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import prisma from '../lib/prisma';
|
||||
import { CustomError } from './errorHandler';
|
||||
|
||||
export interface AuthenticatedRequest extends Request {
|
||||
user?: {
|
||||
id: string;
|
||||
email: string;
|
||||
role: 'ADMIN' | 'STUDENT';
|
||||
};
|
||||
}
|
||||
|
||||
export const protect = async (req: AuthenticatedRequest, _res: Response, next: NextFunction) => {
|
||||
let token: string | undefined;
|
||||
|
||||
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
|
||||
token = req.headers.authorization.split(' ')[1];
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
const error: CustomError = new Error('Not authorized to access this route, token is missing');
|
||||
error.statusCode = 401;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET || 'internify_secret_key_2026_dev') as {
|
||||
id: string;
|
||||
email: string;
|
||||
role: 'ADMIN' | 'STUDENT';
|
||||
};
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: decoded.id },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
const error: CustomError = new Error('User belonging to this token no longer exists');
|
||||
error.statusCode = 401;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
req.user = user as { id: string; email: string; role: 'ADMIN' | 'STUDENT' };
|
||||
next();
|
||||
} catch (err) {
|
||||
const error: CustomError = new Error('Not authorized to access this route, token is invalid or expired');
|
||||
error.statusCode = 401;
|
||||
return next(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const restrictTo = (...roles: ('ADMIN' | 'STUDENT')[]) => {
|
||||
return (req: AuthenticatedRequest, _res: Response, next: NextFunction) => {
|
||||
if (!req.user || !roles.includes(req.user.role)) {
|
||||
const error: CustomError = new Error('You do not have permission to perform this action');
|
||||
error.statusCode = 403;
|
||||
return next(error);
|
||||
}
|
||||
next();
|
||||
};
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
export interface CustomError extends Error {
|
||||
statusCode?: number;
|
||||
}
|
||||
|
||||
export const errorHandler = (
|
||||
err: CustomError,
|
||||
_req: Request,
|
||||
res: Response,
|
||||
_next: NextFunction
|
||||
) => {
|
||||
const statusCode = err.statusCode || 500;
|
||||
const message = err.message || 'Internal Server Error';
|
||||
|
||||
console.error(`[Error] ${statusCode} - ${message}`);
|
||||
if (err.stack) {
|
||||
console.error(err.stack);
|
||||
}
|
||||
|
||||
res.status(statusCode).json({
|
||||
status: 'error',
|
||||
statusCode,
|
||||
message,
|
||||
...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
|
||||
});
|
||||
};
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
const { UnauthorizedError } = require('../helpers/error')
|
||||
const { response } = require('../helpers/utils/wrapper');
|
||||
const { ERROR } = require('../helpers/http-status/status_code');
|
||||
|
||||
module.exports = function isAdmin(req, res, next) {
|
||||
if (req.role && req.role === 'admin') {
|
||||
return next();
|
||||
}
|
||||
|
||||
return response(res, 'fail', new UnauthorizedError('Akses ditolak: Hanya admin yang dapat mengakses ini'), 'Akses ditolak: Hanya admin yang dapat mengakses ini', ERROR.UNAUTHORIZED);
|
||||
}
|
||||
Executable
+124
@@ -0,0 +1,124 @@
|
||||
const multer = require('multer');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { response } = require('../helpers/utils/wrapper')
|
||||
|
||||
const uploadDir = process.env.NODE_ENV === 'production'
|
||||
? '/tmp/uploads'
|
||||
: path.join(__dirname, '../uploads');
|
||||
|
||||
if (!fs.existsSync(uploadDir)) {
|
||||
fs.mkdirSync(uploadDir, { recursive: true });
|
||||
}
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (_req, _file, cb) => cb(null, uploadDir),
|
||||
filename: (_req, file, cb) => {
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
|
||||
cb(null, uniqueSuffix + path.extname(file.originalname));
|
||||
},
|
||||
});
|
||||
|
||||
const fileFilter = (req, file, cb) => {
|
||||
const allowedMimeTypes = [
|
||||
'image/jpeg',
|
||||
'image/jpg',
|
||||
'image/png',
|
||||
'application/pdf'
|
||||
];
|
||||
|
||||
if (allowedMimeTypes.includes(file.mimetype)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
const errMsg = 'Can only upload images (jpeg, jpg, png) or PDF files';
|
||||
req.fileValidationError = errMsg;
|
||||
cb(new Error(errMsg), false);
|
||||
}
|
||||
};
|
||||
|
||||
const upload = multer({
|
||||
storage: storage,
|
||||
fileFilter: fileFilter,
|
||||
});
|
||||
|
||||
// middleware untuk ngechek ukuran file
|
||||
const checkFileSizes = (req, res, next) => {
|
||||
const maxSize = 5 * 1024 * 1024; // 5MB
|
||||
const errors = {};
|
||||
const filesToDelete = [];
|
||||
|
||||
const allFiles = [];
|
||||
// ini untuk 1 file
|
||||
if (req.file) allFiles.push(req.file);
|
||||
|
||||
// ini untuk multiple files
|
||||
if (req.files) {
|
||||
if (Array.isArray(req.files)) {
|
||||
allFiles.push(...req.files);
|
||||
} else {
|
||||
Object.values(req.files).flat().forEach(file => allFiles.push(file));
|
||||
}
|
||||
}
|
||||
|
||||
allFiles.forEach(file => {
|
||||
if (file.size > maxSize) {
|
||||
errors[file.fieldname] = `Ukuran file ${file.fieldname} terlalu besar. Maksimal 5MB`;
|
||||
}
|
||||
filesToDelete.push(file.path);
|
||||
});
|
||||
|
||||
// ini untuk jika ada error maka file yang terupload dihapus
|
||||
if (Object.keys(errors).length > 0) {
|
||||
filesToDelete.forEach(filePath => {
|
||||
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
||||
});
|
||||
|
||||
return res.status(413).json({
|
||||
status: false,
|
||||
data: null,
|
||||
message: errors,
|
||||
code: 413,
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
|
||||
// middleware untuk error multer
|
||||
const multerErrorHandler = (err, req, res, next) => {
|
||||
if (err instanceof multer.MulterError) {
|
||||
if (err.code === 'LIMIT_UNEXPECTED_FILE') {
|
||||
return res.status(400).json({
|
||||
status: false,
|
||||
data: null,
|
||||
message: {
|
||||
[err.field]: `Field '${err.field}' tidak boleh memiliki lebih dari 1 file.`,
|
||||
},
|
||||
code: 400,
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(400).json({
|
||||
status: false,
|
||||
data: null,
|
||||
message: err.message,
|
||||
code: 400,
|
||||
});
|
||||
}
|
||||
|
||||
if (err) {
|
||||
return res.status(400).json({
|
||||
status: false,
|
||||
data: null,
|
||||
message: err.message || 'Error saat upload file',
|
||||
code: 400,
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
module.exports = upload;
|
||||
module.exports.multerErrorHandler = multerErrorHandler;
|
||||
module.exports.checkFileSizes = checkFileSizes;
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
const axios = require('axios');
|
||||
const path = require('path');
|
||||
const { deleteFileIfExists } = require('../helpers/utils/fileHelper');
|
||||
const { response } = require('../helpers/utils/wrapper');
|
||||
const { SUCCESS, ERROR } = require('../helpers/http-status/status_code');
|
||||
|
||||
const verifyRecaptcha = async (req, res, next) => {
|
||||
const recaptchaToken = req.body?.['g-recaptcha-response'] || req.query?.['g-recaptcha-response'];
|
||||
|
||||
const cv = req.files.cv?.[0]?.filename;
|
||||
const pdf = req.files.portofolio?.[0]?.filename;
|
||||
const files = [cv, pdf];
|
||||
|
||||
if (!recaptchaToken) {
|
||||
await deleteFiles(files);
|
||||
return response(res, "fail", { err: 'Recaptcha token is missing' }, "Recaptcha Verification Failed", ERROR.BAD_REQUEST);
|
||||
}
|
||||
|
||||
try {
|
||||
const secretKey = process.env.RECAPTCHA_SECRET_KEY;
|
||||
const response = await axios.post(
|
||||
`https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${recaptchaToken}`
|
||||
)
|
||||
if (!response.data.success) {
|
||||
await deleteFiles(files);
|
||||
return res.status(400).json({ message: 'Recaptcha verification failed' });
|
||||
}
|
||||
return next();
|
||||
} catch (error) {
|
||||
console.error('Recaptcha verification error:', error);
|
||||
res.status(500).json({ message: 'Recaptcha verification failed' });
|
||||
}
|
||||
};
|
||||
|
||||
async function deleteFiles(files) {
|
||||
for (const file of files) {
|
||||
if (file) {
|
||||
const fileName = path.basename(`/uploads/${file}`);
|
||||
await deleteFileIfExists(fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = verifyRecaptcha;
|
||||
@@ -1,46 +0,0 @@
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (_req, file, cb) => {
|
||||
let folder = 'uploads/';
|
||||
if (file.fieldname === 'cv' || file.fieldname === 'portofolio') {
|
||||
folder += 'docs/';
|
||||
} else {
|
||||
folder += 'images/';
|
||||
}
|
||||
|
||||
fs.mkdirSync(folder, { recursive: true });
|
||||
cb(null, folder);
|
||||
},
|
||||
filename: (_req, file, cb) => {
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
|
||||
const ext = path.extname(file.originalname);
|
||||
cb(null, `${file.fieldname}-${uniqueSuffix}${ext}`);
|
||||
}
|
||||
});
|
||||
|
||||
const fileFilter = (_req: any, file: any, cb: any) => {
|
||||
if (file.fieldname === 'cv' || file.fieldname === 'portofolio') {
|
||||
if (file.mimetype === 'application/pdf') {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error('CV dan Portofolio harus dalam format PDF!'), false);
|
||||
}
|
||||
} else {
|
||||
if (file.mimetype.startsWith('image/')) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error('File upload harus berupa gambar!'), false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const upload = multer({
|
||||
storage: storage,
|
||||
fileFilter: fileFilter,
|
||||
limits: {
|
||||
fileSize: 10 * 1024 * 1024, // Maksimal 10MB yaa, nanti paling bisa diganti oleh admin melalui website
|
||||
}
|
||||
});
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
const { config } = require('../helpers/infra/global_config');
|
||||
const { response } = require('../helpers/utils/wrapper');
|
||||
const { UnauthorizedError } = require('../helpers/error');
|
||||
const { UNAUTHORIZED } = require('../helpers/http-status/status_code');
|
||||
|
||||
const privateKey = config.jwtPrivateKey ? config.jwtPrivateKey.replace(/\\n/g, '\n') : null;
|
||||
const publicKey = config.jwtPublicKey ? config.jwtPublicKey.replace(/\\n/g, '\n') : null;
|
||||
|
||||
const createToken = (data) => {
|
||||
if (!privateKey) {
|
||||
throw new Error('JWT private key not configured');
|
||||
}
|
||||
|
||||
const accessToken = jwt.sign(
|
||||
{
|
||||
id: data.id,
|
||||
email: data.email,
|
||||
role: data.role,
|
||||
signature: data.signature
|
||||
},
|
||||
privateKey,
|
||||
{ algorithm: 'RS256', expiresIn: '1d' }
|
||||
);
|
||||
|
||||
return accessToken;
|
||||
};
|
||||
|
||||
const verifyJWT = async (req, res, next) => {
|
||||
try {
|
||||
const { authorization } = req.headers;
|
||||
|
||||
if (!authorization || !authorization.startsWith('Bearer ')) {
|
||||
const err = new UnauthorizedError('Token is required and must be in Bearer format');
|
||||
return response(res, "fail", { err }, "Unauthorized", UNAUTHORIZED);
|
||||
}
|
||||
|
||||
const token = authorization.split(' ')[1];
|
||||
|
||||
if (!publicKey) {
|
||||
const err = new UnauthorizedError('JWT public key not configured');
|
||||
return response(res, "fail", { err }, "Server Configuration Error", UNAUTHORIZED);
|
||||
}
|
||||
|
||||
jwt.verify(token, publicKey, { algorithms: ['RS256'] }, (err, decoded) => {
|
||||
if (err) {
|
||||
let unauthorizedError;
|
||||
if (err instanceof jwt.TokenExpiredError) {
|
||||
unauthorizedError = new UnauthorizedError('Token has expired', err);
|
||||
} else if (err instanceof jwt.JsonWebTokenError) {
|
||||
unauthorizedError = new UnauthorizedError('Invalid Token', err);
|
||||
} else {
|
||||
unauthorizedError = new UnauthorizedError('Token verification failed', err);
|
||||
}
|
||||
return response(res, "fail", { err: unauthorizedError }, "Unauthorized", UNAUTHORIZED);
|
||||
}
|
||||
|
||||
req.id = decoded.id;
|
||||
req.role = decoded.role;
|
||||
req.signature = decoded.signature;
|
||||
req.email = decoded.email;
|
||||
|
||||
next();
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
const unauthorizedError = new UnauthorizedError(err.message);
|
||||
return response(res, "fail", { err: unauthorizedError }, "Unauthorized", UNAUTHORIZED);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { verifyJWT, createToken };
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
const adminService = require('../services/admin.service');
|
||||
const { response, data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { SUCCESS, ERROR } = require('../../../helpers/http-status/status_code');
|
||||
const { ForbiddenError, BadRequestError, NotFoundError, InternalServerError } = require('../../../helpers/error');
|
||||
const { isValidPayload } = require('../../../helpers/utils/validator');
|
||||
const { createAdminModel, updateAdminModel } = require('../models/admin.model');
|
||||
|
||||
class AdminController {
|
||||
async addAdmin(req, res) {
|
||||
try {
|
||||
const validatePayload = isValidPayload(req.body, createAdminModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await adminService.createAdmin(validatePayload.data);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', data(), 'Admin berhasil dibuat', SUCCESS.CREATED);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getAdmins(req, res) {
|
||||
try {
|
||||
const result = await adminService.getAllAdmins();
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
if (!result.data || result.data.length === 0) {
|
||||
return response(res, 'fail', error(new NotFoundError('Tidak ada admin ditemukan')));
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Admin berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getAdminById(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await adminService.getAdminById(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Admin berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async updateAdmin(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, updateAdminModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await adminService.updateAdmin(id, validatePayload.data);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', data(), 'Admin berhasil diperbarui', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteAdmin(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await adminService.deleteAdmin(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', data(), 'Admin berhasil dihapus', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AdminController();
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const adminController = require('./controllers/admin.controller');
|
||||
const adminService = require('./services/admin.service');
|
||||
const adminRepository = require('./repositories/admin.repository');
|
||||
|
||||
module.exports = {
|
||||
adminController,
|
||||
adminService,
|
||||
adminRepository
|
||||
};
|
||||
Executable
+75
@@ -0,0 +1,75 @@
|
||||
const joi = require('joi');
|
||||
|
||||
const createAdminModel = joi.object().keys({
|
||||
nama_depan: joi.string().max(255).required().messages({
|
||||
'string.base': 'Nama depan harus berupa teks.',
|
||||
'string.empty': 'Nama depan tidak boleh kosong.',
|
||||
'string.max': 'Nama depan maksimal {#limit} karakter.',
|
||||
'any.required': 'Nama depan wajib diisi.',
|
||||
}),
|
||||
|
||||
nama_belakang: joi.string().max(255).required().messages({
|
||||
'string.base': 'Nama belakang harus berupa teks.',
|
||||
'string.empty': 'Nama belakang tidak boleh kosong.',
|
||||
'string.max': 'Nama belakang maksimal {#limit} karakter.',
|
||||
'any.required': 'Nama belakang wajib diisi.',
|
||||
}),
|
||||
|
||||
email: joi.string().email({ tlds: { allow: false } }).max(255).required().messages({
|
||||
'string.base': 'Email harus berupa teks.',
|
||||
'string.empty': 'Email tidak boleh kosong.',
|
||||
'string.email': 'Format email tidak valid.',
|
||||
'string.max': 'Email maksimal {#limit} karakter.',
|
||||
'any.required': 'Email wajib diisi.',
|
||||
}),
|
||||
|
||||
password: joi.string().min(8).required().messages({
|
||||
'string.base': 'Password harus berupa teks.',
|
||||
'string.empty': 'Password tidak boleh kosong.',
|
||||
'string.min': 'Password minimal {#limit} karakter.',
|
||||
'any.required': 'Password wajib diisi.',
|
||||
}),
|
||||
|
||||
role: joi.string().valid('admin').default('admin').messages({
|
||||
'string.base': 'Role harus berupa teks.',
|
||||
'any.only': 'Role hanya boleh "admin".',
|
||||
}),
|
||||
|
||||
signature: joi.string().optional().allow('', null).messages({
|
||||
'string.base': 'Signature harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
const updateAdminModel = joi.object().keys({
|
||||
nama_depan: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Nama depan harus berupa teks.',
|
||||
'string.empty': 'Nama depan tidak boleh kosong.',
|
||||
'string.max': 'Nama depan maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
nama_belakang: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Nama belakang harus berupa teks.',
|
||||
'string.empty': 'Nama belakang tidak boleh kosong.',
|
||||
'string.max': 'Nama belakang maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
email: joi.string().email({ tlds: { allow: false } }).max(255).optional().messages({
|
||||
'string.base': 'Email harus berupa teks.',
|
||||
'string.email': 'Format email tidak valid.',
|
||||
'string.max': 'Email maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
password: joi.string().min(8).optional().messages({
|
||||
'string.base': 'Password harus berupa teks.',
|
||||
'string.min': 'Password minimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
signature: joi.string().optional().allow('', null).messages({
|
||||
'string.base': 'Signature harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
createAdminModel,
|
||||
updateAdminModel,
|
||||
};
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
const prisma = require('../../../helpers/db/db_connection');
|
||||
|
||||
class AdminRepository {
|
||||
async create(adminData) {
|
||||
return prisma.admin.create({
|
||||
data: adminData
|
||||
});
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
return prisma.admin.findMany();
|
||||
}
|
||||
|
||||
async findByEmail(email) {
|
||||
return prisma.admin.findUnique({
|
||||
where: { email }
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id) {
|
||||
return prisma.admin.findUnique({
|
||||
where: { id: parseInt(id) }
|
||||
});
|
||||
}
|
||||
|
||||
async updateById(id, adminData) {
|
||||
return prisma.admin.update({
|
||||
where: { id: parseInt(id) },
|
||||
data: adminData
|
||||
});
|
||||
}
|
||||
|
||||
async deleteById(id) {
|
||||
return prisma.admin.delete({
|
||||
where: { id: parseInt(id) }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AdminRepository();
|
||||
Executable
+114
@@ -0,0 +1,114 @@
|
||||
const bcrypt = require('bcrypt');
|
||||
const adminRepository = require('../repositories/admin.repository');
|
||||
const { data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { BadRequestError, NotFoundError } = require('../../../helpers/error');
|
||||
|
||||
class AdminService {
|
||||
async createAdmin(adminData) {
|
||||
try {
|
||||
const { nama_depan, nama_belakang, email, password, role } = adminData;
|
||||
|
||||
const existingAdmin = await adminRepository.findByEmail(email);
|
||||
|
||||
if (existingAdmin) {
|
||||
return error(new BadRequestError('Email sudah terdaftar'));
|
||||
}
|
||||
|
||||
const saltRounds = 10;
|
||||
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
||||
|
||||
const newAdminData = {
|
||||
nama_depan,
|
||||
nama_belakang,
|
||||
email,
|
||||
password: hashedPassword,
|
||||
role,
|
||||
signature: `${nama_depan}-${Date.now()}`,
|
||||
};
|
||||
|
||||
await adminRepository.create(newAdminData);
|
||||
return data();
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllAdmins() {
|
||||
try {
|
||||
const admins = await adminRepository.findAll();
|
||||
if (!admins || admins.length === 0) {
|
||||
return error(new NotFoundError('Tidak ada admin ditemukan'));
|
||||
}
|
||||
return data(admins);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAdminById(id) {
|
||||
try {
|
||||
const admin = await adminRepository.findById(id);
|
||||
if (!admin) {
|
||||
return error(new NotFoundError('Admin tidak ditemukan'));
|
||||
}
|
||||
return data(admin);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAdminByEmail(email) {
|
||||
try {
|
||||
const admin = await adminRepository.findByEmail(email);
|
||||
return data(admin);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async verifyPassword(plainPassword, hashedPassword) {
|
||||
try {
|
||||
const isValid = await bcrypt.compare(plainPassword, hashedPassword);
|
||||
return data(isValid);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async updateAdmin(id, adminData) {
|
||||
try {
|
||||
const adminResult = await this.getAdminById(id);
|
||||
if (adminResult.err) {
|
||||
return adminResult;
|
||||
}
|
||||
|
||||
if (adminData.email) {
|
||||
const existingAdmin = await adminRepository.findByEmail(adminData.email);
|
||||
if (existingAdmin && existingAdmin.id !== id) {
|
||||
return error(new BadRequestError('Email sudah terdaftar'));
|
||||
}
|
||||
}
|
||||
|
||||
await adminRepository.updateById(id, adminData);
|
||||
return data();
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteAdmin(id) {
|
||||
try {
|
||||
const adminResult = await this.getAdminById(id);
|
||||
if (adminResult.err) {
|
||||
return adminResult;
|
||||
}
|
||||
|
||||
await adminRepository.deleteById(id);
|
||||
return data();
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AdminService();
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
const authService = require('../services/auth.service');
|
||||
const { response, data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { SUCCESS, ERROR } = require('../../../helpers/http-status/status_code');
|
||||
const { BadRequestError, UnauthorizedError, InternalServerError } = require('../../../helpers/error');
|
||||
const { isValidPayload } = require('../../../helpers/utils/validator');
|
||||
const { loginModel } = require('../models/auth.model');
|
||||
|
||||
class AuthController {
|
||||
async login(req, res) {
|
||||
try {
|
||||
const validatePayload = isValidPayload(req.body, loginModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const { email, password } = validatePayload.data;
|
||||
const result = await authService.login(email, password);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
console.log(result.data.token)
|
||||
res.cookie("token", result.data.token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'None',
|
||||
maxAge: 7 * 24 * 60 * 60,
|
||||
});
|
||||
|
||||
return response(res, 'success', result, 'Login berhasil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async me(req, res) {
|
||||
try {
|
||||
const id = req.id;
|
||||
|
||||
if (!id) {
|
||||
return response(res, 'fail', error(new UnauthorizedError('Tidak diotorisasi: ID pengguna tidak ditemukan')));
|
||||
}
|
||||
|
||||
const result = await authService.getCurrentUser(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Pengguna berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async logout(req, res) {
|
||||
try {
|
||||
return response(res, 'success', data(), 'Logout berhasil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AuthController();
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
const authController = require('./controllers/auth.controller');
|
||||
const authService = require('./services/auth.service');
|
||||
|
||||
module.exports = {
|
||||
authController,
|
||||
authService
|
||||
};
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
const joi = require('joi');
|
||||
|
||||
const loginModel = joi.object().keys({
|
||||
email: joi.string().email({ tlds: { allow: false } }).required().messages({
|
||||
'string.base': 'Email harus berupa teks.',
|
||||
'string.empty': 'Email tidak boleh kosong.',
|
||||
'string.email': 'Format email tidak valid.',
|
||||
'any.required': 'Email wajib diisi.',
|
||||
}),
|
||||
|
||||
password: joi.string().required().messages({
|
||||
'string.base': 'Password harus berupa teks.',
|
||||
'string.empty': 'Password tidak boleh kosong.',
|
||||
'string.min': 'Password minimal {#limit} karakter.',
|
||||
'any.required': 'Password wajib diisi.',
|
||||
}),
|
||||
});
|
||||
|
||||
const registerModel = joi.object().keys({
|
||||
email: joi.string().email({ tlds: { allow: false } }).required().messages({
|
||||
'string.base': 'Email harus berupa teks.',
|
||||
'string.empty': 'Email tidak boleh kosong.',
|
||||
'string.email': 'Format email tidak valid.',
|
||||
'any.required': 'Email wajib diisi.',
|
||||
}),
|
||||
|
||||
password: joi.string()
|
||||
.min(8)
|
||||
.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/)
|
||||
.required()
|
||||
.messages({
|
||||
'string.base': 'Password harus berupa teks.',
|
||||
'string.empty': 'Password tidak boleh kosong.',
|
||||
'string.min': 'Password minimal {#limit} karakter.',
|
||||
'string.pattern.base': 'Password harus mengandung huruf besar, huruf kecil, dan angka.',
|
||||
'any.required': 'Password wajib diisi.',
|
||||
}),
|
||||
});
|
||||
|
||||
const forgotPasswordModel = joi.object().keys({
|
||||
email: joi.string().email({ tlds: { allow: false } }).required().messages({
|
||||
'string.base': 'Email harus berupa teks.',
|
||||
'string.empty': 'Email tidak boleh kosong.',
|
||||
'string.email': 'Format email tidak valid.',
|
||||
'any.required': 'Email wajib diisi.',
|
||||
}),
|
||||
});
|
||||
|
||||
const resetPasswordModel = joi.object().keys({
|
||||
token: joi.string().required().messages({
|
||||
'string.base': 'Token harus berupa teks.',
|
||||
'string.empty': 'Token tidak boleh kosong.',
|
||||
'any.required': 'Token wajib diisi.',
|
||||
}),
|
||||
|
||||
password: joi.string()
|
||||
.min(8)
|
||||
.pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/)
|
||||
.required()
|
||||
.messages({
|
||||
'string.base': 'Password harus berupa teks.',
|
||||
'string.empty': 'Password tidak boleh kosong.',
|
||||
'string.min': 'Password minimal {#limit} karakter.',
|
||||
'string.pattern.base': 'Password harus mengandung huruf besar, huruf kecil, dan angka.',
|
||||
'any.required': 'Password wajib diisi.',
|
||||
}),
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
loginModel,
|
||||
registerModel,
|
||||
forgotPasswordModel,
|
||||
resetPasswordModel,
|
||||
};
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
const bcrypt = require('bcrypt');
|
||||
const adminService = require('../../admin/services/admin.service');
|
||||
const { createToken } = require('../../../middleware/verifyJWT');
|
||||
const { data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { UnauthorizedError, NotFoundError } = require('../../../helpers/error');
|
||||
|
||||
class AuthService {
|
||||
async login(email, password) {
|
||||
try {
|
||||
const result = await adminService.getAdminByEmail(email);
|
||||
if (result.err || !result.data) {
|
||||
return error(new UnauthorizedError('Email atau password tidak valid'));
|
||||
}
|
||||
|
||||
const admin = result.data;
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(password, admin.password);
|
||||
|
||||
if (!isPasswordValid) {
|
||||
return error(new UnauthorizedError('Email atau password tidak valid'));
|
||||
}
|
||||
|
||||
const token = createToken({
|
||||
id: admin.id.toString(),
|
||||
email: admin.email,
|
||||
role: admin.role,
|
||||
signature: admin.signature
|
||||
});
|
||||
|
||||
return data({
|
||||
token,
|
||||
admin: {
|
||||
id: admin.id.toString(),
|
||||
nama_depan: admin.nama_depan,
|
||||
nama_belakang: admin.nama_belakang,
|
||||
email: admin.email,
|
||||
role: admin.role,
|
||||
signature: admin.signature,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getCurrentUser(userId) {
|
||||
try {
|
||||
const result = await adminService.getAdminById(userId);
|
||||
|
||||
if (result.err) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const { password, ...adminWithoutPassword } = result.data;
|
||||
|
||||
return data(adminWithoutPassword);
|
||||
} catch (err) {
|
||||
return error(new NotFoundError('Pengguna tidak ditemukan'));
|
||||
}
|
||||
}
|
||||
|
||||
generateToken(payload) {
|
||||
try {
|
||||
const token = createToken(payload);
|
||||
return data(token);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new AuthService();
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
const batchService = require('../services/batch.service');
|
||||
const { response, error } = require('../../../helpers/utils/wrapper');
|
||||
const { BadRequestError, InternalServerError } = require('../../../helpers/error');
|
||||
const { SUCCESS, ERROR } = require('../../../helpers/http-status/status_code');
|
||||
const { isValidPayload } = require('../../../helpers/utils/validator');
|
||||
const { createBatchModel, updateBatchModel } = require('../models/batch.model');
|
||||
|
||||
class BatchController {
|
||||
async createBatch(req, res) {
|
||||
try {
|
||||
const validatePayload = isValidPayload(req.body, createBatchModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await batchService.createBatch(validatePayload.data);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Batch berhasil dibuat', SUCCESS.CREATED);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllBatches(req, res) {
|
||||
try {
|
||||
const result = await batchService.getAllBatches();
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Berhasil mengambil semua batch', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async updateBatch(req, res) {
|
||||
try {
|
||||
const id = parseInt(req.params.id);
|
||||
|
||||
const validatePayload = isValidPayload(req.body, updateBatchModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await batchService.updateBatch(id, validatePayload.data);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Batch berhasil diperbarui', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteBatch(req, res) {
|
||||
try {
|
||||
const id = parseInt(req.params.id);
|
||||
|
||||
if (isNaN(id)) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
error(new BadRequestError('ID batch harus berupa angka')),
|
||||
'ID batch tidak valid',
|
||||
ERROR.BAD_REQUEST
|
||||
);
|
||||
}
|
||||
|
||||
const result = await batchService.deleteBatch(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Batch berhasil dihapus', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async switchBatch(req, res) {
|
||||
try {
|
||||
const batch_number = parseInt(req.params.batch_number);
|
||||
|
||||
if (isNaN(batch_number)) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
error(new BadRequestError('Nomor batch harus berupa angka')),
|
||||
'Nomor batch tidak valid',
|
||||
ERROR.BAD_REQUEST
|
||||
);
|
||||
}
|
||||
|
||||
const result = await batchService.switchBatch(batch_number);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Batch berhasil diaktifkan', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new BatchController();
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const batchController = require('./controllers/batch.controller');
|
||||
const batchService = require('./services/batch.service');
|
||||
const batchRepository = require('./repositories/batch.repository');
|
||||
|
||||
module.exports = {
|
||||
batchController,
|
||||
batchService,
|
||||
batchRepository,
|
||||
};
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
const joi = require('joi');
|
||||
|
||||
const createBatchModel = joi.object().keys({
|
||||
batch_number: joi.number().integer().positive().messages({
|
||||
'number.base': 'Nomor batch harus berupa angka.',
|
||||
'number.integer': 'Nomor batch harus berupa bilangan bulat.',
|
||||
'number.positive': 'Nomor batch harus berupa angka positif.',
|
||||
}),
|
||||
|
||||
is_active: joi.boolean().default(true).messages({
|
||||
'boolean.base': 'Status aktif harus berupa boolean.',
|
||||
}),
|
||||
});
|
||||
|
||||
const updateBatchModel = joi.object().keys({
|
||||
batch_number: joi.number().integer().positive().messages({
|
||||
'number.base': 'Nomor batch harus berupa angka.',
|
||||
'number.integer': 'Nomor batch harus berupa bilangan bulat.',
|
||||
'number.positive': 'Nomor batch harus berupa angka positif.',
|
||||
}),
|
||||
|
||||
is_active: joi.boolean().messages({
|
||||
'boolean.base': 'Status aktif harus berupa boolean.',
|
||||
}),
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
createBatchModel,
|
||||
updateBatchModel,
|
||||
};
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
const prisma = require('../../../helpers/db/db_connection');
|
||||
|
||||
class BatchRepository {
|
||||
async create(batchData) {
|
||||
return prisma.batch.create({
|
||||
data: batchData,
|
||||
});
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
return prisma.batch.findMany({
|
||||
orderBy: {
|
||||
batch_number: 'desc',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id) {
|
||||
return prisma.batch.findUnique({
|
||||
where: { id: id },
|
||||
});
|
||||
}
|
||||
|
||||
async findByBatchNumber(batch_number) {
|
||||
return prisma.batch.findUnique({
|
||||
where: { batch_number: batch_number },
|
||||
});
|
||||
}
|
||||
|
||||
async findActiveBatch() {
|
||||
return prisma.batch.findFirst({
|
||||
where: { is_active: true },
|
||||
});
|
||||
}
|
||||
|
||||
async findLatestBatch() {
|
||||
return prisma.batch.findFirst({
|
||||
orderBy: {
|
||||
batch_number: 'desc',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async updateById(id, batchData) {
|
||||
return prisma.batch.update({
|
||||
where: { id: id },
|
||||
data: batchData,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteById(id) {
|
||||
return prisma.batch.delete({
|
||||
where: { id: id },
|
||||
});
|
||||
}
|
||||
|
||||
async deactivateAllBatches() {
|
||||
return prisma.batch.updateMany({
|
||||
data: { is_active: false },
|
||||
});
|
||||
}
|
||||
|
||||
async countBatches() {
|
||||
return prisma.batch.count();
|
||||
}
|
||||
|
||||
async findByStatus(is_active) {
|
||||
return prisma.batch.findMany({
|
||||
where: { is_active: is_active },
|
||||
orderBy: {
|
||||
batch_number: 'desc',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getBatchById(batchId) {
|
||||
if (!batchId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.findById(parseInt(batchId));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new BatchRepository();
|
||||
Executable
+119
@@ -0,0 +1,119 @@
|
||||
const batchRepository = require('../repositories/batch.repository');
|
||||
const { data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { NotFoundError, ConflictError } = require('../../../helpers/error');
|
||||
|
||||
class BatchService {
|
||||
async createBatch(batchData) {
|
||||
try {
|
||||
let batchNumber;
|
||||
|
||||
if (batchData.batch_number) {
|
||||
const existingBatch = await batchRepository.findByBatchNumber(batchData.batch_number);
|
||||
if (existingBatch) {
|
||||
return error(new ConflictError('Nomor batch sudah digunakan'));
|
||||
}
|
||||
batchNumber = batchData.batch_number;
|
||||
} else {
|
||||
const latestBatch = await batchRepository.findLatestBatch();
|
||||
batchNumber = latestBatch ? latestBatch.batch_number + 1 : 1;
|
||||
}
|
||||
|
||||
await batchRepository.deactivateAllBatches();
|
||||
|
||||
const newBatchData = {
|
||||
...batchData,
|
||||
batch_number: batchNumber,
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
const result = await batchRepository.create(newBatchData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllBatches() {
|
||||
try {
|
||||
const batchList = await batchRepository.findAll();
|
||||
return data(batchList);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async switchBatch(batch_number) {
|
||||
try {
|
||||
const batch = await batchRepository.findByBatchNumber(batch_number);
|
||||
|
||||
if (!batch) {
|
||||
return error(new NotFoundError('Batch tidak ditemukan'));
|
||||
}
|
||||
|
||||
await batchRepository.deactivateAllBatches();
|
||||
|
||||
const result = await batchRepository.updateById(batch.id, { is_active: true });
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getBatchById(id) {
|
||||
try {
|
||||
const batch = await batchRepository.findById(id);
|
||||
|
||||
if (!batch) {
|
||||
return error(new NotFoundError('Batch tidak ditemukan'));
|
||||
}
|
||||
|
||||
return data(batch);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async updateBatch(id, batchData) {
|
||||
try {
|
||||
const checkResult = await this.getBatchById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
console.log(batchData, id);
|
||||
|
||||
const existingBatch = checkResult.data;
|
||||
|
||||
if (batchData.batch_number && batchData.batch_number !== existingBatch.batch_number) {
|
||||
const duplicateBatch = await batchRepository.findByBatchNumber(batchData.batch_number);
|
||||
if (duplicateBatch) {
|
||||
return error(new ConflictError('Nomor batch sudah digunakan'));
|
||||
}
|
||||
}
|
||||
|
||||
if (batchData.is_active === true) {
|
||||
await batchRepository.deactivateAllBatches();
|
||||
}
|
||||
|
||||
const result = await batchRepository.updateById(id, batchData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteBatch(id) {
|
||||
try {
|
||||
const checkResult = await this.getBatchById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const result = await batchRepository.deleteById(id);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new BatchService();
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
const faqService = require('../services/faq.services');
|
||||
const { createFaqModel, updateFaqModel } = require('../models/faq.models');
|
||||
const { response } = require('../../../helpers/utils/wrapper');
|
||||
const { isValidPayload } = require('../../../helpers/utils/validator');
|
||||
const { InternalServerError } = require('../../../helpers/error');
|
||||
const { SUCCESS, ERROR } = require('../../../helpers/http-status/status_code');
|
||||
|
||||
class FaqController {
|
||||
async addFaq(req, res) {
|
||||
try {
|
||||
const payload = req.body;
|
||||
|
||||
const validatePayload = isValidPayload(payload, createFaqModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
validatePayload,
|
||||
'Validasi gagal',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await faqService.createFaq(validatePayload.data);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(
|
||||
res,
|
||||
'success',
|
||||
result,
|
||||
'FAQ berhasil ditambahkan',
|
||||
SUCCESS.CREATED
|
||||
);
|
||||
} catch (err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: new InternalServerError(err.message) },
|
||||
'Terjadi kesalahan yang tidak terduga',
|
||||
ERROR.INTERNAL_ERROR
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllFaq(req, res) {
|
||||
try {
|
||||
const result = await faqService.getAllFaq();
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(
|
||||
res,
|
||||
'success',
|
||||
result,
|
||||
'Data FAQ berhasil diambil',
|
||||
SUCCESS.OK
|
||||
);
|
||||
} catch (err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: new InternalServerError(err.message) },
|
||||
'Terjadi kesalahan yang tidak terduga',
|
||||
ERROR.INTERNAL_ERROR
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getFaqById(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await faqService.getFaqById(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(
|
||||
res,
|
||||
'success',
|
||||
result,
|
||||
'Data FAQ berhasil diambil',
|
||||
SUCCESS.OK
|
||||
);
|
||||
} catch (err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: new InternalServerError(err.message) },
|
||||
'Terjadi kesalahan yang tidak terduga',
|
||||
ERROR.INTERNAL_ERROR
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async updateFaq(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const payload = req.body;
|
||||
|
||||
const validatePayload = isValidPayload(payload, updateFaqModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
validatePayload,
|
||||
'Validasi gagal',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await faqService.updateFaq(id, validatePayload.data);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(
|
||||
res,
|
||||
'success',
|
||||
result,
|
||||
'FAQ berhasil diperbarui',
|
||||
SUCCESS.OK
|
||||
);
|
||||
} catch (err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: new InternalServerError(err.message) },
|
||||
'Terjadi kesalahan yang tidak terduga',
|
||||
ERROR.INTERNAL_ERROR
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteFaq(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await faqService.deleteFaq(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(
|
||||
res,
|
||||
'success',
|
||||
result,
|
||||
'FAQ berhasil dihapus',
|
||||
SUCCESS.OK
|
||||
);
|
||||
} catch (err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: new InternalServerError(err.message) },
|
||||
'Terjadi kesalahan yang tidak terduga',
|
||||
ERROR.INTERNAL_ERROR
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new FaqController();
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
const faqController = require('./controllers/faq.controllers');
|
||||
|
||||
module.exports = {
|
||||
faqController,
|
||||
};
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
const joi = require('joi');
|
||||
|
||||
const createFaqModel = joi.object({
|
||||
pertanyaan: joi.string().required().messages({
|
||||
'string.base': 'Pertanyaan harus berupa teks.',
|
||||
'any.required': 'Pertanyaan wajib diisi.',
|
||||
}),
|
||||
jawaban: joi.string().required().messages({
|
||||
'string.base': 'Jawaban harus berupa teks.',
|
||||
'any.required': 'Jawaban wajib diisi.',
|
||||
}),
|
||||
});
|
||||
|
||||
const updateFaqModel = joi.object({
|
||||
pertanyaan: joi.string().messages({
|
||||
'string.base': 'Pertanyaan harus berupa teks.',
|
||||
}),
|
||||
jawaban: joi.string().messages({
|
||||
'string.base': 'Jawaban harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
createFaqModel,
|
||||
updateFaqModel,
|
||||
};
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
const prisma = require('../../../helpers/db/db_connection');
|
||||
|
||||
class FaqRepository {
|
||||
async create(data) {
|
||||
return prisma.faq.create({
|
||||
data: data,
|
||||
});
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
return prisma.faq.findMany({
|
||||
orderBy: {
|
||||
created_at: 'desc',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id) {
|
||||
return prisma.faq.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
}
|
||||
|
||||
async updateById(id, data) {
|
||||
return prisma.faq.update({
|
||||
where: { id: parseInt(id) },
|
||||
data: data,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteById(id) {
|
||||
return prisma.faq.delete({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new FaqRepository();
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
const faqRepository = require('../repositories/faq.repositories');
|
||||
const { data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { NotFoundError, BadRequestError } = require('../../../helpers/error');
|
||||
|
||||
class FaqService {
|
||||
async createFaq(faqData) {
|
||||
try {
|
||||
const result = await faqRepository.create(faqData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllFaq() {
|
||||
try {
|
||||
const results = await faqRepository.findAll();
|
||||
return data(results);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getFaqById(id) {
|
||||
try {
|
||||
const result = await faqRepository.findById(id);
|
||||
|
||||
if (!result) {
|
||||
return error(new NotFoundError('FAQ Tidak Ditemukan'));
|
||||
}
|
||||
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async updateFaq(id, faqData) {
|
||||
try {
|
||||
const checkResult = await this.getFaqById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const result = await faqRepository.updateById(id, faqData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteFaq(id) {
|
||||
try {
|
||||
const checkResult = await this.getFaqById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const result = await faqRepository.deleteById(id);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new FaqService();
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
const feedbackService = require('../services/feedback.service');
|
||||
const { response, error } = require('../../../helpers/utils/wrapper');
|
||||
const { BadRequestError, InternalServerError } = require('../../../helpers/error');
|
||||
const { SUCCESS, ERROR } = require('../../../helpers/http-status/status_code');
|
||||
const { isValidPayload } = require('../../../helpers/utils/validator');
|
||||
const { createFeedbackModel, updateFeedbackModel, getAllFeedbackModel } = require('../models/feedback.model');
|
||||
const { deleteFileIfExists } = require('../../../helpers/utils/fileHelper');
|
||||
|
||||
class FeedbackController {
|
||||
async addFeedback(req, res) {
|
||||
try {
|
||||
const image_path = req.file;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, createFeedbackModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
if (image_path?.filename) {
|
||||
await deleteFileIfExists(image_path.filename);
|
||||
}
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await feedbackService.createFeedback(validatePayload.data, image_path);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Feedback berhasil dibuat', SUCCESS.CREATED);
|
||||
} catch (err) {
|
||||
if (req.file?.filename) {
|
||||
await deleteFileIfExists(req.file.filename);
|
||||
}
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllFeedback(req, res) {
|
||||
try {
|
||||
const validatePayload = isValidPayload(req.query, getAllFeedbackModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Query parameter tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await feedbackService.getAllFeedback(validatePayload.data);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Berhasil mengambil semua feedback', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getFeedbackById(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await feedbackService.getFeedbackById(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Berhasil mengambil feedback berdasarkan ID', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async updateFeedback(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const image_path = req.file;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, updateFeedbackModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
if (image_path?.filename) {
|
||||
await deleteFileIfExists(image_path.filename);
|
||||
}
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await feedbackService.updateFeedback(id, validatePayload.data, image_path);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Feedback berhasil diperbarui', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
if (req.file?.filename) {
|
||||
await deleteFileIfExists(req.file.filename);
|
||||
}
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteFeedback(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await feedbackService.deleteFeedback(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Feedback berhasil dihapus', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new FeedbackController();
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
const feedbackController = require('./controllers/feedback.controller');
|
||||
|
||||
module.exports = {
|
||||
feedbackController,
|
||||
};
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
const joi = require('joi');
|
||||
|
||||
const createFeedbackModel = joi.object().keys({
|
||||
nama: joi.string().max(255).required().messages({
|
||||
'string.base': 'Nama harus berupa teks.',
|
||||
'string.empty': 'Nama tidak boleh kosong.',
|
||||
'string.max': 'Nama maksimal {#limit} karakter.',
|
||||
'any.required': 'Nama wajib diisi.',
|
||||
}),
|
||||
|
||||
universitas: joi.string().max(255).required().messages({
|
||||
'string.base': 'Universitas harus berupa teks.',
|
||||
'string.empty': 'Universitas tidak boleh kosong.',
|
||||
'string.max': 'Universitas maksimal {#limit} karakter.',
|
||||
'any.required': 'Universitas wajib diisi.',
|
||||
}),
|
||||
|
||||
pesan: joi.string().required().messages({
|
||||
'string.base': 'Pesan harus berupa teks.',
|
||||
'string.empty': 'Pesan tidak boleh kosong.',
|
||||
'any.required': 'Pesan wajib diisi.',
|
||||
}),
|
||||
|
||||
batch: joi.number().integer().min(1).required().messages({
|
||||
'number.base': 'Batch harus berupa angka.',
|
||||
'number.integer': 'Batch harus berupa bilangan bulat.',
|
||||
'number.min': 'Batch minimal {#limit}.',
|
||||
'any.required': 'Batch wajib diisi.',
|
||||
}),
|
||||
|
||||
posisi: joi.string().max(255).required().messages({
|
||||
'string.base': 'Posisi harus berupa teks.',
|
||||
'string.empty': 'Posisi tidak boleh kosong.',
|
||||
'string.max': 'Posisi maksimal {#limit} karakter.',
|
||||
'any.required': 'Posisi wajib diisi.',
|
||||
}),
|
||||
|
||||
tahun: joi.number().integer().min(2000).max(2100).required().messages({
|
||||
'number.base': 'Tahun harus berupa angka.',
|
||||
'number.integer': 'Tahun harus berupa bilangan bulat.',
|
||||
'number.min': 'Tahun minimal {#limit}.',
|
||||
'number.max': 'Tahun maksimal {#limit}.',
|
||||
'any.required': 'Tahun wajib diisi.',
|
||||
}),
|
||||
|
||||
image_path: joi.string().optional().allow('', null).messages({
|
||||
'string.base': 'Path gambar harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
const updateFeedbackModel = joi.object().keys({
|
||||
nama: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Nama harus berupa teks.',
|
||||
'string.max': 'Nama maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
universitas: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Universitas harus berupa teks.',
|
||||
'string.max': 'Universitas maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
pesan: joi.string().optional().messages({
|
||||
'string.base': 'Pesan harus berupa teks.',
|
||||
}),
|
||||
|
||||
batch: joi.number().integer().min(1).optional().messages({
|
||||
'number.base': 'Batch harus berupa angka.',
|
||||
'number.integer': 'Batch harus berupa bilangan bulat.',
|
||||
'number.min': 'Batch minimal {#limit}.',
|
||||
}),
|
||||
|
||||
posisi: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Posisi harus berupa teks.',
|
||||
'string.max': 'Posisi maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
tahun: joi.number().integer().min(2000).max(2100).optional().messages({
|
||||
'number.base': 'Tahun harus berupa angka.',
|
||||
'number.integer': 'Tahun harus berupa bilangan bulat.',
|
||||
'number.min': 'Tahun minimal {#limit}.',
|
||||
'number.max': 'Tahun maksimal {#limit}.',
|
||||
}),
|
||||
|
||||
image_path: joi.string().optional().allow('', null).messages({
|
||||
'string.base': 'Path gambar harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
const getAllFeedbackModel = joi.object().keys({
|
||||
batch: joi.number().integer().min(1).optional().messages({
|
||||
'number.base': 'Batch harus berupa angka.',
|
||||
'number.integer': 'Batch harus berupa bilangan bulat.',
|
||||
'number.min': 'Batch minimal {#limit}.',
|
||||
}),
|
||||
|
||||
tahun: joi.number().integer().min(2000).max(2100).optional().messages({
|
||||
'number.base': 'Tahun harus berupa angka.',
|
||||
'number.integer': 'Tahun harus berupa bilangan bulat.',
|
||||
'number.min': 'Tahun minimal {#limit}.',
|
||||
'number.max': 'Tahun maksimal {#limit}.',
|
||||
}),
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
createFeedbackModel,
|
||||
updateFeedbackModel,
|
||||
getAllFeedbackModel,
|
||||
};
|
||||
@@ -0,0 +1,60 @@
|
||||
const prisma = require('../../../helpers/db/db_connection');
|
||||
|
||||
class FeedbackRepository {
|
||||
async create(feedbackData) {
|
||||
return prisma.feedback.create({
|
||||
data: {
|
||||
...feedbackData,
|
||||
created_at: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
return prisma.feedback.findMany({
|
||||
orderBy: {
|
||||
created_at: 'desc',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findAllWithFilters({ batch, tahun }) {
|
||||
const where = {};
|
||||
|
||||
if (batch) {
|
||||
where.batch = parseInt(batch);
|
||||
}
|
||||
|
||||
if (tahun) {
|
||||
where.tahun = parseInt(tahun);
|
||||
}
|
||||
|
||||
return prisma.feedback.findMany({
|
||||
where,
|
||||
orderBy: {
|
||||
created_at: 'desc',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id) {
|
||||
return prisma.feedback.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
}
|
||||
|
||||
async updateById(id, feedbackData) {
|
||||
return prisma.feedback.update({
|
||||
where: { id: parseInt(id) },
|
||||
data: feedbackData,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteById(id) {
|
||||
return prisma.feedback.delete({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new FeedbackRepository();
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
const path = require('path');
|
||||
const feedbackRepository = require('../repositories/feedback.repository');
|
||||
const imageUploadHelper = require('../../../helpers/utils/imageUpload.helper');
|
||||
const { deleteFileIfExists } = require('../../../helpers/utils/fileHelper');
|
||||
const { data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { NotFoundError } = require('../../../helpers/error');
|
||||
|
||||
class FeedbackService {
|
||||
async createFeedback(feedbackData, imageFile) {
|
||||
try {
|
||||
const imagePath = imageUploadHelper.uploadImage(imageFile);
|
||||
|
||||
const newFeedbackData = {
|
||||
...feedbackData,
|
||||
image_path: imagePath,
|
||||
};
|
||||
|
||||
const result = await feedbackRepository.create(newFeedbackData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
if (imageFile?.filename) {
|
||||
try {
|
||||
await deleteFileIfExists(imageFile.filename);
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup file:', cleanupErr);
|
||||
}
|
||||
}
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllFeedback(query = {}) {
|
||||
try {
|
||||
const feedbackList = await feedbackRepository.findAllWithFilters(query);
|
||||
|
||||
if (feedbackList.length === 0) {
|
||||
return data([]);
|
||||
}
|
||||
|
||||
return data(feedbackList);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getFeedbackById(id) {
|
||||
try {
|
||||
const feedback = await feedbackRepository.findById(id);
|
||||
|
||||
if (!feedback) {
|
||||
return error(new NotFoundError('Feedback tidak ditemukan'));
|
||||
}
|
||||
|
||||
return data(feedback);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async updateFeedback(id, feedbackData, imageFile) {
|
||||
let oldImagePath = null;
|
||||
let newImageUploaded = false;
|
||||
|
||||
try {
|
||||
const checkResult = await this.getFeedbackById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const existingFeedback = checkResult.data;
|
||||
|
||||
if (imageFile) {
|
||||
oldImagePath = existingFeedback.image_path;
|
||||
|
||||
feedbackData.image_path = imageUploadHelper.uploadImage(imageFile);
|
||||
newImageUploaded = true;
|
||||
|
||||
if (oldImagePath) {
|
||||
const oldFileName = path.basename(oldImagePath);
|
||||
await deleteFileIfExists(oldFileName);
|
||||
}
|
||||
}
|
||||
|
||||
const result = await feedbackRepository.updateById(id, feedbackData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
if (newImageUploaded && imageFile?.filename) {
|
||||
try {
|
||||
await deleteFileIfExists(imageFile.filename);
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup new file:', cleanupErr);
|
||||
}
|
||||
}
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteFeedback(id) {
|
||||
try {
|
||||
const checkResult = await this.getFeedbackById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const feedback = checkResult.data;
|
||||
|
||||
if (feedback.image_path) {
|
||||
const fileName = path.basename(feedback.image_path);
|
||||
await deleteFileIfExists(fileName);
|
||||
}
|
||||
|
||||
const result = await feedbackRepository.deleteById(id);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new FeedbackService();
|
||||
@@ -0,0 +1,126 @@
|
||||
const hasilResearchService = require('../services/hasilResearch.service');
|
||||
const { response, error } = require('../../../helpers/utils/wrapper');
|
||||
const { BadRequestError, InternalServerError } = require('../../../helpers/error');
|
||||
const { SUCCESS, ERROR } = require('../../../helpers/http-status/status_code');
|
||||
const { isValidPayload } = require('../../../helpers/utils/validator');
|
||||
const { createHasilResearchModel, updateHasilResearchModel } = require('../models/hasilResearch.model');
|
||||
const { deleteFileIfExists } = require('../../../helpers/utils/fileHelper');
|
||||
|
||||
class HasilResearchController {
|
||||
async addHasilResearch(req, res) {
|
||||
try {
|
||||
const image = req.file;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, createHasilResearchModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
if (image?.filename) {
|
||||
await deleteFileIfExists(image.filename);
|
||||
}
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await hasilResearchService.createHasilResearch(validatePayload.data, image);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Data hasil research berhasil ditambahkan', SUCCESS.CREATED);
|
||||
} catch (err) {
|
||||
if (req.file?.filename) {
|
||||
await deleteFileIfExists(req.file.filename);
|
||||
}
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getHasilResearch(req, res) {
|
||||
try {
|
||||
const result = await hasilResearchService.getAllHasilResearch();
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Data research berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getHasilResearchById(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await hasilResearchService.getHasilResearchById(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Data research berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async updateHasilResearch(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const image = req.file;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, updateHasilResearchModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
if (image?.filename) {
|
||||
await deleteFileIfExists(image.filename);
|
||||
}
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await hasilResearchService.updateHasilResearch(id, validatePayload.data, image);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Data hasil research berhasil diperbarui', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
if (req.file?.filename) {
|
||||
await deleteFileIfExists(req.file.filename);
|
||||
}
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteHasilResearch(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await hasilResearchService.deleteHasilResearch(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Data hasil research berhasil dihapus', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new HasilResearchController();
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const hasilResearchController = require('./controllers/hasilResearch.controller');
|
||||
const hasilResearchService = require('./services/hasilResearch.service');
|
||||
const hasilResearchRepository = require('./repositories/hasilResearch.repository');
|
||||
|
||||
module.exports = {
|
||||
hasilResearchController,
|
||||
hasilResearchService,
|
||||
hasilResearchRepository
|
||||
};
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
joi = require('joi');
|
||||
|
||||
const urlRegex = /^(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
|
||||
|
||||
const createHasilResearchModel = joi.object().keys({
|
||||
nama_project: joi.string().max(255).required().messages({
|
||||
'string.base': 'Nama project harus berupa teks.',
|
||||
'string.empty': 'Nama project tidak boleh kosong.',
|
||||
'string.max': 'Nama project maksimal {#limit} karakter.',
|
||||
'any.required': 'Nama project wajib diisi.',
|
||||
}),
|
||||
|
||||
deskripsi: joi.string().required().messages({
|
||||
'string.base': 'Deskripsi harus berupa teks.',
|
||||
'string.empty': 'Deskripsi tidak boleh kosong.',
|
||||
'any.required': 'Deskripsi wajib diisi.',
|
||||
}),
|
||||
|
||||
link_project: joi.string().pattern(urlRegex).optional().allow('', null).messages({
|
||||
'string.base': 'Link project harus berupa teks.',
|
||||
'string.pattern.base': 'Format URL tidak valid.',
|
||||
}),
|
||||
|
||||
image_path: joi.string().optional().allow('', null).messages({
|
||||
'string.base': 'Path gambar harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
const updateHasilResearchModel = joi.object().keys({
|
||||
nama_project: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Nama project harus berupa teks.',
|
||||
'string.max': 'Nama project maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
deskripsi: joi.string().optional().messages({
|
||||
'string.base': 'Deskripsi harus berupa teks.',
|
||||
}),
|
||||
|
||||
link_project: joi.string().pattern(urlRegex).optional().allow('', null).messages({
|
||||
'string.base': 'Link project harus berupa teks.',
|
||||
'string.pattern.base': 'Format URL tidak valid.',
|
||||
}),
|
||||
|
||||
image_path: joi.string().optional().allow('', null).messages({
|
||||
'string.base': 'Path gambar harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
createHasilResearchModel,
|
||||
updateHasilResearchModel,
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
const prisma = require('../../../helpers/db/db_connection');
|
||||
|
||||
class HasilResearchRepository {
|
||||
async create(researchData) {
|
||||
return prisma.hasilResearch.create({
|
||||
data: researchData,
|
||||
});
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
return prisma.hasilResearch.findMany();
|
||||
}
|
||||
|
||||
async findById(id) {
|
||||
return prisma.hasilResearch.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
}
|
||||
|
||||
async updateById(id, researchData) {
|
||||
return prisma.hasilResearch.update({
|
||||
where: { id: parseInt(id) },
|
||||
data: researchData,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteById(id) {
|
||||
return prisma.hasilResearch.delete({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new HasilResearchRepository();
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
const hasilResearchRepository = require('../repositories/hasilResearch.repository');
|
||||
const path = require('path');
|
||||
const { deleteFileIfExists } = require('../../../helpers/utils/fileHelper');
|
||||
const imageUploadHelper = require('../../../helpers/utils/imageUpload.helper');
|
||||
const { data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { NotFoundError } = require('../../../helpers/error');
|
||||
|
||||
class HasilResearchService {
|
||||
async createHasilResearch(researchData, imageFile) {
|
||||
try {
|
||||
const imagePath = imageUploadHelper.uploadImage(imageFile);
|
||||
|
||||
const newResearchData = {
|
||||
...researchData,
|
||||
image_path: imagePath,
|
||||
};
|
||||
|
||||
const result = await hasilResearchRepository.create(newResearchData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
if (imageFile?.filename) {
|
||||
try {
|
||||
await deleteFileIfExists(imageFile.filename);
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup file:', cleanupErr);
|
||||
}
|
||||
}
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllHasilResearch() {
|
||||
try {
|
||||
const researchList = await hasilResearchRepository.findAll();
|
||||
return data(researchList);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getHasilResearchById(id) {
|
||||
try {
|
||||
const research = await hasilResearchRepository.findById(id);
|
||||
|
||||
if (!research) {
|
||||
return error(new NotFoundError('Hasil Research Tidak Ditemukan'));
|
||||
}
|
||||
|
||||
return data(research);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async updateHasilResearch(id, researchData, imageFile) {
|
||||
let oldImagePath = null;
|
||||
let newImageUploaded = false;
|
||||
|
||||
try {
|
||||
const checkResult = await this.getHasilResearchById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const existingResearch = checkResult.data;
|
||||
let imagePath = existingResearch.image_path;
|
||||
|
||||
if (imageFile) {
|
||||
oldImagePath = existingResearch.image_path;
|
||||
|
||||
imagePath = imageUploadHelper.uploadImage(imageFile);
|
||||
newImageUploaded = true;
|
||||
|
||||
if (oldImagePath) {
|
||||
const oldFileName = path.basename(oldImagePath);
|
||||
await deleteFileIfExists(oldFileName);
|
||||
}
|
||||
}
|
||||
|
||||
const updatedResearchData = {
|
||||
...researchData,
|
||||
image_path: imagePath,
|
||||
};
|
||||
|
||||
const result = await hasilResearchRepository.updateById(id, updatedResearchData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
if (newImageUploaded && imageFile?.filename) {
|
||||
try {
|
||||
await deleteFileIfExists(imageFile.filename);
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup new file:', cleanupErr);
|
||||
}
|
||||
}
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteHasilResearch(id) {
|
||||
try {
|
||||
const checkResult = await this.getHasilResearchById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const research = checkResult.data;
|
||||
|
||||
if (research.image_path) {
|
||||
const fileName = path.basename(research.image_path);
|
||||
await deleteFileIfExists(fileName);
|
||||
}
|
||||
|
||||
const result = await hasilResearchRepository.deleteById(id);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new HasilResearchService();
|
||||
@@ -0,0 +1,312 @@
|
||||
const lamaranMagangService = require('../services/lamaranMagang.service');
|
||||
const { response, error, paginationResponse } = require('../../../helpers/utils/wrapper');
|
||||
const { InternalServerError } = require('../../../helpers/error');
|
||||
const { SUCCESS, ERROR } = require('../../../helpers/http-status/status_code');
|
||||
const { isValidPayload } = require('../../../helpers/utils/validator');
|
||||
const { createLamaranMagangModel, updateLamaranStatusModel, getAllLamaranMagangModel, statisticModel } = require('../models/lamaranMagang.model');
|
||||
const { cleanupUploadedFiles } = require('../helpers/cleanUpFiles');
|
||||
|
||||
|
||||
class LamaranMagangController {
|
||||
async addLamaranMagang(req, res) {
|
||||
try {
|
||||
const { id_lowongan_magang } = req.params;
|
||||
const uploadedFiles = {
|
||||
cv: req.files?.cv?.[0],
|
||||
portofolio: req.files?.portofolio?.[0],
|
||||
};
|
||||
|
||||
const payloadWithFiles = {
|
||||
...req.body,
|
||||
cv: uploadedFiles.cv?.filename,
|
||||
portofolio: uploadedFiles.portofolio?.filename,
|
||||
id_lowongan_magang,
|
||||
};
|
||||
|
||||
const validatePayload = isValidPayload(payloadWithFiles, createLamaranMagangModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
await cleanupUploadedFiles(uploadedFiles);
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const { id_lowongan_magang: validatedLowonganId, cv, portofolio, ...mahasiswaFormData } = validatePayload.data;
|
||||
|
||||
const result = await lamaranMagangService.createLamaranMagang(
|
||||
validatedLowonganId,
|
||||
mahasiswaFormData,
|
||||
uploadedFiles
|
||||
);
|
||||
|
||||
if (result.err) {
|
||||
await cleanupUploadedFiles(uploadedFiles);
|
||||
return response(res, 'fail', result, 'Gagal mengajukan lamaran magang', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Lamaran magang berhasil diajukan', SUCCESS.CREATED);
|
||||
} catch (err) {
|
||||
|
||||
await cleanupUploadedFiles({
|
||||
cv: req.files?.cv?.[0],
|
||||
portofolio: req.files?.portofolio?.[0],
|
||||
});
|
||||
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
error(new InternalServerError(err.message)),
|
||||
'Terjadi kesalahan yang tidak terduga',
|
||||
ERROR.INTERNAL_ERROR
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllLamaranMagang(req, res) {
|
||||
try {
|
||||
const validatePayload = isValidPayload(req.query, getAllLamaranMagangModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const query = validatePayload.data;
|
||||
|
||||
const result = await lamaranMagangService.getAllLamaranMagang(query);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return paginationResponse(res, 'success', result, 'Lamaran magang berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getLamaranByID(req, res) {
|
||||
try {
|
||||
const { id_lamaran_magang } = req.params;
|
||||
|
||||
const result = await lamaranMagangService.getLamaranById(id_lamaran_magang);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Lamaran magang berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getDetailLamaranById(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await lamaranMagangService.getDetailLamaranById(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Detail lamaran magang berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async updateStatusLamaran(req, res) {
|
||||
try {
|
||||
const { id_lamaran_magang } = req.params;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, updateLamaranStatusModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const { status } = validatePayload.data;
|
||||
const result = await lamaranMagangService.updateLamaranStatus(id_lamaran_magang, status);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Status lamaran berhasil diperbarui', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteLamaran(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await lamaranMagangService.deleteLamaran(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Lamaran magang berhasil dihapus', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async exportLamaranToExcel(req, res) {
|
||||
try {
|
||||
const result = await lamaranMagangService.exportToExcel();
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
const workbook = result.data;
|
||||
|
||||
res.setHeader(
|
||||
'Content-Type',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
);
|
||||
res.setHeader(
|
||||
'Content-Disposition',
|
||||
'attachment; filename=lamaran_magang.xlsx'
|
||||
);
|
||||
|
||||
await workbook.xlsx.write(res);
|
||||
res.end();
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getDashboardStatistics(req, res) {
|
||||
try {
|
||||
const validateQuery = isValidPayload(req.query, statisticModel);
|
||||
|
||||
if (validateQuery.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validateQuery.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const query = validateQuery.data
|
||||
const result = await lamaranMagangService.getDashboardStatistics(query);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result, 'Gagal mengambil statistik dashboard', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Statistik dashboard berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getStatisticsByPosition(req, res) {
|
||||
try {
|
||||
|
||||
const validateQuery = isValidPayload(req.query, statisticModel);
|
||||
|
||||
if (validateQuery.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validateQuery.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const query = validateQuery.data;
|
||||
const result = await lamaranMagangService.getStatisticsByPosition(query);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result, 'Gagal mengambil statistik berdasarkan posisi', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Statistik berdasarkan posisi berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getStatisticsByCountry(req, res) {
|
||||
try {
|
||||
const validateQuery = isValidPayload(req.query, statisticModel);
|
||||
|
||||
if (validateQuery.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validateQuery.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const query = validateQuery.data;
|
||||
const result = await lamaranMagangService.getStatisticsByCountry(query);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result, 'Gagal mengambil statistik berdasarkan negara', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Statistik berdasarkan negara berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getStatisticsByUniversity(req, res) {
|
||||
try {
|
||||
const validateQuery = isValidPayload(req.query, statisticModel);
|
||||
|
||||
if (validateQuery.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validateQuery.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
const query = validateQuery.data;
|
||||
const result = await lamaranMagangService.getStatisticsByUniversity(query);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result, 'Gagal mengambil statistik berdasarkan universitas', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Statistik berdasarkan universitas berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
module.exports = new LamaranMagangController();
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
const { deleteFileIfExists } = require('../../../helpers/utils/fileHelper');
|
||||
|
||||
const cleanupUploadedFiles = async (files) => {
|
||||
if (files?.cv?.filename) {
|
||||
await deleteFileIfExists(files.cv.filename);
|
||||
}
|
||||
if (files?.portofolio?.filename) {
|
||||
await deleteFileIfExists(files.portofolio.filename);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
cleanupUploadedFiles,
|
||||
};
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
const transporter = require('../../../helpers/utils/mail');
|
||||
|
||||
const sendConfirmationEmail = async (mahasiswa, lowongan) => {
|
||||
try {
|
||||
const { nama_depan, nama_belakang, email } = mahasiswa;
|
||||
const { posisi } = lowongan;
|
||||
const fullName = `${nama_depan}${nama_belakang ? ' ' + nama_belakang : ''}`;
|
||||
|
||||
const mailOptions = {
|
||||
from: process.env.MAIL_USER,
|
||||
to: email,
|
||||
subject: 'Konfirmasi Penerimaan Lamaran Anda',
|
||||
headers: {
|
||||
'X-Priority': '1',
|
||||
'X-MSMail-Priority': 'High',
|
||||
Importance: 'high',
|
||||
},
|
||||
html: `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 10px;">
|
||||
<h2 style="color: #333;">Lamaran Anda Telah Kami Terima</h2>
|
||||
<p>Halo ${fullName},</p>
|
||||
|
||||
<p>Terima kasih telah mengirimkan lamaran untuk posisi <strong>${posisi}</strong> di <strong>Humic Engineering</strong>.</p>
|
||||
|
||||
<p>Kami telah menerima dokumen dan informasi yang Anda kirimkan, dan saat ini tim rekrutmen kami sedang meninjaunya dengan seksama.</p>
|
||||
|
||||
<p>Jika profil Anda sesuai dengan kebutuhan kami, tim kami akan menghubungi Anda untuk tahapan seleksi berikutnya. Proses ini dapat memakan waktu hingga beberapa minggu.</p>
|
||||
|
||||
<p>Kami sangat menghargai minat Anda untuk bergabung bersama tim kami.</p>
|
||||
|
||||
<p>Salam hangat,</p>
|
||||
<p><strong>Tim Rekrutmen Humic Engineering</strong></p>
|
||||
|
||||
<hr style="margin: 30px 0;">
|
||||
<p style="font-size: 12px; color: #888;">Email ini dikirim secara otomatis. Jika Anda memiliki pertanyaan lebih lanjut, silakan hubungi kami melalui email resmi yang tersedia di website kami.</p>
|
||||
</div>
|
||||
`,
|
||||
};
|
||||
|
||||
await transporter.sendMail(mailOptions);
|
||||
} catch (error) {
|
||||
console.error('Error sending confirmation email:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const sendStatusEmail = async (lamaran, status) => {
|
||||
try {
|
||||
const { mahasiswa, lowongan_magang } = lamaran;
|
||||
const { nama_depan, nama_belakang, email } = mahasiswa;
|
||||
const { posisi } = lowongan_magang;
|
||||
|
||||
const isAccepted = status === 'diterima';
|
||||
const fullName = `${nama_depan}${nama_belakang ? ' ' + nama_belakang : ''}`;
|
||||
|
||||
const subject = isAccepted
|
||||
? 'Selamat! Lamaran Anda Diterima'
|
||||
: 'Pemberitahuan Status Lamaran Anda';
|
||||
|
||||
const message = isAccepted
|
||||
? `
|
||||
<p>Halo ${fullName},</p>
|
||||
<p>Selamat! Lamaran Anda untuk posisi <strong>${posisi}</strong> di <strong>Humic Engineering</strong> telah diterima.</p>
|
||||
<p>Tim kami sangat terkesan dengan profil dan kualifikasi Anda. Kami akan segera menghubungi Anda terkait tahapan selanjutnya.</p>
|
||||
<p>Terima kasih telah melamar dan kami menantikan kerja sama yang luar biasa bersama Anda.</p>
|
||||
`
|
||||
: `
|
||||
<p>Halo ${fullName},</p>
|
||||
<p>Terima kasih atas lamaran Anda untuk posisi <strong>${posisi}</strong> di <strong>Humic Engineering</strong>.</p>
|
||||
<p>Setelah mempertimbangkan secara seksama, kami memutuskan untuk tidak melanjutkan proses lamaran Anda ke tahap berikutnya.</p>
|
||||
<p>Jangan berkecil hati—kami sangat menghargai waktu dan usaha Anda. Kami mendorong Anda untuk terus mencoba dan semoga sukses dalam perjalanan karier Anda.</p>
|
||||
`;
|
||||
|
||||
const mailOptions = {
|
||||
from: process.env.MAIL_USER,
|
||||
to: email,
|
||||
subject,
|
||||
headers: {
|
||||
'X-Priority': '1',
|
||||
'X-MSMail-Priority': 'High',
|
||||
Importance: 'high',
|
||||
},
|
||||
html: `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: auto; padding: 20px; border: 1px solid #e0e0e0; border-radius: 10px;">
|
||||
${message}
|
||||
<p>Salam hangat,</p>
|
||||
<p><strong>Tim Rekrutmen Humic Engineering</strong></p>
|
||||
<hr style="margin: 30px 0;">
|
||||
<p style="font-size: 12px; color: #888;">Email ini dikirim secara otomatis. Untuk informasi lebih lanjut, silakan hubungi kami melalui kontak resmi.</p>
|
||||
</div>
|
||||
`,
|
||||
};
|
||||
|
||||
await transporter.sendMail(mailOptions);
|
||||
} catch (error) {
|
||||
console.error('Gagal mengirim email status lamaran:', error);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
sendConfirmationEmail,
|
||||
sendStatusEmail,
|
||||
};
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
const lamaranMagangController = require('./controllers/lamaranMagang.controller');
|
||||
|
||||
module.exports = {
|
||||
lamaranMagangController,
|
||||
};
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
const joi = require('joi');
|
||||
|
||||
const phoneRegex = /^(\+62|62|0)8[1-9][0-9]{6,11}$/;
|
||||
|
||||
const createLamaranMagangModel = joi.object().keys({
|
||||
id_lowongan_magang: joi.string().uuid().required().messages({
|
||||
'string.base': 'ID lowongan magang harus berupa teks.',
|
||||
'string.empty': 'ID lowongan magang tidak boleh kosong.',
|
||||
'string.guid': 'Format ID lowongan magang tidak valid.',
|
||||
'any.required': 'ID lowongan magang wajib diisi.',
|
||||
}),
|
||||
|
||||
nama_depan: joi.string().max(255).required().messages({
|
||||
'string.base': 'Nama depan harus berupa teks.',
|
||||
'string.empty': 'Nama depan tidak boleh kosong.',
|
||||
'string.max': 'Nama depan maksimal {#limit} karakter.',
|
||||
'any.required': 'Nama depan wajib diisi.',
|
||||
}),
|
||||
|
||||
nama_belakang: joi.string().max(255).optional().allow('', null).messages({
|
||||
'string.base': 'Nama belakang harus berupa teks.',
|
||||
'string.max': 'Nama belakang maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
email: joi.string().email({ tlds: { allow: false } }).max(255).required().messages({
|
||||
'string.base': 'Email harus berupa teks.',
|
||||
'string.empty': 'Email tidak boleh kosong.',
|
||||
'string.email': 'Format email tidak valid.',
|
||||
'string.max': 'Email maksimal {#limit} karakter.',
|
||||
'any.required': 'Email wajib diisi.',
|
||||
}),
|
||||
|
||||
kontak: joi.string().pattern(phoneRegex).max(255).required().messages({
|
||||
'string.base': 'Kontak harus berupa teks.',
|
||||
'string.empty': 'Kontak tidak boleh kosong.',
|
||||
'string.pattern.base': 'Format nomor kontak tidak valid. Gunakan format Indonesia (08xx atau +628xx).',
|
||||
'string.max': 'Kontak maksimal {#limit} karakter.',
|
||||
'any.required': 'Kontak wajib diisi.',
|
||||
}),
|
||||
|
||||
jurusan: joi.string().max(255).required().messages({
|
||||
'string.base': 'Jurusan harus berupa teks.',
|
||||
'string.empty': 'Jurusan tidak boleh kosong.',
|
||||
'string.max': 'Jurusan maksimal {#limit} karakter.',
|
||||
'any.required': 'Jurusan wajib diisi.',
|
||||
}),
|
||||
|
||||
universitas: joi.string().max(255).required().messages({
|
||||
'string.base': 'Universitas harus berupa teks.',
|
||||
'string.empty': 'Universitas tidak boleh kosong.',
|
||||
'string.max': 'Universitas maksimal {#limit} karakter.',
|
||||
'any.required': 'Universitas wajib diisi.',
|
||||
}),
|
||||
|
||||
negara: joi.string().max(255).required().messages({
|
||||
'string.base': 'Negara harus berupa teks.',
|
||||
'string.empty': 'Negara tidak boleh kosong.',
|
||||
'string.max': 'Negara maksimal {#limit} karakter.',
|
||||
'any.required': 'Negara wajib diisi.',
|
||||
}),
|
||||
|
||||
motivasi: joi.string().required().messages({
|
||||
'string.base': 'Motivasi harus berupa teks.',
|
||||
'string.empty': 'Motivasi tidak boleh kosong.',
|
||||
'any.required': 'Motivasi wajib diisi.',
|
||||
}),
|
||||
|
||||
relevant_skills: joi.string().max(255).required().messages({
|
||||
'string.base': 'Keahlian yang relevan harus berupa teks.',
|
||||
'string.empty': 'Keahlian yang relevan tidak boleh kosong.',
|
||||
'string.max': 'Keahlian yang relevan maksimal {#limit} karakter.',
|
||||
'any.required': 'Keahlian yang relevan wajib diisi.',
|
||||
}),
|
||||
|
||||
cv: joi.string().required().messages({
|
||||
'string.base': 'Path CV harus berupa teks.',
|
||||
'string.empty': 'Path CV tidak boleh kosong.',
|
||||
'any.required': 'CV wajib diupload.',
|
||||
}),
|
||||
|
||||
portofolio: joi.string().required().messages({
|
||||
'string.base': 'Path portofolio harus berupa teks.',
|
||||
'string.empty': 'Path portofolio tidak boleh kosong.',
|
||||
'any.required': 'Portofolio wajib diupload.',
|
||||
}),
|
||||
|
||||
status: joi.string().valid('diterima', 'diproses', 'ditolak').default('pending').messages({
|
||||
'string.base': 'Status harus berupa teks.',
|
||||
'any.only': 'Status hanya boleh "diterima", "diproses", atau "ditolak".',
|
||||
}),
|
||||
});
|
||||
|
||||
const updateLamaranStatusModel = joi.object().keys({
|
||||
status: joi.string().valid('diterima', 'diproses', 'ditolak').required().messages({
|
||||
'string.base': 'Status harus berupa teks.',
|
||||
'string.empty': 'Status tidak boleh kosong.',
|
||||
'any.only': 'Status hanya boleh "diterima", "diproses", atau "ditolak".',
|
||||
'any.required': 'Status wajib diisi.',
|
||||
}),
|
||||
});
|
||||
|
||||
const updateLamaranMagangModel = joi.object().keys({
|
||||
id_lowongan_magang: joi.string().uuid().optional().messages({
|
||||
'string.base': 'ID lowongan magang harus berupa teks.',
|
||||
'string.guid': 'Format ID lowongan magang tidak valid.',
|
||||
}),
|
||||
|
||||
nama_depan: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Nama depan harus berupa teks.',
|
||||
'string.max': 'Nama depan maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
nama_belakang: joi.string().max(255).optional().allow('', null).messages({
|
||||
'string.base': 'Nama belakang harus berupa teks.',
|
||||
'string.max': 'Nama belakang maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
email: joi.string().email({ tlds: { allow: false } }).max(255).optional().messages({
|
||||
'string.base': 'Email harus berupa teks.',
|
||||
'string.email': 'Format email tidak valid.',
|
||||
'string.max': 'Email maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
kontak: joi.string().pattern(phoneRegex).max(255).optional().messages({
|
||||
'string.base': 'Kontak harus berupa teks.',
|
||||
'string.pattern.base': 'Format nomor kontak tidak valid. Gunakan format Indonesia (08xx atau +628xx).',
|
||||
'string.max': 'Kontak maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
jurusan: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Jurusan harus berupa teks.',
|
||||
'string.max': 'Jurusan maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
universitas: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Universitas harus berupa teks.',
|
||||
'string.max': 'Universitas maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
negara: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Negara harus berupa teks.',
|
||||
'string.max': 'Negara maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
motivasi: joi.string().optional().messages({
|
||||
'string.base': 'Motivasi harus berupa teks.',
|
||||
}),
|
||||
|
||||
relevant_skills: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Keahlian yang relevan harus berupa teks.',
|
||||
'string.max': 'Keahlian yang relevan maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
cv_path: joi.string().optional().messages({
|
||||
'string.base': 'Path CV harus berupa teks.',
|
||||
}),
|
||||
|
||||
portofolio_path: joi.string().optional().messages({
|
||||
'string.base': 'Path portofolio harus berupa teks.',
|
||||
}),
|
||||
|
||||
status: joi.string().valid('diterima', 'diproses', 'ditolak').optional().messages({
|
||||
'string.base': 'Status harus berupa teks.',
|
||||
'any.only': 'Status hanya boleh "diterima", "diproses", atau "ditolak".',
|
||||
}),
|
||||
});
|
||||
|
||||
const getAllLamaranMagangModel = joi.object().keys({
|
||||
page: joi.number().integer().min(0).optional().messages({
|
||||
'number.base': 'page harus berupa angka.',
|
||||
}),
|
||||
limit: joi.number().integer().min(1).optional().messages({
|
||||
'number.base': 'Limit harus berupa angka.',
|
||||
}),
|
||||
posisi: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Posisi harus berupa teks.',
|
||||
'string.max': 'Posisi maksimal {#limit} karakter.',
|
||||
}),
|
||||
status: joi.string().valid('diterima', 'diproses', 'ditolak').optional().messages({
|
||||
'string.base': 'Status harus berupa teks.',
|
||||
'any.only': 'Status hanya boleh "diterima", "diproses", atau "ditolak".',
|
||||
}),
|
||||
universitas: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Universitas harus berupa teks.',
|
||||
'string.max': 'Universitas maksimal {#limit} karakter.',
|
||||
}),
|
||||
id_lowongan: joi.string().uuid().optional().messages({
|
||||
'string.base': 'ID lowongan magang harus berupa teks.',
|
||||
'string.guid': 'Format ID lowongan magang tidak valid.',
|
||||
}),
|
||||
});
|
||||
|
||||
const statisticModel = joi.object().keys({
|
||||
batch: joi.number().integer().min(1).optional().messages({
|
||||
'number.base': 'Batch harus berupa angka.',
|
||||
'number.min': 'Batch minimal adalah {#limit}.',
|
||||
}),
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
createLamaranMagangModel,
|
||||
updateLamaranStatusModel,
|
||||
updateLamaranMagangModel,
|
||||
getAllLamaranMagangModel,
|
||||
statisticModel,
|
||||
};
|
||||
@@ -0,0 +1,292 @@
|
||||
const prisma = require('../../../helpers/db/db_connection');
|
||||
const { Prisma } = require('../../../generated/prisma')
|
||||
|
||||
class LamaranMagangRepository {
|
||||
async create(lamaranData) {
|
||||
return prisma.lamaranMagang.create({
|
||||
data: {
|
||||
...lamaranData,
|
||||
created_at: new Date(),
|
||||
update_at: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findAll({ offset, limit, status, posisi, universitas, id_lowongan }) {
|
||||
const where = {};
|
||||
|
||||
if (status) {
|
||||
where.status = status;
|
||||
}
|
||||
if (posisi) {
|
||||
where.lowongan_magang = { posisi: posisi };
|
||||
}
|
||||
if (universitas) {
|
||||
where.mahasiswa = { universitas: universitas };
|
||||
}
|
||||
if (id_lowongan) {
|
||||
where.id_lowongan_magang = id_lowongan;
|
||||
}
|
||||
|
||||
const lamaranList = await prisma.lamaranMagang.findMany({
|
||||
skip: offset,
|
||||
take: limit,
|
||||
where,
|
||||
include: {
|
||||
mahasiswa: {
|
||||
select: { nama_depan: true, nama_belakang: true },
|
||||
},
|
||||
lowongan_magang: {
|
||||
select: { posisi: true, kelompok_peminatan: true },
|
||||
},
|
||||
batch_data: {
|
||||
select: {
|
||||
id: true,
|
||||
batch_number: true,
|
||||
is_active: true,
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return lamaranList;
|
||||
}
|
||||
|
||||
async countAllLamaran({ status, posisi, universitas }) {
|
||||
|
||||
const where = {};
|
||||
|
||||
if (status) {
|
||||
where.status = status;
|
||||
}
|
||||
if (posisi) {
|
||||
where.lowongan_magang = { posisi: posisi };
|
||||
}
|
||||
if (universitas) {
|
||||
where.mahasiswa = { universitas: universitas };
|
||||
}
|
||||
|
||||
return prisma.lamaranMagang.count(
|
||||
{ where }
|
||||
);
|
||||
}
|
||||
|
||||
async findById(id_lamaran_magang) {
|
||||
return prisma.lamaranMagang.findUnique({
|
||||
where: { id: parseInt(id_lamaran_magang) },
|
||||
include: {
|
||||
mahasiswa: {
|
||||
select: {
|
||||
nama_depan: true,
|
||||
nama_belakang: true,
|
||||
email: true,
|
||||
kontak: true,
|
||||
jurusan: true,
|
||||
cv_path: true,
|
||||
portofolio_path: true,
|
||||
motivasi: true,
|
||||
relevant_skills: true,
|
||||
universitas: true,
|
||||
negara: true,
|
||||
},
|
||||
},
|
||||
lowongan_magang: {
|
||||
select: {
|
||||
posisi: true,
|
||||
},
|
||||
},
|
||||
batch_data: {
|
||||
select: {
|
||||
id: true,
|
||||
batch_number: true,
|
||||
is_active: true,
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findByMahasiswaAndLowongan(id_mahasiswa, id_lowongan_magang) {
|
||||
return prisma.lamaranMagang.findFirst({
|
||||
where: {
|
||||
id_mahasiswa: parseInt(id_mahasiswa),
|
||||
id_lowongan_magang: id_lowongan_magang,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findAnyLamaranByMahasiswa(id_mahasiswa) {
|
||||
return prisma.lamaranMagang.findFirst({
|
||||
where: {
|
||||
id_mahasiswa: parseInt(id_mahasiswa),
|
||||
},
|
||||
include: {
|
||||
lowongan_magang: {
|
||||
select: {
|
||||
posisi: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findDetailById(idLamaran) {
|
||||
return prisma.lamaranMagang.findUnique({
|
||||
where: { id: parseInt(idLamaran) },
|
||||
include: {
|
||||
mahasiswa: true,
|
||||
lowongan_magang: true,
|
||||
batch_data: {
|
||||
select: {
|
||||
id: true,
|
||||
batch_number: true,
|
||||
is_active: true,
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async updateStatus(id_lamaran_magang, status) {
|
||||
return prisma.lamaranMagang.update({
|
||||
where: { id: parseInt(id_lamaran_magang) },
|
||||
data: {
|
||||
status,
|
||||
update_at: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async deleteById(id) {
|
||||
return prisma.lamaranMagang.delete({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
}
|
||||
|
||||
async getStatistics({ query }) {
|
||||
let where = {};
|
||||
|
||||
if (query && query.batch) {
|
||||
where.batch = parseInt(query.batch);
|
||||
}
|
||||
|
||||
const [total, diterima, ditolak, diproses] = await Promise.all([
|
||||
prisma.lamaranMagang.count({ where }),
|
||||
prisma.lamaranMagang.count({ where: { ...where, status: 'diterima' } }),
|
||||
prisma.lamaranMagang.count({ where: { ...where, status: 'ditolak' } }),
|
||||
prisma.lamaranMagang.count({ where: { ...where, status: 'diproses' } }),
|
||||
]);
|
||||
|
||||
return { total, diterima, ditolak, diproses };
|
||||
}
|
||||
|
||||
async getStatisticsByPosition({ query }) {
|
||||
let where = {};
|
||||
|
||||
if (query && query.batch) {
|
||||
where.batch = parseInt(query.batch);
|
||||
}
|
||||
|
||||
const data = await prisma.lamaranMagang.groupBy({
|
||||
by: ['id_lowongan_magang'],
|
||||
where,
|
||||
_count: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
const positions = await Promise.all(
|
||||
data.map(async (item) => {
|
||||
const lowongan = await prisma.lowonganMagang.findUnique({
|
||||
where: { id: item.id_lowongan_magang },
|
||||
select: { posisi: true },
|
||||
});
|
||||
|
||||
const [total, diterima, ditolak, diproses] = await Promise.all([
|
||||
prisma.lamaranMagang.count({
|
||||
where: { id_lowongan_magang: item.id_lowongan_magang },
|
||||
}),
|
||||
prisma.lamaranMagang.count({
|
||||
where: { id_lowongan_magang: item.id_lowongan_magang, status: 'diterima' },
|
||||
}),
|
||||
prisma.lamaranMagang.count({
|
||||
where: { id_lowongan_magang: item.id_lowongan_magang, status: 'ditolak' },
|
||||
}),
|
||||
prisma.lamaranMagang.count({
|
||||
where: { id_lowongan_magang: item.id_lowongan_magang, status: 'diproses' },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
posisi: lowongan?.posisi || 'Tidak Diketahui',
|
||||
total,
|
||||
diterima,
|
||||
ditolak,
|
||||
diproses,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return positions;
|
||||
}
|
||||
|
||||
async getStatisticsByCountry({ query }) {
|
||||
|
||||
// Note : Menggunakan Raw Query karena Prisma ngga dukung join yang kompleks (lebih mudah juga :b)
|
||||
const whereClause = query.batch
|
||||
? Prisma.sql`WHERE lm.batch = ${parseInt(query.batch)}`
|
||||
: Prisma.sql``;
|
||||
|
||||
const data = await prisma.$queryRaw`
|
||||
SELECT
|
||||
m.negara,
|
||||
COUNT(*) as total,
|
||||
SUM(lm.status = 'diterima') as diterima,
|
||||
SUM(lm.status = 'ditolak') as ditolak,
|
||||
SUM(lm.status = 'diproses') as diproses
|
||||
FROM lamaran_magang lm
|
||||
JOIN mahasiswa m ON lm.id_mahasiswa = m.id
|
||||
${whereClause}
|
||||
GROUP BY m.negara
|
||||
ORDER BY total DESC
|
||||
`;
|
||||
|
||||
return data.map((item) => ({
|
||||
negara: item.negara,
|
||||
total: Number(item.total),
|
||||
diterima: Number(item.diterima),
|
||||
ditolak: Number(item.ditolak),
|
||||
diproses: Number(item.diproses),
|
||||
}));
|
||||
}
|
||||
|
||||
async getStatisticsByUniversity({ query }) {
|
||||
const whereClause = query.batch
|
||||
? Prisma.sql`WHERE lm.batch = ${parseInt(query.batch)}`
|
||||
: Prisma.sql``;
|
||||
|
||||
const data = await prisma.$queryRaw`
|
||||
SELECT
|
||||
m.universitas,
|
||||
COUNT(*) as total,
|
||||
SUM(lm.status = 'diterima') as diterima,
|
||||
SUM(lm.status = 'ditolak') as ditolak,
|
||||
SUM(lm.status = 'diproses') as diproses
|
||||
FROM lamaran_magang lm
|
||||
JOIN mahasiswa m ON lm.id_mahasiswa = m.id
|
||||
${whereClause}
|
||||
GROUP BY m.universitas
|
||||
ORDER BY total DESC
|
||||
`;
|
||||
|
||||
return data.map((item) => ({
|
||||
universitas: item.universitas,
|
||||
total: Number(item.total),
|
||||
diterima: Number(item.diterima),
|
||||
ditolak: Number(item.ditolak),
|
||||
diproses: Number(item.diproses),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new LamaranMagangRepository();
|
||||
+311
@@ -0,0 +1,311 @@
|
||||
const lamaranMagangRepository = require('../repositories/lamaranMagang.repository');
|
||||
const mahasiswaRepository = require('../../mahasiswa/repositories/mahasiswa.repository');
|
||||
const lowonganMagangRepository = require('../../lowonganMagang/repositories/lowonganMagang.repository');
|
||||
const batchRepository = require('../../batch/repositories/batch.repository');
|
||||
const imageUploadHelper = require('../../../helpers/utils/imageUpload.helper');
|
||||
const { sendConfirmationEmail, sendStatusEmail } = require('../helpers/email.helper');
|
||||
const ExcelJS = require('exceljs');
|
||||
const path = require('path');
|
||||
const { deleteFileIfExists } = require('../../../helpers/utils/fileHelper');
|
||||
const { data, error, paginationData } = require('../../../helpers/utils/wrapper');
|
||||
const { NotFoundError, ConflictError } = require('../../../helpers/error');
|
||||
|
||||
class LamaranMagangService {
|
||||
async createLamaranMagang(id_lowongan_magang, mahasiswaFormData, uploadedFiles) {
|
||||
try {
|
||||
const lowonganMagang = await lowonganMagangRepository.findById(id_lowongan_magang);
|
||||
|
||||
if (!lowonganMagang) {
|
||||
return error(new NotFoundError('Lowongan Magang Tidak Ditemukan'));
|
||||
}
|
||||
|
||||
const batchId = lowonganMagang.batch?.id || null;
|
||||
|
||||
const existingMahasiswa = await mahasiswaRepository.findByEmail(mahasiswaFormData.email);
|
||||
|
||||
if (existingMahasiswa) {
|
||||
|
||||
const existingLamaran = await lamaranMagangRepository.findAnyLamaranByMahasiswa(
|
||||
existingMahasiswa.id
|
||||
);
|
||||
|
||||
if (existingLamaran) {
|
||||
const posisiYangSudahDilamar = existingLamaran.lowongan_magang?.posisi || 'posisi tertentu';
|
||||
return error(new ConflictError(
|
||||
`Anda sudah pernah melamar untuk posisi ${posisiYangSudahDilamar}. Setiap pengguna hanya dapat melamar satu posisi.`
|
||||
));
|
||||
}
|
||||
|
||||
const lamaranData = {
|
||||
id_mahasiswa: existingMahasiswa.id,
|
||||
id_lowongan_magang,
|
||||
batch: batchId,
|
||||
status: 'diproses',
|
||||
};
|
||||
|
||||
await lamaranMagangRepository.create(lamaranData);
|
||||
|
||||
return data({
|
||||
id_mahasiswa: existingMahasiswa.id,
|
||||
id_lowongan_magang,
|
||||
batch: batchId,
|
||||
status: 'diproses',
|
||||
});
|
||||
}
|
||||
|
||||
const cv_path = imageUploadHelper.uploadCV(uploadedFiles.cv);
|
||||
const portofolio_path = imageUploadHelper.uploadPortofolio(uploadedFiles.portofolio);
|
||||
|
||||
const namaBelakangFinal = mahasiswaFormData.nama_belakang?.trim() || null;
|
||||
|
||||
const mahasiswaData = {
|
||||
nama_depan: mahasiswaFormData.nama_depan,
|
||||
nama_belakang: namaBelakangFinal,
|
||||
email: mahasiswaFormData.email,
|
||||
kontak: mahasiswaFormData.kontak,
|
||||
jurusan: mahasiswaFormData.jurusan,
|
||||
universitas: mahasiswaFormData.universitas,
|
||||
negara: mahasiswaFormData.negara,
|
||||
motivasi: mahasiswaFormData.motivasi,
|
||||
relevant_skills: mahasiswaFormData.relevant_skills,
|
||||
role: 'student',
|
||||
cv_path,
|
||||
portofolio_path,
|
||||
};
|
||||
|
||||
const createdMahasiswa = await mahasiswaRepository.create(mahasiswaData);
|
||||
const id_mahasiswa = createdMahasiswa.id;
|
||||
|
||||
const lamaranData = {
|
||||
id_mahasiswa,
|
||||
id_lowongan_magang,
|
||||
batch: batchId,
|
||||
status: 'diproses',
|
||||
};
|
||||
|
||||
await lamaranMagangRepository.create(lamaranData);
|
||||
|
||||
await sendConfirmationEmail(mahasiswaData, lowonganMagang);
|
||||
|
||||
return data({
|
||||
id_mahasiswa,
|
||||
id_lowongan_magang,
|
||||
batch: batchId,
|
||||
status: 'diproses',
|
||||
});
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllLamaranMagang(query = {}) {
|
||||
try {
|
||||
const { page = 1, limit = 10, posisi, status, universitas, id_lowongan } = query;
|
||||
const offset = (page - 1) * limit;
|
||||
const lamaranList = await lamaranMagangRepository.findAll({ offset, limit, status, posisi, universitas, id_lowongan });
|
||||
const total = await lamaranMagangRepository.countAllLamaran({ status, posisi, universitas, id_lowongan });
|
||||
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
const meta = { page: Number(page), limit: Number(limit), total, totalPages };
|
||||
return paginationData(lamaranList, meta);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getLamaranById(id_lamaran_magang) {
|
||||
try {
|
||||
const lamaran = await lamaranMagangRepository.findById(id_lamaran_magang);
|
||||
|
||||
if (!lamaran) {
|
||||
return error(new NotFoundError('Lamaran Magang Tidak Ditemukan'));
|
||||
}
|
||||
|
||||
return data(lamaran);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getDetailLamaranById(id_lamaran) {
|
||||
try {
|
||||
const lamaran = await lamaranMagangRepository.findDetailById(id_lamaran);
|
||||
|
||||
if (!lamaran) {
|
||||
return error(new NotFoundError('Lamaran Magang Tidak Ditemukan'));
|
||||
}
|
||||
|
||||
return data(lamaran);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async updateLamaranStatus(id_lamaran_magang, status) {
|
||||
try {
|
||||
const checkResult = await this.getDetailLamaranById(id_lamaran_magang);
|
||||
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const result = await lamaranMagangRepository.updateStatus(id_lamaran_magang, status);
|
||||
|
||||
await sendStatusEmail(checkResult.data, status);
|
||||
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteLamaran(id) {
|
||||
try {
|
||||
const checkResult = await this.getDetailLamaranById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const lamaran = checkResult.data;
|
||||
|
||||
if (lamaran.cv_path) {
|
||||
const cvFileName = path.basename(lamaran.cv_path);
|
||||
await deleteFileIfExists(cvFileName);
|
||||
}
|
||||
|
||||
if (lamaran.portofolio_path) {
|
||||
const portofolioFileName = path.basename(lamaran.portofolio_path);
|
||||
await deleteFileIfExists(portofolioFileName);
|
||||
}
|
||||
|
||||
const result = await lamaranMagangRepository.deleteById(id);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async exportToExcel() {
|
||||
try {
|
||||
const lamaranList = await lamaranMagangRepository.findAll({});
|
||||
|
||||
if (!lamaranList || lamaranList.length === 0) {
|
||||
return error(new NotFoundError("Tidak ada data lamaran untuk diekspor"));
|
||||
}
|
||||
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const worksheet = workbook.addWorksheet('Lamaran Magang');
|
||||
|
||||
worksheet.columns = [
|
||||
{ header: 'ID', key: 'id', width: 10 },
|
||||
{ header: 'Nama Depan', key: 'nama_depan', width: 20 },
|
||||
{ header: 'Nama Belakang', key: 'nama_belakang', width: 20 },
|
||||
{ header: 'Posisi', key: 'posisi', width: 25 },
|
||||
{ header: 'Kelompok Peminatan', key: 'kelompok_peminatan', width: 25 },
|
||||
{ header: 'Status', key: 'status', width: 15 },
|
||||
{ header: 'Tanggal Dibuat', key: 'created_at', width: 20 },
|
||||
];
|
||||
|
||||
lamaranList.forEach((lamaran) => {
|
||||
worksheet.addRow({
|
||||
id: lamaran.id,
|
||||
nama_depan: lamaran.mahasiswa?.nama_depan || '',
|
||||
nama_belakang: lamaran.mahasiswa?.nama_belakang || '',
|
||||
posisi: lamaran.lowongan_magang?.posisi || '',
|
||||
kelompok_peminatan: lamaran.lowongan_magang?.kelompok_peminatan || '',
|
||||
status: lamaran.status,
|
||||
created_at: lamaran.created_at,
|
||||
});
|
||||
});
|
||||
|
||||
worksheet.getRow(1).font = { bold: true };
|
||||
worksheet.getRow(1).fill = {
|
||||
type: 'pattern',
|
||||
pattern: 'solid',
|
||||
fgColor: { argb: 'FFD3D3D3' },
|
||||
};
|
||||
|
||||
return data(workbook);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getDashboardStatistics(query) {
|
||||
try {
|
||||
const batch = await batchRepository.getBatchById(query.batch);
|
||||
const batchDisplay = batch ? batch.batch_number : 'Data Seluruh Batch';
|
||||
const stats = await lamaranMagangRepository.getStatistics({ query });
|
||||
|
||||
const acceptanceRate = stats.total > 0 ? ((stats.diterima / stats.total) * 100).toFixed(1) : 0;
|
||||
const rejectionRate = stats.total > 0 ? ((stats.ditolak / stats.total) * 100).toFixed(1) : 0;
|
||||
const pendingRate = stats.total > 0 ? ((stats.diproses / stats.total) * 100).toFixed(1) : 0;
|
||||
|
||||
if (stats.total === 0) {
|
||||
return error(new NotFoundError(`Tidak ada data lamaran ditemukan pada batch ${batchDisplay}`));
|
||||
}
|
||||
|
||||
return data({
|
||||
total_pendaftar: stats.total,
|
||||
total_diterima: stats.diterima,
|
||||
total_ditolak: stats.ditolak,
|
||||
sedang_diproses: stats.diproses,
|
||||
presentase_diterima: `${acceptanceRate}%`,
|
||||
presentase_ditolak: `${rejectionRate}%`,
|
||||
presentase_diproses: `${pendingRate}%`,
|
||||
batch: batchDisplay,
|
||||
});
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getStatisticsByPosition(query) {
|
||||
try {
|
||||
const batch = await batchRepository.getBatchById(query.batch);
|
||||
const batchDisplay = batch ? batch.batch_number : 'semua batch';
|
||||
const positions = await lamaranMagangRepository.getStatisticsByPosition({ query });
|
||||
|
||||
if (positions.length === 0) {
|
||||
return error(new NotFoundError(`Tidak ada data lamaran ditemukan pada batch ${batchDisplay}`));
|
||||
}
|
||||
|
||||
return data(positions);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getStatisticsByCountry(query) {
|
||||
try {
|
||||
const batch = await batchRepository.getBatchById(query.batch);
|
||||
const batchDisplay = batch ? batch.batch_number : 'semua batch';
|
||||
const countries = await lamaranMagangRepository.getStatisticsByCountry({ query });
|
||||
if (countries.length === 0) {
|
||||
return error(new NotFoundError(`Tidak ada data lamaran ditemukan pada batch ${batchDisplay}`));
|
||||
}
|
||||
|
||||
return data(countries);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getStatisticsByUniversity(query) {
|
||||
try {
|
||||
const batch = await batchRepository.getBatchById(query.batch);
|
||||
const batchDisplay = batch ? batch.batch_number : 'semua batch';
|
||||
const universities = await lamaranMagangRepository.getStatisticsByUniversity({ query });
|
||||
if (universities.length === 0) {
|
||||
return error(new NotFoundError(`Tidak ada data lamaran ditemukan pada batch ${batchDisplay}`));
|
||||
}
|
||||
return data(universities);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
module.exports = new LamaranMagangService();
|
||||
@@ -0,0 +1,157 @@
|
||||
const lowonganMagangService = require('../services/lowonganMagang.service');
|
||||
const { response, error } = require('../../../helpers/utils/wrapper');
|
||||
const { BadRequestError, ForbiddenError, InternalServerError } = require('../../../helpers/error');
|
||||
const { SUCCESS, ERROR } = require('../../../helpers/http-status/status_code');
|
||||
const { isValidPayload } = require('../../../helpers/utils/validator');
|
||||
const { createLowonganMagangModel, updateLowonganMagangModel } = require('../models/lowonganMagang.model');
|
||||
const { deleteFileIfExists } = require('../../../helpers/utils/fileHelper');
|
||||
|
||||
class LowonganMagangController {
|
||||
async addLowonganMagang(req, res) {
|
||||
try {
|
||||
const image_path = req.file;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, createLowonganMagangModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
if (image_path?.filename) {
|
||||
await deleteFileIfExists(image_path.filename);
|
||||
}
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await lowonganMagangService.createLowonganMagang(validatePayload.data, image_path);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Lowongan magang berhasil dibuat', SUCCESS.CREATED);
|
||||
} catch (err) {
|
||||
if (req.file?.filename) {
|
||||
await deleteFileIfExists(req.file.filename);
|
||||
}
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllLowonganMagang(req, res) {
|
||||
try {
|
||||
const result = await lowonganMagangService.getAllLowonganMagang();
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Berhasil mengambil semua lowongan magang', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)),
|
||||
'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getLowonganMagangById(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await lowonganMagangService.getLowonganMagangById(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Berhasil mengambil lowongan magang berdasarkan ID', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getLowonganByKelompokPeminatan(req, res) {
|
||||
try {
|
||||
const { kelompok_peminatan } = req.params;
|
||||
|
||||
const result = await lowonganMagangService.getLowonganByKelompokPeminatan(kelompok_peminatan);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Berhasil mengambil lowongan magang berdasarkan kelompok peminatan', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllKelompokPeminatan(req, res) {
|
||||
try {
|
||||
const result = await lowonganMagangService.getAllKelompokPeminatan();
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Berhasil mengambil semua kelompok peminatan', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async updateLowonganMagang(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const image_path = req.file;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, updateLowonganMagangModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
if (image_path?.filename) {
|
||||
await deleteFileIfExists(image_path.filename);
|
||||
}
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await lowonganMagangService.updateLowonganMagang(id, validatePayload.data, image_path);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Lowongan magang berhasil diperbarui', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
if (req.file?.filename) {
|
||||
await deleteFileIfExists(req.file.filename);
|
||||
}
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteLowonganMagangById(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await lowonganMagangService.deleteLowonganMagang(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Lowongan magang berhasil dihapus', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new LowonganMagangController();
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
class FileUploadHelper {
|
||||
uploadImage(file) {
|
||||
if (!file) {
|
||||
throw new Error('Please upload an image!');
|
||||
}
|
||||
|
||||
const filePath = `/uploads/${file.filename}`;
|
||||
return filePath;
|
||||
}
|
||||
|
||||
validateImage(file) {
|
||||
if (!file) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
|
||||
return allowedTypes.includes(file.mimetype);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new FileUploadHelper();
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
class StatusHelper {
|
||||
calculateStatus(durasi_awal, durasi_akhir) {
|
||||
const now = new Date();
|
||||
const startDate = new Date(durasi_awal);
|
||||
const endDate = new Date(durasi_akhir);
|
||||
|
||||
if (now >= startDate && now <= endDate) {
|
||||
return 'dibuka';
|
||||
}
|
||||
return 'ditutup';
|
||||
}
|
||||
|
||||
updateLowonganStatus(lowongan) {
|
||||
const status = this.calculateStatus(lowongan.durasi_awal, lowongan.durasi_akhir);
|
||||
return {
|
||||
...lowongan,
|
||||
status_lowongan: status,
|
||||
};
|
||||
}
|
||||
|
||||
updateMultipleLowonganStatus(lowonganList) {
|
||||
return lowonganList.map((lowongan) => this.updateLowonganStatus(lowongan));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new StatusHelper();
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
const lowonganMagangController = require('./controllers/lowonganMagang.controller');
|
||||
const lowonganMagangService = require('./services/lowonganMagang.service');
|
||||
const lowonganMagangRepository = require('./repositories/lowonganMagang.repository');
|
||||
const statusHelper = require('./helpers/status.helper');
|
||||
|
||||
module.exports = {
|
||||
lowonganMagangController,
|
||||
lowonganMagangService,
|
||||
lowonganMagangRepository,
|
||||
statusHelper
|
||||
};
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
const joi = require('joi');
|
||||
|
||||
const createLowonganMagangModel = joi.object().keys({
|
||||
posisi: joi.string().max(255).required().messages({
|
||||
'string.base': 'Posisi harus berupa teks.',
|
||||
'string.empty': 'Posisi tidak boleh kosong.',
|
||||
'string.max': 'Posisi maksimal {#limit} karakter.',
|
||||
'any.required': 'Posisi wajib diisi.',
|
||||
}),
|
||||
|
||||
kelompok_peminatan: joi.string().max(255).required().messages({
|
||||
'string.base': 'Kelompok peminatan harus berupa teks.',
|
||||
'string.empty': 'Kelompok peminatan tidak boleh kosong.',
|
||||
'string.max': 'Kelompok peminatan maksimal {#limit} karakter.',
|
||||
'any.required': 'Kelompok peminatan wajib diisi.',
|
||||
}),
|
||||
|
||||
jobdesk: joi.string().required().messages({
|
||||
'string.base': 'Jobdesk harus berupa teks.',
|
||||
'string.empty': 'Jobdesk tidak boleh kosong.',
|
||||
'any.required': 'Jobdesk wajib diisi.',
|
||||
}),
|
||||
|
||||
lokasi: joi.string().max(255).required().messages({
|
||||
'string.base': 'Lokasi harus berupa teks.',
|
||||
'string.empty': 'Lokasi tidak boleh kosong.',
|
||||
'string.max': 'Lokasi maksimal {#limit} karakter.',
|
||||
'any.required': 'Lokasi wajib diisi.',
|
||||
}),
|
||||
|
||||
kualifikasi: joi.string().required().messages({
|
||||
'string.base': 'Kualifikasi harus berupa teks.',
|
||||
'string.empty': 'Kualifikasi tidak boleh kosong.',
|
||||
'any.required': 'Kualifikasi wajib diisi.',
|
||||
}),
|
||||
|
||||
benefit: joi.string().required().messages({
|
||||
'string.base': 'Benefit harus berupa teks.',
|
||||
'string.empty': 'Benefit tidak boleh kosong.',
|
||||
'any.required': 'Benefit wajib diisi.',
|
||||
}),
|
||||
|
||||
durasi_awal: joi.date().required().messages({
|
||||
'date.base': 'Durasi awal harus berupa tanggal yang valid.',
|
||||
'any.required': 'Durasi awal wajib diisi.',
|
||||
}),
|
||||
|
||||
durasi_akhir: joi.date().min(joi.ref('durasi_awal')).required().messages({
|
||||
'date.base': 'Durasi akhir harus berupa tanggal yang valid.',
|
||||
'date.min': 'Durasi akhir harus setelah atau sama dengan durasi awal.',
|
||||
'any.required': 'Durasi akhir wajib diisi.',
|
||||
}),
|
||||
|
||||
paid: joi.string().valid('paid', 'unpaid').required().messages({
|
||||
'string.empty': 'Status paid tidak boleh kosong.',
|
||||
'string.base': 'Status paid harus berupa teks.',
|
||||
'any.only': 'Status paid hanya boleh "paid" atau "unpaid".',
|
||||
'any.required': 'Status paid wajib diisi.',
|
||||
}),
|
||||
|
||||
batch: joi.number().integer().min(1).optional().messages({
|
||||
'number.base': 'Batch harus berupa angka.',
|
||||
'number.integer': 'Batch harus berupa bilangan bulat.',
|
||||
'number.min': 'Batch minimal {#limit}.',
|
||||
}),
|
||||
|
||||
image_path: joi.string().optional().allow('', null).messages({
|
||||
'string.base': 'Path gambar harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
const updateLowonganMagangModel = joi.object().keys({
|
||||
posisi: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Posisi harus berupa teks.',
|
||||
'string.max': 'Posisi maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
kelompok_peminatan: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Kelompok peminatan harus berupa teks.',
|
||||
'string.max': 'Kelompok peminatan maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
jobdesk: joi.string().optional().messages({
|
||||
'string.base': 'Jobdesk harus berupa teks.',
|
||||
}),
|
||||
|
||||
lokasi: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Lokasi harus berupa teks.',
|
||||
'string.max': 'Lokasi maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
kualifikasi: joi.string().optional().messages({
|
||||
'string.base': 'Kualifikasi harus berupa teks.',
|
||||
}),
|
||||
|
||||
benefit: joi.string().optional().messages({
|
||||
'string.base': 'Benefit harus berupa teks.',
|
||||
}),
|
||||
|
||||
durasi_awal: joi.date().optional().messages({
|
||||
'date.base': 'Durasi awal harus berupa tanggal yang valid.',
|
||||
}),
|
||||
|
||||
durasi_akhir: joi.date().min(joi.ref('durasi_awal')).optional().messages({
|
||||
'date.base': 'Durasi akhir harus berupa tanggal yang valid.',
|
||||
'date.min': 'Durasi akhir harus setelah atau sama dengan durasi awal.',
|
||||
}),
|
||||
|
||||
paid: joi.string().valid('paid', 'unpaid').optional().messages({
|
||||
'string.base': 'Status paid harus berupa teks.',
|
||||
'any.only': 'Status paid hanya boleh "paid" atau "unpaid".',
|
||||
}),
|
||||
|
||||
batch: joi.number().integer().min(1).optional().messages({
|
||||
'number.base': 'Batch harus berupa angka.',
|
||||
'number.integer': 'Batch harus berupa bilangan bulat.',
|
||||
'number.min': 'Batch minimal {#limit}.',
|
||||
}),
|
||||
|
||||
image_path: joi.string().optional().allow('', null).messages({
|
||||
'string.base': 'Path gambar harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
createLowonganMagangModel,
|
||||
updateLowonganMagangModel,
|
||||
};
|
||||
@@ -0,0 +1,78 @@
|
||||
const prisma = require('../../../helpers/db/db_connection');
|
||||
|
||||
|
||||
class LowonganMagangRepository {
|
||||
async create(lowonganData) {
|
||||
return prisma.lowonganMagang.create({
|
||||
data: lowonganData,
|
||||
});
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
return prisma.lowonganMagang.findMany({
|
||||
include: {
|
||||
batch: {
|
||||
select: {
|
||||
id: true,
|
||||
batch_number: true,
|
||||
is_active: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id) {
|
||||
return prisma.lowonganMagang.findUnique({
|
||||
where: { id: id },
|
||||
include: {
|
||||
batch: {
|
||||
select: {
|
||||
id: true,
|
||||
batch_number: true,
|
||||
is_active: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findByKelompokPeminatan(kelompok_peminatan) {
|
||||
return prisma.lowonganMagang.findMany({
|
||||
where: { kelompok_peminatan },
|
||||
include: {
|
||||
batch: {
|
||||
select: {
|
||||
id: true,
|
||||
batch_number: true,
|
||||
is_active: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findAllKelompokPeminatan() {
|
||||
return prisma.lowonganMagang.findMany({
|
||||
select: {
|
||||
kelompok_peminatan: true,
|
||||
},
|
||||
distinct: ['kelompok_peminatan'],
|
||||
});
|
||||
}
|
||||
|
||||
async updateById(id, lowonganData) {
|
||||
return prisma.lowonganMagang.update({
|
||||
where: { id: id },
|
||||
data: lowonganData,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteById(id) {
|
||||
return prisma.lowonganMagang.delete({
|
||||
where: { id: id },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new LowonganMagangRepository();
|
||||
@@ -0,0 +1,191 @@
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const path = require('path');
|
||||
const lowonganMagangRepository = require('../repositories/lowonganMagang.repository');
|
||||
const batchRepository = require('../../batch/repositories/batch.repository');
|
||||
const imageUploadHelper = require('../../../helpers/utils/imageUpload.helper');
|
||||
const statusHelper = require('../helpers/status.helper');
|
||||
const { deleteFileIfExists, validateImagePath } = require('../../../helpers/utils/fileHelper');
|
||||
const { data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { NotFoundError } = require('../../../helpers/error');
|
||||
|
||||
class LowonganMagangService {
|
||||
async createLowonganMagang(lowonganData, imageFile) {
|
||||
try {
|
||||
const activeBatch = await batchRepository.findActiveBatch();
|
||||
|
||||
if (!activeBatch) {
|
||||
return error(new NotFoundError('Tidak ada batch yang aktif'));
|
||||
}
|
||||
|
||||
const id = uuidv4();
|
||||
const imagePath = imageUploadHelper.uploadImage(imageFile);
|
||||
const status = statusHelper.calculateStatus(
|
||||
lowonganData.durasi_awal,
|
||||
lowonganData.durasi_akhir
|
||||
);
|
||||
|
||||
const newLowonganData = {
|
||||
id,
|
||||
...lowonganData,
|
||||
id_batch: activeBatch.id,
|
||||
status_lowongan: status,
|
||||
image_path: imagePath,
|
||||
};
|
||||
|
||||
const result = await lowonganMagangRepository.create(newLowonganData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
if (imageFile?.filename) {
|
||||
try {
|
||||
await deleteFileIfExists(imageFile.filename);
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup file:', cleanupErr);
|
||||
}
|
||||
}
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllLowonganMagang() {
|
||||
try {
|
||||
const lowonganList = await lowonganMagangRepository.findAll();
|
||||
|
||||
if (lowonganList.length === 0) {
|
||||
return data([]);
|
||||
}
|
||||
|
||||
const updatedList = statusHelper.updateMultipleLowonganStatus(lowonganList);
|
||||
|
||||
const validatedList = updatedList.map(lowongan => ({
|
||||
...lowongan,
|
||||
image_path: validateImagePath(lowongan.image_path)
|
||||
}));
|
||||
|
||||
return data(validatedList);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getLowonganMagangById(id) {
|
||||
try {
|
||||
const lowongan = await lowonganMagangRepository.findById(id);
|
||||
|
||||
if (!lowongan) {
|
||||
return error(new NotFoundError('Lowongan Magang Tidak Ditemukan'));
|
||||
}
|
||||
|
||||
const updatedLowongan = statusHelper.updateLowonganStatus(lowongan);
|
||||
|
||||
updatedLowongan.image_path = validateImagePath(updatedLowongan.image_path);
|
||||
|
||||
return data(updatedLowongan);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getLowonganByKelompokPeminatan(kelompok_peminatan) {
|
||||
try {
|
||||
const lowonganList = await lowonganMagangRepository.findByKelompokPeminatan(
|
||||
kelompok_peminatan
|
||||
);
|
||||
|
||||
if (lowonganList.length === 0) {
|
||||
return data([]);
|
||||
}
|
||||
|
||||
const updatedList = statusHelper.updateMultipleLowonganStatus(lowonganList);
|
||||
|
||||
const validatedList = updatedList.map(lowongan => ({
|
||||
...lowongan,
|
||||
image_path: validateImagePath(lowongan.image_path)
|
||||
}));
|
||||
|
||||
return data(validatedList);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllKelompokPeminatan() {
|
||||
try {
|
||||
const kelompokList = await lowonganMagangRepository.findAllKelompokPeminatan();
|
||||
const kelompokNames = kelompokList.map((row) => row.kelompok_peminatan);
|
||||
return data(kelompokNames);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async updateLowonganMagang(id, lowonganData, imageFile) {
|
||||
let oldImagePath = null;
|
||||
let newImageUploaded = false;
|
||||
|
||||
try {
|
||||
const checkResult = await this.getLowonganMagangById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const existingLowongan = checkResult.data;
|
||||
|
||||
if (imageFile) {
|
||||
oldImagePath = existingLowongan.image_path;
|
||||
|
||||
lowonganData.image_path = imageUploadHelper.uploadImage(imageFile);
|
||||
newImageUploaded = true;
|
||||
|
||||
if (oldImagePath) {
|
||||
const oldFileName = path.basename(oldImagePath);
|
||||
await deleteFileIfExists(oldFileName);
|
||||
}
|
||||
}
|
||||
|
||||
if (lowonganData.durasi_awal || lowonganData.durasi_akhir) {
|
||||
const durasi_awal = lowonganData.durasi_awal || existingLowongan.durasi_awal;
|
||||
const durasi_akhir = lowonganData.durasi_akhir || existingLowongan.durasi_akhir;
|
||||
|
||||
lowonganData.status_lowongan = statusHelper.calculateStatus(
|
||||
durasi_awal,
|
||||
durasi_akhir
|
||||
);
|
||||
}
|
||||
|
||||
const result = await lowonganMagangRepository.updateById(id, lowonganData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
if (newImageUploaded && imageFile?.filename) {
|
||||
try {
|
||||
await deleteFileIfExists(imageFile.filename);
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup new file:', cleanupErr);
|
||||
}
|
||||
}
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteLowonganMagang(id) {
|
||||
try {
|
||||
const checkResult = await this.getLowonganMagangById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const lowongan = checkResult.data;
|
||||
|
||||
if (lowongan.image_path) {
|
||||
const fileName = path.basename(lowongan.image_path);
|
||||
await deleteFileIfExists(fileName);
|
||||
}
|
||||
|
||||
const result = await lowonganMagangRepository.deleteById(id);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new LowonganMagangService();
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
const mahasiswaService = require('../services/mahasiswa.service');
|
||||
const { response, error, paginationResponse } = require('../../../helpers/utils/wrapper');
|
||||
const { InternalServerError } = require('../../../helpers/error');
|
||||
const { SUCCESS, ERROR } = require('../../../helpers/http-status/status_code');
|
||||
const { isValidPayload } = require('../../../helpers/utils/validator');
|
||||
const { createMahasiswaModel, updateMahasiswaModel, getAllMahasiswaModel } = require('../models/mahasiswa.model');
|
||||
|
||||
class MahasiswaController {
|
||||
async createMahasiswa(req, res) {
|
||||
try {
|
||||
const validatePayload = isValidPayload(req.body, createMahasiswaModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await mahasiswaService.createMahasiswa(validatePayload.data);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Mahasiswa berhasil dibuat', SUCCESS.CREATED);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllMahasiswa(req, res) {
|
||||
try {
|
||||
const validatePayload = isValidPayload(req.query, getAllMahasiswaModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const query = validatePayload.data;
|
||||
const result = await mahasiswaService.getAllMahasiswa({ query });
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return paginationResponse(res, 'success', result, 'Data mahasiswa berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getMahasiswaById(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await mahasiswaService.getMahasiswaById(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Mahasiswa berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async updateMahasiswa(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, updateMahasiswaModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const result = await mahasiswaService.updateMahasiswa(id, validatePayload.data);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Mahasiswa berhasil diperbarui', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteMahasiswa(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await mahasiswaService.deleteMahasiswa(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Mahasiswa berhasil dihapus', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteAllMahasiswa(req, res) {
|
||||
try {
|
||||
const result = await mahasiswaService.deleteAllMahasiswa();
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Semua mahasiswa berhasil dihapus', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new MahasiswaController();
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const mahasiswaController = require('./controllers/mahasiswa.controller');
|
||||
const mahasiswaService = require('./services/mahasiswa.service');
|
||||
const mahasiswaRepository = require('./repositories/mahasiswa.repository');
|
||||
|
||||
module.exports = {
|
||||
mahasiswaController,
|
||||
mahasiswaService,
|
||||
mahasiswaRepository
|
||||
};
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
const joi = require('joi');
|
||||
|
||||
const phoneRegex = /^(\+62|62|0)8[1-9][0-9]{6,11}$/;
|
||||
|
||||
const createMahasiswaModel = joi.object().keys({
|
||||
nama_depan: joi.string().max(255).required().messages({
|
||||
'string.base': 'Nama depan harus berupa teks.',
|
||||
'string.empty': 'Nama depan tidak boleh kosong.',
|
||||
'string.max': 'Nama depan maksimal {#limit} karakter.',
|
||||
'any.required': 'Nama depan wajib diisi.',
|
||||
}),
|
||||
|
||||
nama_belakang: joi.string().max(255).optional().allow('', null).messages({
|
||||
'string.base': 'Nama belakang harus berupa teks.',
|
||||
'string.max': 'Nama belakang maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
email: joi.string().email({ tlds: { allow: false } }).max(255).required().messages({
|
||||
'string.base': 'Email harus berupa teks.',
|
||||
'string.empty': 'Email tidak boleh kosong.',
|
||||
'string.email': 'Format email tidak valid.',
|
||||
'string.max': 'Email maksimal {#limit} karakter.',
|
||||
'any.required': 'Email wajib diisi.',
|
||||
}),
|
||||
|
||||
kontak: joi.string().pattern(phoneRegex).max(255).required().messages({
|
||||
'string.base': 'Kontak harus berupa teks.',
|
||||
'string.empty': 'Kontak tidak boleh kosong.',
|
||||
'string.pattern.base': 'Format nomor kontak tidak valid. Gunakan format Indonesia (08xx atau +628xx).',
|
||||
'string.max': 'Kontak maksimal {#limit} karakter.',
|
||||
'any.required': 'Kontak wajib diisi.',
|
||||
}),
|
||||
|
||||
jurusan: joi.string().max(255).required().messages({
|
||||
'string.base': 'Jurusan harus berupa teks.',
|
||||
'string.empty': 'Jurusan tidak boleh kosong.',
|
||||
'string.max': 'Jurusan maksimal {#limit} karakter.',
|
||||
'any.required': 'Jurusan wajib diisi.',
|
||||
}),
|
||||
|
||||
universitas: joi.string().max(255).required().messages({
|
||||
'string.base': 'Universitas harus berupa teks.',
|
||||
'string.empty': 'Universitas tidak boleh kosong.',
|
||||
'string.max': 'Universitas maksimal {#limit} karakter.',
|
||||
'any.required': 'Universitas wajib diisi.',
|
||||
}),
|
||||
|
||||
negara: joi.string().max(255).required().messages({
|
||||
'string.base': 'Negara harus berupa teks.',
|
||||
'string.empty': 'Negara tidak boleh kosong.',
|
||||
'string.max': 'Negara maksimal {#limit} karakter.',
|
||||
'any.required': 'Negara wajib diisi.',
|
||||
}),
|
||||
|
||||
role: joi.string().valid('student').default('student').messages({
|
||||
'string.base': 'Role harus berupa teks.',
|
||||
'any.only': 'Role hanya boleh "student".',
|
||||
}),
|
||||
|
||||
cv_path: joi.string().required().messages({
|
||||
'string.base': 'Path CV harus berupa teks.',
|
||||
'string.empty': 'Path CV tidak boleh kosong.',
|
||||
'any.required': 'CV wajib diupload.',
|
||||
}),
|
||||
|
||||
portofolio_path: joi.string().required().messages({
|
||||
'string.base': 'Path portofolio harus berupa teks.',
|
||||
'string.empty': 'Path portofolio tidak boleh kosong.',
|
||||
'any.required': 'Portofolio wajib diupload.',
|
||||
}),
|
||||
|
||||
motivasi: joi.string().required().messages({
|
||||
'string.base': 'Motivasi harus berupa teks.',
|
||||
'string.empty': 'Motivasi tidak boleh kosong.',
|
||||
'any.required': 'Motivasi wajib diisi.',
|
||||
}),
|
||||
|
||||
relevant_skills: joi.string().max(255).required().messages({
|
||||
'string.base': 'Keahlian yang relevan harus berupa teks.',
|
||||
'string.empty': 'Keahlian yang relevan tidak boleh kosong.',
|
||||
'string.max': 'Keahlian yang relevan maksimal {#limit} karakter.',
|
||||
'any.required': 'Keahlian yang relevan wajib diisi.',
|
||||
}),
|
||||
});
|
||||
|
||||
const updateMahasiswaModel = joi.object().keys({
|
||||
nama_depan: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Nama depan harus berupa teks.',
|
||||
'string.max': 'Nama depan maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
nama_belakang: joi.string().max(255).optional().allow('', null).messages({
|
||||
'string.base': 'Nama belakang harus berupa teks.',
|
||||
'string.max': 'Nama belakang maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
email: joi.string().email({ tlds: { allow: false } }).max(255).optional().messages({
|
||||
'string.base': 'Email harus berupa teks.',
|
||||
'string.email': 'Format email tidak valid.',
|
||||
'string.max': 'Email maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
kontak: joi.string().pattern(phoneRegex).max(255).optional().messages({
|
||||
'string.base': 'Kontak harus berupa teks.',
|
||||
'string.pattern.base': 'Format nomor kontak tidak valid. Gunakan format Indonesia (08xx atau +628xx).',
|
||||
'string.max': 'Kontak maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
jurusan: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Jurusan harus berupa teks.',
|
||||
'string.max': 'Jurusan maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
universitas: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Universitas harus berupa teks.',
|
||||
'string.max': 'Universitas maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
negara: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Negara harus berupa teks.',
|
||||
'string.max': 'Negara maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
cv_path: joi.string().optional().messages({
|
||||
'string.base': 'Path CV harus berupa teks.',
|
||||
}),
|
||||
|
||||
portofolio_path: joi.string().optional().messages({
|
||||
'string.base': 'Path portofolio harus berupa teks.',
|
||||
}),
|
||||
|
||||
motivasi: joi.string().optional().messages({
|
||||
'string.base': 'Motivasi harus berupa teks.',
|
||||
}),
|
||||
|
||||
relevant_skills: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Keahlian yang relevan harus berupa teks.',
|
||||
'string.max': 'Keahlian yang relevan maksimal {#limit} karakter.',
|
||||
}),
|
||||
});
|
||||
|
||||
const getAllMahasiswaModel = joi.object().keys({
|
||||
page: joi.number().integer().min(1).default(1).messages({
|
||||
'number.base': 'Halaman harus berupa angka.',
|
||||
'number.integer': 'Halaman harus berupa angka bulat.',
|
||||
'number.min': 'Halaman minimal adalah {#limit}.',
|
||||
}),
|
||||
limit: joi.number().integer().min(1).default(10).messages({
|
||||
'number.base': 'Limit harus berupa angka.',
|
||||
'number.integer': 'Limit harus berupa angka bulat.',
|
||||
'number.min': 'Limit minimal adalah {#limit}.',
|
||||
}),
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
createMahasiswaModel,
|
||||
updateMahasiswaModel,
|
||||
getAllMahasiswaModel
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
const prisma = require('../../../helpers/db/db_connection');
|
||||
|
||||
class MahasiswaRepository {
|
||||
async create(mahasiswaData) {
|
||||
return prisma.mahasiswa.create({
|
||||
data: mahasiswaData,
|
||||
});
|
||||
}
|
||||
|
||||
async findAll({ offset, limit }) {
|
||||
return prisma.mahasiswa.findMany({
|
||||
skip: offset,
|
||||
take: limit,
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id) {
|
||||
return prisma.mahasiswa.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
include: {
|
||||
lamaran_magang: {
|
||||
include: {
|
||||
lowongan_magang: {
|
||||
select: {
|
||||
posisi: true,
|
||||
kelompok_peminatan: true,
|
||||
durasi_awal: true,
|
||||
durasi_akhir: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async findByEmail(email) {
|
||||
return prisma.mahasiswa.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
}
|
||||
|
||||
async updateById(id, mahasiswaData) {
|
||||
return prisma.mahasiswa.update({
|
||||
where: { id: parseInt(id) },
|
||||
data: mahasiswaData,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteById(id) {
|
||||
return prisma.mahasiswa.delete({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
}
|
||||
|
||||
async deleteAll() {
|
||||
return prisma.mahasiswa.deleteMany();
|
||||
}
|
||||
|
||||
async countAllMahasiswa() {
|
||||
return prisma.mahasiswa.count();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new MahasiswaRepository();
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
const mahasiswaRepository = require('../repositories/mahasiswa.repository');
|
||||
const { data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { BadRequestError, NotFoundError } = require('../../../helpers/error');
|
||||
const { paginationData } = require("../../../helpers/utils/wrapper");
|
||||
|
||||
class MahasiswaService {
|
||||
async createMahasiswa(mahasiswaData) {
|
||||
try {
|
||||
const existingMahasiswa = await mahasiswaRepository.findByEmail(mahasiswaData.email);
|
||||
|
||||
if (existingMahasiswa) {
|
||||
return error(new BadRequestError('Email Sudah Terdaftar'));
|
||||
}
|
||||
|
||||
if (!mahasiswaData.role) {
|
||||
mahasiswaData.role = 'student';
|
||||
}
|
||||
|
||||
const result = await mahasiswaRepository.create(mahasiswaData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllMahasiswa({ page = 1, limit = 10 }) {
|
||||
try {
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const mahasiswa = await mahasiswaRepository.findAll({ offset, limit });
|
||||
|
||||
if (!mahasiswa || mahasiswa.length === 0) {
|
||||
return error(new NotFoundError('Tidak ada mahasiswa ditemukan'));
|
||||
}
|
||||
|
||||
const total = await mahasiswaRepository.countAllMahasiswa();
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
const meta = { page: Number(page), limit: Number(limit), total, totalPages };
|
||||
return paginationData(mahasiswa, meta);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getMahasiswaById(id) {
|
||||
try {
|
||||
const mahasiswa = await mahasiswaRepository.findById(id);
|
||||
|
||||
if (!mahasiswa) {
|
||||
return error(new NotFoundError('Mahasiswa Tidak Ditemukan'));
|
||||
}
|
||||
|
||||
return data(mahasiswa);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getMahasiswaByEmail(email) {
|
||||
try {
|
||||
const mahasiswa = await mahasiswaRepository.findByEmail(email);
|
||||
|
||||
if (!mahasiswa) {
|
||||
return error(new NotFoundError('Mahasiswa Tidak Ditemukan'));
|
||||
}
|
||||
|
||||
return data(mahasiswa);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async updateMahasiswa(id, mahasiswaData) {
|
||||
try {
|
||||
const checkResult = await this.getMahasiswaById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
if (mahasiswaData.email) {
|
||||
const existingMahasiswa = await mahasiswaRepository.findByEmail(mahasiswaData.email);
|
||||
|
||||
if (existingMahasiswa && existingMahasiswa.id !== id) {
|
||||
return error(new BadRequestError('Email Sudah Terdaftar'));
|
||||
}
|
||||
}
|
||||
|
||||
const result = await mahasiswaRepository.updateById(id, mahasiswaData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteMahasiswa(id) {
|
||||
try {
|
||||
const checkResult = await this.getMahasiswaById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const result = await mahasiswaRepository.deleteById(id);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteAllMahasiswa() {
|
||||
try {
|
||||
const result = await mahasiswaRepository.deleteAll();
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new MahasiswaService();
|
||||
@@ -0,0 +1,128 @@
|
||||
const partnershipService = require('../services/partnership.service');
|
||||
const { response, error } = require('../../../helpers/utils/wrapper');
|
||||
const { InternalServerError } = require('../../../helpers/error');
|
||||
const { SUCCESS, ERROR } = require('../../../helpers/http-status/status_code');
|
||||
const { isValidPayload } = require('../../../helpers/utils/validator');
|
||||
const { createPartnershipModel, updatePartnershipModel } = require('../models/partnership.model');
|
||||
const { deleteFileIfExists } = require('../../../helpers/utils/fileHelper');
|
||||
|
||||
class PartnershipController {
|
||||
async addPartnership(req, res) {
|
||||
try {
|
||||
const image = req.file;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, createPartnershipModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
if (image?.filename) {
|
||||
await deleteFileIfExists(image.filename);
|
||||
}
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const { nama_partner } = validatePayload.data;
|
||||
const result = await partnershipService.createPartnership(nama_partner, image);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Data partnership berhasil ditambahkan', SUCCESS.CREATED);
|
||||
} catch (err) {
|
||||
if (req.file?.filename) {
|
||||
await deleteFileIfExists(req.file.filename);
|
||||
}
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getPartnership(req, res) {
|
||||
try {
|
||||
const result = await partnershipService.getAllPartnerships();
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Data partnership berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async getPartnershipById(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await partnershipService.getPartnershipById(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Data partnership berhasil diambil', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async updatePartnership(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const image = req.file;
|
||||
|
||||
const validatePayload = isValidPayload(req.body, updatePartnershipModel);
|
||||
|
||||
if (validatePayload.err) {
|
||||
if (image?.filename) {
|
||||
await deleteFileIfExists(image.filename);
|
||||
}
|
||||
return response(
|
||||
res,
|
||||
'fail',
|
||||
{ err: validatePayload.err, data: null },
|
||||
'Data tidak valid',
|
||||
ERROR.EXPECTATION_FAILED
|
||||
);
|
||||
}
|
||||
|
||||
const { nama_partner } = validatePayload.data;
|
||||
const result = await partnershipService.updatePartnership(id, nama_partner, image);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Data partnership berhasil diperbarui', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
if (req.file?.filename) {
|
||||
await deleteFileIfExists(req.file.filename);
|
||||
}
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
async deletePartnership(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
const result = await partnershipService.deletePartnership(id);
|
||||
|
||||
if (result.err) {
|
||||
return response(res, 'fail', result);
|
||||
}
|
||||
|
||||
return response(res, 'success', result, 'Data partnership berhasil dihapus', SUCCESS.OK);
|
||||
} catch (err) {
|
||||
return response(res, 'fail', error(new InternalServerError(err.message)), 'Terjadi kesalahan yang tidak terduga', ERROR.INTERNAL_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new PartnershipController();
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
const partnershipController = require('./controllers/partnership.controller');
|
||||
const partnershipService = require('./services/partnership.service');
|
||||
const partnershipRepository = require('./repositories/partnership.repository');
|
||||
|
||||
module.exports = {
|
||||
partnershipController,
|
||||
partnershipService,
|
||||
partnershipRepository
|
||||
};
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
const joi = require('joi');
|
||||
|
||||
const createPartnershipModel = joi.object().keys({
|
||||
nama_partner: joi.string().max(255).required().messages({
|
||||
'string.base': 'Nama partner harus berupa teks.',
|
||||
'string.empty': 'Nama partner tidak boleh kosong.',
|
||||
'string.max': 'Nama partner maksimal {#limit} karakter.',
|
||||
'any.required': 'Nama partner wajib diisi.',
|
||||
}),
|
||||
|
||||
image_path: joi.string().optional().allow('', null).messages({
|
||||
'string.base': 'Path gambar harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
const updatePartnershipModel = joi.object().keys({
|
||||
nama_partner: joi.string().max(255).optional().messages({
|
||||
'string.base': 'Nama partner harus berupa teks.',
|
||||
'string.max': 'Nama partner maksimal {#limit} karakter.',
|
||||
}),
|
||||
|
||||
image_path: joi.string().optional().allow('', null).messages({
|
||||
'string.base': 'Path gambar harus berupa teks.',
|
||||
}),
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
createPartnershipModel,
|
||||
updatePartnershipModel,
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
const prisma = require('../../../helpers/db/db_connection');
|
||||
|
||||
class PartnershipRepository {
|
||||
async create(partnershipData) {
|
||||
return prisma.partnership.create({
|
||||
data: partnershipData,
|
||||
});
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
return prisma.partnership.findMany();
|
||||
}
|
||||
|
||||
async findById(id) {
|
||||
return prisma.partnership.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
}
|
||||
|
||||
async updateById(id, partnershipData) {
|
||||
return prisma.partnership.update({
|
||||
where: { id: parseInt(id) },
|
||||
data: partnershipData,
|
||||
});
|
||||
}
|
||||
|
||||
async deleteById(id) {
|
||||
return prisma.partnership.delete({
|
||||
where: { id: parseInt(id) },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new PartnershipRepository();
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
const partnershipRepository = require('../repositories/partnership.repository');
|
||||
const path = require('path');
|
||||
const { deleteFileIfExists } = require('../../../helpers/utils/fileHelper');
|
||||
const imageUploadHelper = require('../../../helpers/utils/imageUpload.helper');
|
||||
const { data, error } = require('../../../helpers/utils/wrapper');
|
||||
const { NotFoundError } = require('../../../helpers/error');
|
||||
|
||||
class PartnershipService {
|
||||
async createPartnership(nama_partner, imageFile) {
|
||||
try {
|
||||
const imagePath = imageUploadHelper.uploadImage(imageFile);
|
||||
|
||||
const partnershipData = {
|
||||
nama_partner,
|
||||
image_path: imagePath,
|
||||
};
|
||||
|
||||
const result = await partnershipRepository.create(partnershipData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
if (imageFile?.filename) {
|
||||
try {
|
||||
await deleteFileIfExists(imageFile.filename);
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup file:', cleanupErr);
|
||||
}
|
||||
}
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllPartnerships() {
|
||||
try {
|
||||
const partnerships = await partnershipRepository.findAll();
|
||||
return data(partnerships);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async getPartnershipById(id) {
|
||||
try {
|
||||
const partnership = await partnershipRepository.findById(id);
|
||||
|
||||
if (!partnership) {
|
||||
return error(new NotFoundError('Partnership Tidak Ditemukan'));
|
||||
}
|
||||
|
||||
return data(partnership);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async updatePartnership(id, nama_partner, imageFile) {
|
||||
let oldImagePath = null;
|
||||
let newImageUploaded = false;
|
||||
|
||||
try {
|
||||
const checkResult = await this.getPartnershipById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const existingPartnership = checkResult.data;
|
||||
let imagePath = existingPartnership.image_path;
|
||||
|
||||
if (imageFile) {
|
||||
oldImagePath = existingPartnership.image_path;
|
||||
|
||||
imagePath = imageUploadHelper.uploadImage(imageFile);
|
||||
newImageUploaded = true;
|
||||
|
||||
if (oldImagePath) {
|
||||
const oldFileName = path.basename(oldImagePath);
|
||||
await deleteFileIfExists(oldFileName);
|
||||
}
|
||||
}
|
||||
|
||||
const partnershipData = {
|
||||
nama_partner,
|
||||
image_path: imagePath,
|
||||
};
|
||||
|
||||
const result = await partnershipRepository.updateById(id, partnershipData);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
if (newImageUploaded && imageFile?.filename) {
|
||||
try {
|
||||
await deleteFileIfExists(imageFile.filename);
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup new file:', cleanupErr);
|
||||
}
|
||||
}
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
|
||||
async deletePartnership(id) {
|
||||
try {
|
||||
const checkResult = await this.getPartnershipById(id);
|
||||
if (checkResult.err) {
|
||||
return checkResult;
|
||||
}
|
||||
|
||||
const partnership = checkResult.data;
|
||||
|
||||
if (partnership.image_path) {
|
||||
const fileName = path.basename(partnership.image_path);
|
||||
await deleteFileIfExists(fileName);
|
||||
}
|
||||
|
||||
const result = await partnershipRepository.deleteById(id);
|
||||
return data(result);
|
||||
} catch (err) {
|
||||
return error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new PartnershipService();
|
||||
Executable
+91
@@ -0,0 +1,91 @@
|
||||
const express = require('express');
|
||||
const { adminController } = require('../modules/admin');
|
||||
const { verifyJWT } = require('../middleware/verifyJWT');
|
||||
const isAdmin = require('../middleware/isAdmin');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* components:
|
||||
* schemas:
|
||||
* Admin:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* example: 1
|
||||
* nama_depan:
|
||||
* type: string
|
||||
* example: "John"
|
||||
* nama_belakang:
|
||||
* type: string
|
||||
* example: "Doe"
|
||||
* email:
|
||||
* type: string
|
||||
* example: "admin@example.com"
|
||||
* role:
|
||||
* type: string
|
||||
* example: "admin"
|
||||
*/
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /admin-api/add:
|
||||
* post:
|
||||
* summary: Create a new admin account
|
||||
* tags: [Admin]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* nama_depan:
|
||||
* type: string
|
||||
* example: "John"
|
||||
* nama_belakang:
|
||||
* type: string
|
||||
* example: "Doe"
|
||||
* email:
|
||||
* type: string
|
||||
* example: "admin@example.com"
|
||||
* password:
|
||||
* type: string
|
||||
* example: "password123"
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Admin created successfully
|
||||
* 400:
|
||||
* description: Email already exists or unauthorized access
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.post("/add", verifyJWT, isAdmin, adminController.addAdmin);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /admin-api/get:
|
||||
* get:
|
||||
* summary: Retrieve all admin account
|
||||
* tags: [Admin]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Successfully retrieved all admins
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/Admin'
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.get("/get", verifyJWT, adminController.getAdmins);
|
||||
|
||||
module.exports = router;
|
||||
Executable
+95
@@ -0,0 +1,95 @@
|
||||
const express = require('express');
|
||||
const { authController } = require('../modules/auth');
|
||||
const { verifyJWT } = require('../middleware/verifyJWT');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /auth-api/login:
|
||||
* post:
|
||||
* summary: Admin login
|
||||
* tags: [Auth]
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* email:
|
||||
* type: string
|
||||
* example: "admin@example.com"
|
||||
* password:
|
||||
* type: string
|
||||
* example: "password123"
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Login successful
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Login successful"
|
||||
* token:
|
||||
* type: string
|
||||
* example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
|
||||
* 400:
|
||||
* description: Invalid email or password
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.post("/login", authController.login);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /auth-api/me:
|
||||
* get:
|
||||
* summary: Get authenticated admin details
|
||||
* tags: [Auth]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Get admin details successfully
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Get admin successfully"
|
||||
* data:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* example: 1
|
||||
* nama_depan:
|
||||
* type: string
|
||||
* example: "John"
|
||||
* nama_belakang:
|
||||
* type: string
|
||||
* example: "Doe"
|
||||
* email:
|
||||
* type: string
|
||||
* example: "admin@example.com"
|
||||
* role:
|
||||
* type: string
|
||||
* example: "admin"
|
||||
* 401:
|
||||
* description: Authorization header missing or invalid
|
||||
* 403:
|
||||
* description: Invalid or expired token
|
||||
* 404:
|
||||
* description: Admin not found
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.get("/me", verifyJWT, authController.me);
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,432 +0,0 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import prisma from '../lib/prisma';
|
||||
import { protect, AuthenticatedRequest } from '../middleware/auth';
|
||||
import { CustomError } from '../middleware/errorHandler';
|
||||
|
||||
const router = Router();
|
||||
|
||||
const generateToken = (payload: { id: string; email: string; role: string }) => {
|
||||
return jwt.sign(
|
||||
payload,
|
||||
process.env.JWT_SECRET || 'internify_secret_key_2026_dev',
|
||||
{ expiresIn: (process.env.JWT_EXPIRES_IN || '7d') as any }
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/auth/register:
|
||||
* post:
|
||||
* summary: Registrasi akun mahasiswa baru
|
||||
* description: Membuat akun pengguna baru dengan role `STUDENT` beserta profil mahasiswa.
|
||||
* tags: [Auth]
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - email
|
||||
* - password
|
||||
* - namaDepan
|
||||
* - kontak
|
||||
* - jurusan
|
||||
* - universitas
|
||||
* - negara
|
||||
* properties:
|
||||
* email:
|
||||
* type: string
|
||||
* example: student@example.com
|
||||
* password:
|
||||
* type: string
|
||||
* example: Student123!
|
||||
* namaDepan:
|
||||
* type: string
|
||||
* example: Alya
|
||||
* namaBelakang:
|
||||
* type: string
|
||||
* example: Putri
|
||||
* kontak:
|
||||
* type: string
|
||||
* example: 08123456789
|
||||
* jurusan:
|
||||
* type: string
|
||||
* example: Informatika
|
||||
* universitas:
|
||||
* type: string
|
||||
* example: Telkom University
|
||||
* negara:
|
||||
* type: string
|
||||
* example: Indonesia
|
||||
* cvPath:
|
||||
* type: string
|
||||
* example: /uploads/docs/cv.pdf
|
||||
* portofolioPath:
|
||||
* type: string
|
||||
* example: /uploads/docs/portofolio.pdf
|
||||
* motivasi:
|
||||
* type: string
|
||||
* example: Saya tertarik mengikuti program ini.
|
||||
* relevantSkills:
|
||||
* type: string
|
||||
* example: React, Node.js
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Registrasi mahasiswa berhasil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: Registrasi mahasiswa berhasil
|
||||
* data:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: string
|
||||
* example: cku3xq2v0000xk8w7a1b2c3d4
|
||||
* email:
|
||||
* type: string
|
||||
* example: student@example.com
|
||||
* role:
|
||||
* type: string
|
||||
* example: STUDENT
|
||||
* createdAt:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* example: 2026-06-02T10:00:00.000Z
|
||||
* 400:
|
||||
* description: Validasi registrasi gagal
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* field_wajib_kosong:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: Mohon lengkapi semua field wajib yang diperlukan
|
||||
* email_sudah_terdaftar:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: Email sudah terdaftar
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.post('/register', async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const {
|
||||
email,
|
||||
password,
|
||||
namaDepan,
|
||||
namaBelakang,
|
||||
kontak,
|
||||
jurusan,
|
||||
universitas,
|
||||
negara,
|
||||
cvPath,
|
||||
portofolioPath,
|
||||
motivasi,
|
||||
relevantSkills,
|
||||
} = req.body;
|
||||
|
||||
if (!email || !password || !namaDepan || !kontak || !jurusan || !universitas || !negara) {
|
||||
const error: CustomError = new Error('Mohon lengkapi semua field wajib yang diperlukan');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const existingUser = await prisma.user.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
const error: CustomError = new Error('Email sudah terdaftar');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const salt = await bcrypt.genSalt(10);
|
||||
const passwordHash = await bcrypt.hash(password, salt);
|
||||
|
||||
const newUser = await prisma.$transaction(async (tx) => {
|
||||
const user = await tx.user.create({
|
||||
data: {
|
||||
email,
|
||||
passwordHash,
|
||||
role: 'STUDENT',
|
||||
},
|
||||
});
|
||||
|
||||
await tx.mahasiswa.create({
|
||||
data: {
|
||||
idUser: user.id,
|
||||
namaDepan,
|
||||
namaBelakang: namaBelakang || null,
|
||||
kontak,
|
||||
jurusan,
|
||||
universitas,
|
||||
negara,
|
||||
cvPath: cvPath || '',
|
||||
portofolioPath: portofolioPath || '',
|
||||
motivasi: motivasi || '',
|
||||
relevantSkills: relevantSkills || '',
|
||||
},
|
||||
});
|
||||
|
||||
return user;
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Registrasi mahasiswa berhasil',
|
||||
data: {
|
||||
id: newUser.id,
|
||||
email: newUser.email,
|
||||
role: newUser.role,
|
||||
createdAt: newUser.createdAt,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/auth/login:
|
||||
* post:
|
||||
* summary: Login pengguna dan mendapatkan token JWT
|
||||
* description: Melakukan autentikasi pengguna (admin/mahasiswa) dan mengembalikan token akses.
|
||||
* tags: [Auth]
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - email
|
||||
* - password
|
||||
* properties:
|
||||
* email:
|
||||
* type: string
|
||||
* example: admin@internify.com
|
||||
* password:
|
||||
* type: string
|
||||
* example: AdminInternify123!
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Login berhasil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* type: object
|
||||
* properties:
|
||||
* token:
|
||||
* type: string
|
||||
* example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
|
||||
* user:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: string
|
||||
* example: cku3xq2v0000xk8w7a1b2c3d4
|
||||
* email:
|
||||
* type: string
|
||||
* example: admin@internify.com
|
||||
* role:
|
||||
* type: string
|
||||
* example: ADMIN
|
||||
* profile:
|
||||
* type: object
|
||||
* description: Data profil admin atau mahasiswa
|
||||
* 401:
|
||||
* description: Autentikasi gagal
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 401
|
||||
* message: Email atau password salah
|
||||
* 400:
|
||||
* description: Validasi login gagal
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: Mohon masukkan email dan password
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.post('/login', async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
|
||||
if (!email || !password) {
|
||||
const error: CustomError = new Error('Mohon masukkan email dan password');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email },
|
||||
include: {
|
||||
admin: true,
|
||||
mahasiswa: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
const error: CustomError = new Error('Email atau password salah');
|
||||
error.statusCode = 401;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const isMatch = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!isMatch) {
|
||||
const error: CustomError = new Error('Email atau password salah');
|
||||
error.statusCode = 401;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const profile = user.role === 'ADMIN' ? user.admin : user.mahasiswa;
|
||||
|
||||
const token = generateToken({
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
});
|
||||
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
data: {
|
||||
token,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
profile,
|
||||
},
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/auth/me:
|
||||
* get:
|
||||
* summary: Ambil profil pengguna yang sedang login
|
||||
* description: Mengembalikan informasi ringkas user berdasarkan token JWT aktif.
|
||||
* tags: [Auth]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Profil pengguna berhasil diambil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: string
|
||||
* example: cku3xq2v0000xk8w7a1b2c3d4
|
||||
* email:
|
||||
* type: string
|
||||
* example: admin@internify.com
|
||||
* role:
|
||||
* type: string
|
||||
* example: ADMIN
|
||||
* nama_depan:
|
||||
* type: string
|
||||
* example: Super
|
||||
* 401:
|
||||
* description: Token tidak valid atau tidak tersedia
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* token_missing:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 401
|
||||
* message: Not authorized to access this route, token is missing
|
||||
* token_invalid:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 401
|
||||
* message: Not authorized to access this route, token is invalid or expired
|
||||
* user_token_tidak_ada:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 401
|
||||
* message: User belonging to this token no longer exists
|
||||
* 404:
|
||||
* description: Pengguna tidak ditemukan
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 404
|
||||
* message: User not found
|
||||
*/
|
||||
router.get('/me', protect, async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const userId = req.user?.id;
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: {
|
||||
admin: true,
|
||||
mahasiswa: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
const error: CustomError = new Error('User not found');
|
||||
error.statusCode = 404;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const profile = user.role === 'ADMIN' ? user.admin : user.mahasiswa;
|
||||
const namaDepan = profile?.namaDepan || '';
|
||||
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
data: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
nama_depan: namaDepan
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
Executable
+336
@@ -0,0 +1,336 @@
|
||||
const express = require('express');
|
||||
const { batchController } = require('../modules/batch');
|
||||
const { verifyJWT } = require('../middleware/verifyJWT');
|
||||
const isAdmin = require('../middleware/isAdmin');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* components:
|
||||
* schemas:
|
||||
* Batch:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* example: 1
|
||||
* batch_number:
|
||||
* type: integer
|
||||
* example: 1
|
||||
* is_active:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* created_at:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* example: "2025-01-01T00:00:00.000Z"
|
||||
* updated_at:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* example: "2025-01-01T00:00:00.000Z"
|
||||
* BatchCreate:
|
||||
* type: object
|
||||
* properties:
|
||||
* batch_number:
|
||||
* type: integer
|
||||
* description: Opsional - Nomor batch akan di-generate otomatis (batch terakhir + 1) jika tidak disediakan
|
||||
* example: 1
|
||||
* is_active:
|
||||
* type: boolean
|
||||
* description: Opsional - Batch baru akan otomatis aktif dan menonaktifkan batch sebelumnya
|
||||
* example: true
|
||||
* BatchUpdate:
|
||||
* type: object
|
||||
* properties:
|
||||
* batch_number:
|
||||
* type: integer
|
||||
* example: 2
|
||||
* is_active:
|
||||
* type: boolean
|
||||
* example: true
|
||||
*/
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* tags:
|
||||
* name: Batch
|
||||
* description: API untuk mengelola batch magang
|
||||
*/
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /batch-api/add:
|
||||
* post:
|
||||
* summary: Membuat batch baru (auto-increment + auto-deactivate batch sebelumnya)
|
||||
* description: Membuat batch baru dengan nomor batch otomatis (batch terakhir + 1), mengaktifkan batch baru, dan menonaktifkan semua batch sebelumnya
|
||||
* tags: [Batch]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* requestBody:
|
||||
* required: false
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/BatchCreate'
|
||||
* examples:
|
||||
* auto:
|
||||
* summary: Auto-generate batch (recommended)
|
||||
* value: {}
|
||||
* manual:
|
||||
* summary: Manual batch number (optional)
|
||||
* value:
|
||||
* batch_number: 5
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Batch berhasil dibuat
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Batch berhasil dibuat"
|
||||
* data:
|
||||
* $ref: '#/components/schemas/Batch'
|
||||
* examples:
|
||||
* success:
|
||||
* value:
|
||||
* success: true
|
||||
* message: "Batch berhasil dibuat"
|
||||
* data:
|
||||
* id: 1
|
||||
* batch_number: 6
|
||||
* is_active: true
|
||||
* created_at: "2025-11-17T00:00:00.000Z"
|
||||
* updated_at: "2025-11-17T00:00:00.000Z"
|
||||
* 400:
|
||||
* description: Data tidak valid
|
||||
* 401:
|
||||
* description: Tidak terautentikasi
|
||||
* 403:
|
||||
* description: Tidak memiliki akses (bukan admin)
|
||||
* 409:
|
||||
* description: Nomor batch sudah digunakan (jika manual)
|
||||
*/
|
||||
router.post('/add', verifyJWT, isAdmin, batchController.createBatch);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /batch-api/:
|
||||
* get:
|
||||
* summary: Mengambil semua batch
|
||||
* description: Mendapatkan daftar semua batch yang tersedia, diurutkan berdasarkan nomor batch (descending)
|
||||
* tags: [Batch]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Berhasil mengambil semua batch
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Berhasil mengambil semua batch"
|
||||
* data:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/Batch'
|
||||
* examples:
|
||||
* success:
|
||||
* value:
|
||||
* success: true
|
||||
* message: "Berhasil mengambil semua batch"
|
||||
* data:
|
||||
* - id: 3
|
||||
* batch_number: 3
|
||||
* is_active: true
|
||||
* created_at: "2025-11-17T00:00:00.000Z"
|
||||
* updated_at: "2025-11-17T00:00:00.000Z"
|
||||
* - id: 2
|
||||
* batch_number: 2
|
||||
* is_active: false
|
||||
* created_at: "2025-11-16T00:00:00.000Z"
|
||||
* updated_at: "2025-11-17T00:00:00.000Z"
|
||||
* - id: 1
|
||||
* batch_number: 1
|
||||
* is_active: false
|
||||
* created_at: "2025-11-15T00:00:00.000Z"
|
||||
* updated_at: "2025-11-16T00:00:00.000Z"
|
||||
* 401:
|
||||
* description: Tidak terautentikasi
|
||||
* 403:
|
||||
* description: Tidak memiliki akses (bukan admin)
|
||||
*/
|
||||
router.get('/', verifyJWT, isAdmin, batchController.getAllBatches);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /batch-api/{id}:
|
||||
* put:
|
||||
* summary: Memperbarui batch
|
||||
* description: Memperbarui data batch. Jika is_active diset true, semua batch lain akan otomatis dinonaktifkan
|
||||
* tags: [Batch]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID batch
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: '#/components/schemas/BatchUpdate'
|
||||
* examples:
|
||||
* activate:
|
||||
* summary: Aktifkan batch
|
||||
* value:
|
||||
* is_active: true
|
||||
* deactivate:
|
||||
* summary: Nonaktifkan batch
|
||||
* value:
|
||||
* is_active: false
|
||||
* update_number:
|
||||
* summary: Update nomor batch
|
||||
* value:
|
||||
* batch_number: 3
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Batch berhasil diperbarui
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Batch berhasil diperbarui"
|
||||
* data:
|
||||
* $ref: '#/components/schemas/Batch'
|
||||
* 400:
|
||||
* description: Data tidak valid
|
||||
* 401:
|
||||
* description: Tidak terautentikasi
|
||||
* 403:
|
||||
* description: Tidak memiliki akses (bukan admin)
|
||||
* 404:
|
||||
* description: Batch tidak ditemukan
|
||||
* 409:
|
||||
* description: Nomor batch sudah digunakan
|
||||
*/
|
||||
router.put('/:id', verifyJWT, isAdmin, batchController.updateBatch);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /batch-api/{id}:
|
||||
* delete:
|
||||
* summary: Menghapus batch
|
||||
* tags: [Batch]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: ID batch
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Batch berhasil dihapus
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Batch berhasil dihapus"
|
||||
* data:
|
||||
* $ref: '#/components/schemas/Batch'
|
||||
* 401:
|
||||
* description: Tidak terautentikasi
|
||||
* 403:
|
||||
* description: Tidak memiliki akses (bukan admin)
|
||||
* 404:
|
||||
* description: Batch tidak ditemukan
|
||||
*/
|
||||
router.delete('/:id', verifyJWT, isAdmin, batchController.deleteBatch);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /batch-api/switch/{batch_number}:
|
||||
* patch:
|
||||
* summary: Mengaktifkan batch yang sudah ada (switch batch)
|
||||
* description: Menonaktifkan semua batch dan mengaktifkan batch dengan nomor yang ditentukan
|
||||
* tags: [Batch]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: batch_number
|
||||
* schema:
|
||||
* type: integer
|
||||
* required: true
|
||||
* description: Nomor batch yang akan diaktifkan
|
||||
* example: 3
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Batch berhasil diaktifkan
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Batch berhasil diaktifkan"
|
||||
* data:
|
||||
* $ref: '#/components/schemas/Batch'
|
||||
* examples:
|
||||
* success:
|
||||
* value:
|
||||
* success: true
|
||||
* message: "Batch berhasil diaktifkan"
|
||||
* data:
|
||||
* id: 3
|
||||
* batch_number: 3
|
||||
* is_active: true
|
||||
* created_at: "2025-11-17T00:00:00.000Z"
|
||||
* updated_at: "2025-11-17T00:00:00.000Z"
|
||||
* 400:
|
||||
* description: Nomor batch tidak valid
|
||||
* 401:
|
||||
* description: Tidak terautentikasi
|
||||
* 403:
|
||||
* description: Tidak memiliki akses (bukan admin)
|
||||
* 404:
|
||||
* description: Batch tidak ditemukan
|
||||
*/
|
||||
router.patch('/switch/:batch_number', verifyJWT, isAdmin, batchController.switchBatch);
|
||||
|
||||
module.exports = router;
|
||||
Executable
+254
@@ -0,0 +1,254 @@
|
||||
const express = require('express');
|
||||
const { faqController } = require('../modules/faq');
|
||||
const { verifyJWT } = require('../middleware/verifyJWT');
|
||||
const isAdmin = require('../middleware/isAdmin');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* components:
|
||||
* schemas:
|
||||
* FAQ:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* example: 1
|
||||
* pertanyaan:
|
||||
* type: string
|
||||
* example: "Bagaimana cara mendaftar magang?"
|
||||
* jawaban:
|
||||
* type: string
|
||||
* example: "Anda dapat mendaftar melalui halaman lowongan magang yang tersedia."
|
||||
* created_at:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* example: "2025-11-10T10:00:00Z"
|
||||
*/
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /faq-api/get:
|
||||
* get:
|
||||
* summary: Get all FAQ
|
||||
* tags: [FAQ]
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Successfully retrieved all FAQ
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/FAQ'
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Success"
|
||||
* code:
|
||||
* type: integer
|
||||
* example: 200
|
||||
* 404:
|
||||
* description: No FAQ found
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.get('/get', faqController.getAllFaq);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /faq-api/get/{id}:
|
||||
* get:
|
||||
* summary: Get FAQ by ID
|
||||
* tags: [FAQ]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: The FAQ ID
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Successfully retrieved FAQ
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* $ref: '#/components/schemas/FAQ'
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Success"
|
||||
* code:
|
||||
* type: integer
|
||||
* example: 200
|
||||
* 404:
|
||||
* description: FAQ not found
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.get('/get/:id', faqController.getFaqById);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /faq-api/add:
|
||||
* post:
|
||||
* summary: Create a new FAQ
|
||||
* tags: [FAQ]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - pertanyaan
|
||||
* - jawaban
|
||||
* properties:
|
||||
* pertanyaan:
|
||||
* type: string
|
||||
* example: "Bagaimana cara mendaftar magang?"
|
||||
* jawaban:
|
||||
* type: string
|
||||
* example: "Anda dapat mendaftar melalui halaman lowongan magang yang tersedia."
|
||||
* responses:
|
||||
* 200:
|
||||
* description: FAQ created successfully
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* $ref: '#/components/schemas/FAQ'
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Success"
|
||||
* code:
|
||||
* type: integer
|
||||
* example: 200
|
||||
* 417:
|
||||
* description: Validation error
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.post('/add', verifyJWT, isAdmin, faqController.addFaq);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /faq-api/update/{id}:
|
||||
* patch:
|
||||
* summary: Update an existing FAQ
|
||||
* tags: [FAQ]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: The FAQ ID
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* pertanyaan:
|
||||
* type: string
|
||||
* example: "Bagaimana cara mendaftar magang?"
|
||||
* jawaban:
|
||||
* type: string
|
||||
* example: "Anda dapat mendaftar melalui halaman lowongan magang yang tersedia."
|
||||
* responses:
|
||||
* 200:
|
||||
* description: FAQ updated successfully
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* $ref: '#/components/schemas/FAQ'
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Success"
|
||||
* code:
|
||||
* type: integer
|
||||
* example: 200
|
||||
* 404:
|
||||
* description: FAQ not found
|
||||
* 417:
|
||||
* description: Validation error
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.patch('/update/:id', verifyJWT, isAdmin, faqController.updateFaq);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /faq-api/delete/{id}:
|
||||
* delete:
|
||||
* summary: Delete an FAQ
|
||||
* tags: [FAQ]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: The FAQ ID
|
||||
* responses:
|
||||
* 200:
|
||||
* description: FAQ deleted successfully
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: "FAQ berhasil dihapus"
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Success"
|
||||
* code:
|
||||
* type: integer
|
||||
* example: 200
|
||||
* 404:
|
||||
* description: FAQ not found
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.delete('/delete/:id', verifyJWT, isAdmin, faqController.deleteFaq);
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,352 +0,0 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { protect, restrictTo, AuthenticatedRequest } from '../middleware/auth';
|
||||
import prisma from '../lib/prisma';
|
||||
import { CustomError } from '../middleware/errorHandler';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Map data faq dari DB ke format frontend
|
||||
function mapToFrontend(faq: any) {
|
||||
return {
|
||||
id: faq.id,
|
||||
pertanyaan: faq.pertanyaan,
|
||||
jawaban: faq.jawaban,
|
||||
created_at: faq.createdAt
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/faq-api/get:
|
||||
* get:
|
||||
* summary: Ambil seluruh FAQ
|
||||
* description: Mengembalikan daftar semua pertanyaan dan jawaban FAQ.
|
||||
* tags: [FAQ]
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Data FAQ berhasil diambil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.get('/get', async (_req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const faqs = await prisma.faq.findMany({
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
data: faqs.map(mapToFrontend)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/faq-api/get/{id}:
|
||||
* get:
|
||||
* summary: Ambil detail FAQ berdasarkan ID
|
||||
* description: Mengembalikan detail satu item FAQ.
|
||||
* tags: [FAQ]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: ID FAQ
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Detail FAQ berhasil diambil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* type: object
|
||||
* 404:
|
||||
* description: FAQ tidak ditemukan
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 404
|
||||
* message: FAQ tidak ditemukan
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.get('/get/:id', async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const faq = await prisma.faq.findUnique({
|
||||
where: { id: parseInt(id, 10) }
|
||||
});
|
||||
|
||||
if (!faq) {
|
||||
const error: CustomError = new Error('FAQ tidak ditemukan');
|
||||
error.statusCode = 404;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
data: mapToFrontend(faq)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/faq-api/add:
|
||||
* post:
|
||||
* summary: Tambah FAQ baru
|
||||
* description: Menambahkan item FAQ baru. Hanya dapat diakses oleh admin.
|
||||
* tags: [FAQ]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - pertanyaan
|
||||
* - jawaban
|
||||
* properties:
|
||||
* pertanyaan:
|
||||
* type: string
|
||||
* example: Apakah magang ini bisa remote?
|
||||
* jawaban:
|
||||
* type: string
|
||||
* example: Ya, beberapa posisi mendukung skema remote.
|
||||
* responses:
|
||||
* 201:
|
||||
* description: FAQ berhasil ditambahkan
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: FAQ berhasil ditambahkan
|
||||
* 400:
|
||||
* description: Validasi FAQ gagal
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: Pertanyaan dan jawaban harus diisi
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 403:
|
||||
* $ref: '#/components/responses/ForbiddenError'
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.post('/add', protect, restrictTo('ADMIN'), async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { pertanyaan, jawaban } = req.body;
|
||||
|
||||
if (!pertanyaan || !jawaban) {
|
||||
const error: CustomError = new Error('Pertanyaan dan jawaban harus diisi');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const faq = await prisma.faq.create({
|
||||
data: {
|
||||
pertanyaan,
|
||||
jawaban
|
||||
}
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
status: true,
|
||||
message: 'FAQ berhasil ditambahkan',
|
||||
data: mapToFrontend(faq)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/faq-api/update/{id}:
|
||||
* patch:
|
||||
* summary: Perbarui FAQ
|
||||
* description: Memperbarui item FAQ berdasarkan ID. Hanya dapat diakses oleh admin.
|
||||
* tags: [FAQ]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: ID FAQ
|
||||
* requestBody:
|
||||
* required: false
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* pertanyaan:
|
||||
* type: string
|
||||
* jawaban:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: FAQ berhasil diperbarui
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: FAQ berhasil diupdate
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 403:
|
||||
* $ref: '#/components/responses/ForbiddenError'
|
||||
* 404:
|
||||
* description: FAQ tidak ditemukan
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 404
|
||||
* message: FAQ tidak ditemukan
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.patch('/update/:id', protect, restrictTo('ADMIN'), async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { pertanyaan, jawaban } = req.body;
|
||||
|
||||
const existing = await prisma.faq.findUnique({
|
||||
where: { id: parseInt(id, 10) }
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
const error: CustomError = new Error('FAQ tidak ditemukan');
|
||||
error.statusCode = 404;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const updated = await prisma.faq.update({
|
||||
where: { id: parseInt(id, 10) },
|
||||
data: {
|
||||
pertanyaan: pertanyaan ?? existing.pertanyaan,
|
||||
jawaban: jawaban ?? existing.jawaban
|
||||
}
|
||||
});
|
||||
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
message: 'FAQ berhasil diupdate',
|
||||
data: mapToFrontend(updated)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/faq-api/delete/{id}:
|
||||
* delete:
|
||||
* summary: Hapus FAQ
|
||||
* description: Menghapus item FAQ berdasarkan ID. Hanya dapat diakses oleh admin.
|
||||
* tags: [FAQ]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: ID FAQ
|
||||
* responses:
|
||||
* 200:
|
||||
* description: FAQ berhasil dihapus
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: true
|
||||
* message: FAQ berhasil dihapus
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 403:
|
||||
* $ref: '#/components/responses/ForbiddenError'
|
||||
* 404:
|
||||
* description: FAQ tidak ditemukan
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 404
|
||||
* message: FAQ tidak ditemukan
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.delete('/delete/:id', protect, restrictTo('ADMIN'), async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const existing = await prisma.faq.findUnique({
|
||||
where: { id: parseInt(id, 10) }
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
const error: CustomError = new Error('FAQ tidak ditemukan');
|
||||
error.statusCode = 404;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
await prisma.faq.delete({
|
||||
where: { id: parseInt(id, 10) }
|
||||
});
|
||||
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
message: 'FAQ berhasil dihapus'
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
Executable
+254
@@ -0,0 +1,254 @@
|
||||
const express = require('express');
|
||||
const { feedbackController } = require('../modules/feedback');
|
||||
const { verifyJWT } = require('../middleware/verifyJWT');
|
||||
const isAdmin = require('../middleware/isAdmin');
|
||||
const multer = require('../middleware/multer');
|
||||
const { multerErrorHandler } = require('../middleware/multer');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* components:
|
||||
* schemas:
|
||||
* Feedback:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* example: 1
|
||||
* nama:
|
||||
* type: string
|
||||
* example: "John Doe"
|
||||
* universitas:
|
||||
* type: string
|
||||
* example: "Universitas Indonesia"
|
||||
* pesan:
|
||||
* type: string
|
||||
* example: "Great internship experience!"
|
||||
* batch:
|
||||
* type: integer
|
||||
* example: 3
|
||||
* posisi:
|
||||
* type: string
|
||||
* example: "Back End Developer"
|
||||
* tahun:
|
||||
* type: integer
|
||||
* example: 2025
|
||||
* image_path:
|
||||
* type: string
|
||||
* example: "/uploads/feedback_image.png"
|
||||
* created_at:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* example: "2025-01-15T10:00:00Z"
|
||||
*/
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /feedback-api/add:
|
||||
* post:
|
||||
* summary: Add a new feedback
|
||||
* tags: [Feedback]
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* multipart/form-data:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* nama:
|
||||
* type: string
|
||||
* description: Name of the person giving feedback
|
||||
* example: "John Doe"
|
||||
* universitas:
|
||||
* type: string
|
||||
* description: University name
|
||||
* example: "Universitas Indonesia"
|
||||
* pesan:
|
||||
* type: string
|
||||
* description: Feedback message
|
||||
* example: "Great experience during the internship"
|
||||
* batch:
|
||||
* type: integer
|
||||
* description: Batch number
|
||||
* example: 3
|
||||
* posisi:
|
||||
* type: string
|
||||
* description: Internship position
|
||||
* example: "Back End Developer"
|
||||
* tahun:
|
||||
* type: integer
|
||||
* description: Year
|
||||
* example: 2025
|
||||
* image:
|
||||
* type: string
|
||||
* format: binary
|
||||
* description: Optional feedback image
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Feedback created successfully
|
||||
* 413:
|
||||
* description: File size too large (max 5MB)
|
||||
* 417:
|
||||
* description: Validation error
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.post('/add', multer.single('image'), multerErrorHandler, feedbackController.addFeedback);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /feedback-api/get:
|
||||
* get:
|
||||
* summary: Get all feedback with optional filters
|
||||
* tags: [Feedback]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: batch
|
||||
* schema:
|
||||
* type: integer
|
||||
* minimum: 1
|
||||
* description: Filter feedback by batch number
|
||||
* example: 3
|
||||
* - in: query
|
||||
* name: tahun
|
||||
* schema:
|
||||
* type: integer
|
||||
* minimum: 2000
|
||||
* maximum: 2100
|
||||
* description: Filter feedback by year
|
||||
* example: 2025
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Successfully retrieved feedback
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Berhasil mengambil semua feedback"
|
||||
* data:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/Feedback'
|
||||
* 417:
|
||||
* description: Query parameter validation error
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.get('/get', feedbackController.getAllFeedback);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /feedback-api/get/{id}:
|
||||
* get:
|
||||
* summary: Get feedback by ID
|
||||
* tags: [Feedback]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Feedback ID
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Successfully retrieved feedback
|
||||
* 404:
|
||||
* description: Feedback not found
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.get('/get/:id', verifyJWT, isAdmin, feedbackController.getFeedbackById);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /feedback-api/update/{id}:
|
||||
* patch:
|
||||
* summary: Update feedback by ID
|
||||
* tags: [Feedback]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Feedback ID
|
||||
* requestBody:
|
||||
* required: false
|
||||
* content:
|
||||
* multipart/form-data:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* nama:
|
||||
* type: string
|
||||
* example: "John Doe"
|
||||
* universitas:
|
||||
* type: string
|
||||
* example: "Universitas Indonesia"
|
||||
* pesan:
|
||||
* type: string
|
||||
* example: "Updated feedback message"
|
||||
* batch:
|
||||
* type: integer
|
||||
* example: 3
|
||||
* posisi:
|
||||
* type: string
|
||||
* example: "Back End Developer"
|
||||
* tahun:
|
||||
* type: integer
|
||||
* example: 2025
|
||||
* image:
|
||||
* type: string
|
||||
* format: binary
|
||||
* description: Optional new image
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Feedback updated successfully
|
||||
* 404:
|
||||
* description: Feedback not found
|
||||
* 413:
|
||||
* description: File size too large (max 5MB)
|
||||
* 417:
|
||||
* description: Validation error
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.patch('/update/:id', verifyJWT, isAdmin, multer.single('image'), multerErrorHandler, feedbackController.updateFeedback);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /feedback-api/delete/{id}:
|
||||
* delete:
|
||||
* summary: Delete feedback by ID
|
||||
* tags: [Feedback]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: Feedback ID
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Feedback deleted successfully
|
||||
* 404:
|
||||
* description: Feedback not found
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.delete('/delete/:id', verifyJWT, isAdmin, feedbackController.deleteFeedback);
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,460 +0,0 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { protect, restrictTo, AuthenticatedRequest } from '../middleware/auth';
|
||||
import prisma from '../lib/prisma';
|
||||
import { upload } from '../middleware/upload';
|
||||
import { CustomError } from '../middleware/errorHandler';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Map data feedback dari DB ke format frontend
|
||||
function mapToFrontend(feedback: any) {
|
||||
return {
|
||||
id: feedback.id,
|
||||
nama: feedback.nama,
|
||||
universitas: feedback.universitas,
|
||||
posisi: feedback.posisi,
|
||||
batch: feedback.batch,
|
||||
tahun: feedback.tahun,
|
||||
pesan: feedback.pesan,
|
||||
image_path: feedback.imagePath,
|
||||
createdAt: feedback.createdAt
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/feedback-api/get:
|
||||
* get:
|
||||
* summary: Ambil semua feedback
|
||||
* description: Mengembalikan daftar seluruh feedback/testimoni peserta.
|
||||
* tags: [Feedback]
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Data feedback berhasil diambil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.get('/get', async (_req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const feedbacks = await prisma.feedback.findMany({
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
data: feedbacks.map(mapToFrontend)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/feedback-api/get/{id}:
|
||||
* get:
|
||||
* summary: Ambil detail feedback berdasarkan ID
|
||||
* description: Mengembalikan detail satu feedback/testimoni.
|
||||
* tags: [Feedback]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: ID feedback
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Detail feedback berhasil diambil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* type: object
|
||||
* 404:
|
||||
* description: Feedback tidak ditemukan
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 404
|
||||
* message: Feedback tidak ditemukan
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.get('/get/:id', async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const feedback = await prisma.feedback.findUnique({
|
||||
where: { id: parseInt(id, 10) }
|
||||
});
|
||||
|
||||
if (!feedback) {
|
||||
const error: CustomError = new Error('Feedback tidak ditemukan');
|
||||
error.statusCode = 404;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
data: mapToFrontend(feedback)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/feedback-api/add:
|
||||
* post:
|
||||
* summary: Tambah feedback baru
|
||||
* description: Menambahkan feedback/testimoni baru. Dapat diakses user yang sudah login.
|
||||
* tags: [Feedback]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* multipart/form-data:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - nama
|
||||
* - universitas
|
||||
* - posisi
|
||||
* - batch
|
||||
* - tahun
|
||||
* - pesan
|
||||
* properties:
|
||||
* nama:
|
||||
* type: string
|
||||
* example: Alya Putri
|
||||
* universitas:
|
||||
* type: string
|
||||
* example: Telkom University
|
||||
* posisi:
|
||||
* type: string
|
||||
* example: Frontend Developer Intern
|
||||
* batch:
|
||||
* type: integer
|
||||
* example: 3
|
||||
* tahun:
|
||||
* type: integer
|
||||
* example: 2026
|
||||
* pesan:
|
||||
* type: string
|
||||
* example: Pengalaman magang sangat membantu perkembangan skill saya.
|
||||
* image:
|
||||
* type: string
|
||||
* format: binary
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Feedback berhasil ditambahkan
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: Feedback berhasil ditambahkan
|
||||
* 400:
|
||||
* description: Validasi input feedback gagal
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* field_wajib:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: Mohon lengkapi semua field yang wajib diisi
|
||||
* angka_tidak_valid:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: Batch dan tahun harus berupa angka
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 500:
|
||||
* description: Terjadi kesalahan server (termasuk validasi file upload)
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* file_bukan_gambar:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 500
|
||||
* message: File upload harus berupa gambar!
|
||||
* internal:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 500
|
||||
* message: Internal Server Error
|
||||
*/
|
||||
router.post('/add', protect, upload.single('image'), async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { nama, universitas, posisi, batch, tahun, pesan } = req.body;
|
||||
|
||||
if (!nama || !universitas || !posisi || !batch || !tahun || !pesan) {
|
||||
const error: CustomError = new Error('Mohon lengkapi semua field yang wajib diisi');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const parsedBatch = parseInt(batch, 10);
|
||||
const parsedTahun = parseInt(tahun, 10);
|
||||
|
||||
if (isNaN(parsedBatch) || isNaN(parsedTahun)) {
|
||||
const error: CustomError = new Error('Batch dan tahun harus berupa angka');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const imagePath = req.file ? `/uploads/images/${req.file.filename}` : '';
|
||||
|
||||
const feedback = await prisma.feedback.create({
|
||||
data: {
|
||||
nama,
|
||||
universitas,
|
||||
posisi,
|
||||
batch: parsedBatch,
|
||||
tahun: parsedTahun,
|
||||
pesan,
|
||||
imagePath
|
||||
}
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
status: true,
|
||||
message: 'Feedback berhasil ditambahkan',
|
||||
data: mapToFrontend(feedback)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/feedback-api/update/{id}:
|
||||
* patch:
|
||||
* summary: Perbarui feedback
|
||||
* description: Memperbarui data feedback berdasarkan ID. Dapat diakses user yang sudah login.
|
||||
* tags: [Feedback]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: ID feedback
|
||||
* requestBody:
|
||||
* required: false
|
||||
* content:
|
||||
* multipart/form-data:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* nama:
|
||||
* type: string
|
||||
* universitas:
|
||||
* type: string
|
||||
* posisi:
|
||||
* type: string
|
||||
* batch:
|
||||
* type: integer
|
||||
* tahun:
|
||||
* type: integer
|
||||
* pesan:
|
||||
* type: string
|
||||
* image:
|
||||
* type: string
|
||||
* format: binary
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Feedback berhasil diperbarui
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: Feedback berhasil diupdate
|
||||
* 400:
|
||||
* description: Validasi data feedback gagal
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: Batch dan tahun harus berupa angka
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 404:
|
||||
* description: Feedback tidak ditemukan
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 404
|
||||
* message: Feedback tidak ditemukan
|
||||
* 500:
|
||||
* description: Terjadi kesalahan server (termasuk validasi file upload)
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* file_bukan_gambar:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 500
|
||||
* message: File upload harus berupa gambar!
|
||||
* internal:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 500
|
||||
* message: Internal Server Error
|
||||
*/
|
||||
router.patch('/update/:id', protect, upload.single('image'), async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { nama, universitas, posisi, batch, tahun, pesan } = req.body;
|
||||
|
||||
const existing = await prisma.feedback.findUnique({
|
||||
where: { id: parseInt(id, 10) }
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
const error: CustomError = new Error('Feedback tidak ditemukan');
|
||||
error.statusCode = 404;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
let imagePath = existing.imagePath;
|
||||
if (req.file) {
|
||||
imagePath = `/uploads/images/${req.file.filename}`;
|
||||
}
|
||||
|
||||
const parsedBatch = batch ? parseInt(batch, 10) : undefined;
|
||||
const parsedTahun = tahun ? parseInt(tahun, 10) : undefined;
|
||||
|
||||
if ((batch && isNaN(parsedBatch as number)) || (tahun && isNaN(parsedTahun as number))) {
|
||||
const error: CustomError = new Error('Batch dan tahun harus berupa angka');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const updated = await prisma.feedback.update({
|
||||
where: { id: parseInt(id, 10) },
|
||||
data: {
|
||||
nama: nama ?? existing.nama,
|
||||
universitas: universitas ?? existing.universitas,
|
||||
posisi: posisi ?? existing.posisi,
|
||||
batch: parsedBatch ?? existing.batch,
|
||||
tahun: parsedTahun ?? existing.tahun,
|
||||
pesan: pesan ?? existing.pesan,
|
||||
imagePath
|
||||
}
|
||||
});
|
||||
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
message: 'Feedback berhasil diupdate',
|
||||
data: mapToFrontend(updated)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/feedback-api/delete/{id}:
|
||||
* delete:
|
||||
* summary: Hapus feedback
|
||||
* description: Menghapus data feedback berdasarkan ID. Hanya dapat diakses oleh admin.
|
||||
* tags: [Feedback]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: ID feedback
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Feedback berhasil dihapus
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: true
|
||||
* message: Feedback berhasil dihapus
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 403:
|
||||
* $ref: '#/components/responses/ForbiddenError'
|
||||
* 404:
|
||||
* description: Feedback tidak ditemukan
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 404
|
||||
* message: Feedback tidak ditemukan
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.delete('/delete/:id', protect, restrictTo('ADMIN'), async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const existing = await prisma.feedback.findUnique({
|
||||
where: { id: parseInt(id, 10) }
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
const error: CustomError = new Error('Feedback tidak ditemukan');
|
||||
error.statusCode = 404;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
await prisma.feedback.delete({
|
||||
where: { id: parseInt(id, 10) }
|
||||
});
|
||||
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
message: 'Feedback berhasil dihapus'
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
Executable
+286
@@ -0,0 +1,286 @@
|
||||
const express = require('express');
|
||||
const { hasilResearchController } = require('../modules/hasilResearch');
|
||||
const { verifyJWT } = require('../middleware/verifyJWT');
|
||||
const isAdmin = require('../middleware/isAdmin');
|
||||
const multer = require('../middleware/multer');
|
||||
const { multerErrorHandler } = require('../middleware/multer');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* components:
|
||||
* schemas:
|
||||
* HasilResearch:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* example: 1
|
||||
* image_path:
|
||||
* type: string
|
||||
* example: "/uploads/research_image.png"
|
||||
* nama_project:
|
||||
* type: string
|
||||
* example: "Machine Learning for Healthcare"
|
||||
* deskripsi:
|
||||
* type: string
|
||||
* example: "A project exploring machine learning techniques in healthcare."
|
||||
* link_project:
|
||||
* type: string
|
||||
* example: "https://youtube.com"
|
||||
*/
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /hasil-research-api/add:
|
||||
* post:
|
||||
* summary: Add a HUMIC Internship research (product)
|
||||
* tags: [Hasil Research]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* multipart/form-data:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* nama_project:
|
||||
* type: string
|
||||
* description: Name of the research project
|
||||
* example: "Machine Learning for Healthcare"
|
||||
* deskripsi:
|
||||
* type: string
|
||||
* description: Description of the research project
|
||||
* example: "A project exploring machine learning techniques in healthcare."
|
||||
* link_project:
|
||||
* type: string
|
||||
* description: link to the project
|
||||
* example: "https://youtube.com"
|
||||
* image:
|
||||
* type: string
|
||||
* format: binary
|
||||
* description: Image of the research project
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Research result added successfully
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Data hasil research berhasil ditambahkan"
|
||||
* data:
|
||||
* type: object
|
||||
* properties:
|
||||
* nama_project:
|
||||
* type: string
|
||||
* example: "Machine Learning for Healthcare"
|
||||
* deskripsi:
|
||||
* type: string
|
||||
* example: "A project exploring machine learning techniques in healthcare."
|
||||
* image_path:
|
||||
* type: string
|
||||
* example: "/uploads/research_image.png"
|
||||
* 413:
|
||||
* description: File size too large (max 5MB)
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.post('/add', verifyJWT, isAdmin, multer.single('image'), multerErrorHandler, hasilResearchController.addHasilResearch);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /hasil-research-api/get:
|
||||
* get:
|
||||
* summary: Retrieve all research (product) results
|
||||
* tags: [Hasil Research]
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Successfully retrieved all research results
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Research data was successfully collected"
|
||||
* data:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: '#/components/schemas/HasilResearch'
|
||||
* 404:
|
||||
* description: No research data found
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.get('/get', hasilResearchController.getHasilResearch);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /hasil-research-api/get/{id}:
|
||||
* get:
|
||||
* summary: Get research result by ID
|
||||
* tags: [Hasil Research]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: The ID of the research data to retrieve
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Research data was successfully collected
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: Research data was successfully collected
|
||||
* data:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* example: 1
|
||||
* image_path:
|
||||
* type: string
|
||||
* example: "/uploads/1629882719283.png"
|
||||
* nama_project:
|
||||
* type: string
|
||||
* example: "Smart Farming IoT"
|
||||
* deskripsi:
|
||||
* type: string
|
||||
* example: "A smart farming system using IoT sensors"
|
||||
* link_project:
|
||||
* type: string
|
||||
* example: "https://github.com/user/smart-farming"
|
||||
* 404:
|
||||
* description: Hasil research not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: Hasil research not found
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.get('/get/:id', hasilResearchController.getHasilResearchById);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /hasil-research-api/update/{id}:
|
||||
* patch:
|
||||
* summary: Update an existing hasil research entry
|
||||
* tags: [Hasil Research]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: The ID of the hasil research to update
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* multipart/form-data:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* nama_project:
|
||||
* type: string
|
||||
* example: "Sistem Deteksi Kualitas Udara"
|
||||
* deskripsi:
|
||||
* type: string
|
||||
* example: "Aplikasi yang memantau dan menilai kualitas udara secara real-time"
|
||||
* link_project:
|
||||
* type: string
|
||||
* example: "https://github.com/username/project"
|
||||
* image:
|
||||
* type: string
|
||||
* format: binary
|
||||
* description: Optional. Upload a new image to replace the old one.
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Hasil research successfully updated
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Hasil research successfully updated"
|
||||
* data:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: integer
|
||||
* example: 1
|
||||
* nama_project:
|
||||
* type: string
|
||||
* deskripsi:
|
||||
* type: string
|
||||
* link_project:
|
||||
* type: string
|
||||
* image_path:
|
||||
* type: string
|
||||
* example: "/uploads/1721019403915.png"
|
||||
* 404:
|
||||
* description: Hasil research not found
|
||||
* 413:
|
||||
* description: File size too large (max 5MB)
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.patch("/update/:id", verifyJWT, isAdmin, multer.single('image'), multerErrorHandler, hasilResearchController.updateHasilResearch);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /hasil-research-api/delete/{id}:
|
||||
* delete:
|
||||
* summary: Delete a research (product) result by ID
|
||||
* tags: [Hasil Research]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: ID of the research (product) result to delete
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Research result deleted successfully
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* example: "Research result data successfully deleted"
|
||||
* 404:
|
||||
* description: Research result not found
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
router.delete('/delete/:id', verifyJWT, isAdmin, hasilResearchController.deleteHasilResearch);
|
||||
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,151 +0,0 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import prisma from '../lib/prisma';
|
||||
import authRouter from './auth';
|
||||
import lowonganRouter from './lowongan';
|
||||
import lamaranRouter from './lamaran';
|
||||
import partnershipRouter from './partnership';
|
||||
import researchRouter from './research';
|
||||
import feedbackRouter from './feedback';
|
||||
import faqRouter from './faq';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.use('/auth', authRouter);
|
||||
router.use('/auth-api', authRouter);
|
||||
router.use('/lowongan-magang-api', lowonganRouter);
|
||||
router.use('/lamaran-magang-api', lamaranRouter);
|
||||
router.use('/partnership-api', partnershipRouter);
|
||||
router.use('/hasil-research-api', researchRouter);
|
||||
router.use('/feedback-api', feedbackRouter);
|
||||
router.use('/faq-api', faqRouter);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/health:
|
||||
* get:
|
||||
* summary: Cek status kesehatan server
|
||||
* description: Digunakan untuk memastikan API berjalan normal.
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Server berjalan dengan baik
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: string
|
||||
* example: OK
|
||||
* message:
|
||||
* type: string
|
||||
* example: Server is running smoothly
|
||||
* timestamp:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* example: 2026-06-02T10:00:00.000Z
|
||||
*/
|
||||
router.get('/health', (_req: Request, res: Response) => {
|
||||
res.status(200).json({
|
||||
status: 'OK',
|
||||
message: 'Server is running smoothly',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/users:
|
||||
* get:
|
||||
* summary: Ambil daftar seluruh pengguna
|
||||
* description: Mengembalikan seluruh data user dasar dari database.
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Daftar pengguna berhasil diambil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* count:
|
||||
* type: integer
|
||||
* example: 2
|
||||
* data:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: string
|
||||
* example: cku3xq2v0000xk8w7a1b2c3d4
|
||||
* email:
|
||||
* type: string
|
||||
* example: admin@internify.com
|
||||
* role:
|
||||
* type: string
|
||||
* example: ADMIN
|
||||
* createdAt:
|
||||
* type: string
|
||||
* format: date-time
|
||||
* example: 2026-06-02T10:00:00.000Z
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.get('/users', async (_req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const users = await prisma.user.findMany({
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
count: users.length,
|
||||
data: users,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/error-test:
|
||||
* get:
|
||||
* summary: Simulasi error server untuk pengujian
|
||||
* description: Endpoint utilitas untuk menguji middleware penanganan error global.
|
||||
* tags: [Admin]
|
||||
* responses:
|
||||
* 500:
|
||||
* description: Error simulasi berhasil dipicu
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: string
|
||||
* example: error
|
||||
* statusCode:
|
||||
* type: integer
|
||||
* example: 500
|
||||
* message:
|
||||
* type: string
|
||||
* example: This is a test error to verify our custom global error handler!
|
||||
*/
|
||||
router.get('/error-test', (_req: Request, _res: Response, next: NextFunction) => {
|
||||
try {
|
||||
throw new Error('This is a test error to verify our custom global error handler!');
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -1,622 +0,0 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { protect, restrictTo, AuthenticatedRequest } from '../middleware/auth';
|
||||
import prisma from '../lib/prisma';
|
||||
import { upload } from '../middleware/upload';
|
||||
import { CustomError } from '../middleware/errorHandler';
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Map data lamaran dari DB ke format frontend
|
||||
function mapToFrontend(lamaran: any) {
|
||||
return {
|
||||
id: lamaran.id,
|
||||
status: (lamaran.status || 'diproses').toLowerCase(),
|
||||
batch: lamaran.batch,
|
||||
createdAt: lamaran.createdAt,
|
||||
updatedAt: lamaran.updatedAt,
|
||||
mahasiswa: lamaran.mahasiswa ? {
|
||||
id: lamaran.mahasiswa.id,
|
||||
nama_depan: lamaran.mahasiswa.namaDepan,
|
||||
nama_belakang: lamaran.mahasiswa.namaBelakang || '',
|
||||
email: lamaran.mahasiswa.user?.email || '',
|
||||
kontak: lamaran.mahasiswa.kontak,
|
||||
jurusan: lamaran.mahasiswa.jurusan,
|
||||
universitas: lamaran.mahasiswa.universitas,
|
||||
negara: lamaran.mahasiswa.negara,
|
||||
cv_path: lamaran.mahasiswa.cvPath,
|
||||
portofolio_path: lamaran.mahasiswa.portofolioPath,
|
||||
motivasi: lamaran.mahasiswa.motivasi,
|
||||
relevant_skills: lamaran.mahasiswa.relevantSkills
|
||||
} : null,
|
||||
lowongan_magang: lamaran.lowonganMagang ? {
|
||||
id: lamaran.lowonganMagang.id,
|
||||
posisi: lamaran.lowonganMagang.posisi,
|
||||
kelompok_peminatan: lamaran.lowonganMagang.kelompokPeminatan
|
||||
} : null
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/lamaran-magang-api/add/{lowonganId}:
|
||||
* post:
|
||||
* summary: Kirim lamaran magang baru
|
||||
* description: Mengirim pendaftaran magang ke lowongan tertentu beserta CV dan portofolio (PDF).
|
||||
* tags: [Lamaran Magang]
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: lowonganId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: ID lowongan magang
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* multipart/form-data:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - nama_depan
|
||||
* - email
|
||||
* - kontak
|
||||
* - universitas
|
||||
* - negara
|
||||
* - jurusan
|
||||
* - motivasi
|
||||
* - cv
|
||||
* - portofolio
|
||||
* properties:
|
||||
* nama_depan:
|
||||
* type: string
|
||||
* example: Alya
|
||||
* nama_belakang:
|
||||
* type: string
|
||||
* example: Putri
|
||||
* email:
|
||||
* type: string
|
||||
* example: alya@example.com
|
||||
* kontak:
|
||||
* type: string
|
||||
* example: 081234567890
|
||||
* universitas:
|
||||
* type: string
|
||||
* example: Telkom University
|
||||
* negara:
|
||||
* type: string
|
||||
* example: Indonesia
|
||||
* jurusan:
|
||||
* type: string
|
||||
* example: Informatika
|
||||
* batch:
|
||||
* type: integer
|
||||
* example: 3
|
||||
* motivasi:
|
||||
* type: string
|
||||
* example: Saya ingin belajar langsung dari tim engineering.
|
||||
* relevant_skills:
|
||||
* type: string
|
||||
* example: React, TypeScript, Node.js
|
||||
* cv:
|
||||
* type: string
|
||||
* format: binary
|
||||
* portofolio:
|
||||
* type: string
|
||||
* format: binary
|
||||
* responses:
|
||||
* 201:
|
||||
* description: Lamaran berhasil dikirim
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: Pendaftaran magang berhasil dikirim
|
||||
* 400:
|
||||
* description: Validasi pengajuan lamaran gagal
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* field_wajib:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: Mohon lengkapi semua field wajib yang diperlukan
|
||||
* dokumen_wajib:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: CV dan Portofolio wajib diunggah!
|
||||
* 404:
|
||||
* description: Lowongan magang tidak ditemukan
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 404
|
||||
* message: Lowongan magang tidak ditemukan
|
||||
* 500:
|
||||
* description: Terjadi kesalahan server (termasuk validasi tipe file upload)
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* tipe_file_pdf:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 500
|
||||
* message: CV dan Portofolio harus dalam format PDF!
|
||||
* internal:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 500
|
||||
* message: Internal Server Error
|
||||
*/
|
||||
router.post(
|
||||
'/add/:lowonganId',
|
||||
upload.fields([
|
||||
{ name: 'cv', maxCount: 1 },
|
||||
{ name: 'portofolio', maxCount: 1 }
|
||||
]),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { lowonganId } = req.params;
|
||||
const {
|
||||
nama_depan,
|
||||
nama_belakang,
|
||||
email,
|
||||
kontak,
|
||||
universitas,
|
||||
negara,
|
||||
jurusan,
|
||||
batch,
|
||||
motivasi,
|
||||
relevant_skills
|
||||
} = req.body;
|
||||
|
||||
if (!nama_depan || !email || !kontak || !universitas || !negara || !jurusan || !motivasi) {
|
||||
const error: CustomError = new Error('Mohon lengkapi semua field wajib yang diperlukan');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const files = req.files as { [fieldname: string]: Express.Multer.File[] };
|
||||
const cvFile = files?.['cv']?.[0];
|
||||
const portofolioFile = files?.['portofolio']?.[0];
|
||||
|
||||
if (!cvFile || !portofolioFile) {
|
||||
const error: CustomError = new Error('CV dan Portofolio wajib diunggah!');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const lowongan = await prisma.lowonganMagang.findUnique({
|
||||
where: { id: lowonganId }
|
||||
});
|
||||
|
||||
if (!lowongan) {
|
||||
const error: CustomError = new Error('Lowongan magang tidak ditemukan');
|
||||
error.statusCode = 404;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
let user = await prisma.user.findUnique({
|
||||
where: { email },
|
||||
include: { mahasiswa: true }
|
||||
});
|
||||
|
||||
const cvPath = `/uploads/docs/${cvFile.filename}`;
|
||||
const portofolioPath = `/uploads/docs/${portofolioFile.filename}`;
|
||||
|
||||
if (!user) {
|
||||
// Kalo user belom terdaftar, kita buatin akun STUDENT baru
|
||||
const randomPassword = Math.random().toString(36).substring(2, 15);
|
||||
const salt = await bcrypt.genSalt(10);
|
||||
const passwordHash = await bcrypt.hash(randomPassword, salt);
|
||||
|
||||
user = await prisma.user.create({
|
||||
data: {
|
||||
email,
|
||||
passwordHash,
|
||||
role: 'STUDENT',
|
||||
mahasiswa: {
|
||||
create: {
|
||||
namaDepan: nama_depan,
|
||||
namaBelakang: nama_belakang || null,
|
||||
kontak,
|
||||
jurusan,
|
||||
universitas,
|
||||
negara,
|
||||
cvPath,
|
||||
portofolioPath,
|
||||
motivasi,
|
||||
relevantSkills: relevant_skills || ''
|
||||
}
|
||||
}
|
||||
},
|
||||
include: { mahasiswa: true }
|
||||
});
|
||||
} else {
|
||||
// Kalo user udah ada, kita update data profil mahasiswanya aja
|
||||
if (user.mahasiswa) {
|
||||
await prisma.mahasiswa.update({
|
||||
where: { id: user.mahasiswa.id },
|
||||
data: {
|
||||
namaDepan: nama_depan,
|
||||
namaBelakang: nama_belakang || user.mahasiswa.namaBelakang,
|
||||
kontak: kontak || user.mahasiswa.kontak,
|
||||
jurusan: jurusan || user.mahasiswa.jurusan,
|
||||
universitas: universitas || user.mahasiswa.universitas,
|
||||
negara: negara || user.mahasiswa.negara,
|
||||
cvPath,
|
||||
portofolioPath,
|
||||
motivasi,
|
||||
relevantSkills: relevant_skills || user.mahasiswa.relevantSkills
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const parsedBatch = batch ? parseInt(batch, 10) : lowongan.idBatch;
|
||||
|
||||
const lamaran = await prisma.lamaranMagang.create({
|
||||
data: {
|
||||
idMahasiswa: user.mahasiswa!.id,
|
||||
idLowonganMagang: lowongan.id,
|
||||
status: 'DIPROSES',
|
||||
batch: parsedBatch
|
||||
},
|
||||
include: {
|
||||
mahasiswa: {
|
||||
include: { user: true }
|
||||
},
|
||||
lowonganMagang: true
|
||||
}
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
status: true,
|
||||
message: 'Pendaftaran magang berhasil dikirim',
|
||||
data: mapToFrontend(lamaran)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/lamaran-magang-api/get:
|
||||
* get:
|
||||
* summary: Ambil seluruh data lamaran
|
||||
* description: Mengambil daftar seluruh lamaran magang. Hanya dapat diakses oleh admin.
|
||||
* tags: [Lamaran Magang]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Data lamaran berhasil diambil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 403:
|
||||
* $ref: '#/components/responses/ForbiddenError'
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.get('/get', protect, restrictTo('ADMIN'), async (_req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const applications = await prisma.lamaranMagang.findMany({
|
||||
include: {
|
||||
mahasiswa: {
|
||||
include: { user: true }
|
||||
},
|
||||
lowonganMagang: true
|
||||
},
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
data: applications.map(mapToFrontend)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/lamaran-magang-api/get/{id}:
|
||||
* get:
|
||||
* summary: Ambil detail lamaran berdasarkan ID
|
||||
* description: Mengambil detail satu lamaran magang. Hanya dapat diakses oleh admin.
|
||||
* tags: [Lamaran Magang]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: ID lamaran magang
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Detail lamaran berhasil diambil
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* data:
|
||||
* type: object
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 403:
|
||||
* $ref: '#/components/responses/ForbiddenError'
|
||||
* 404:
|
||||
* description: Lamaran tidak ditemukan
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: error
|
||||
* statusCode: 404
|
||||
* message: Lamaran tidak ditemukan
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.get('/get/:id', protect, restrictTo('ADMIN'), async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const application = await prisma.lamaranMagang.findUnique({
|
||||
where: { id: parseInt(id, 10) },
|
||||
include: {
|
||||
mahasiswa: {
|
||||
include: { user: true }
|
||||
},
|
||||
lowonganMagang: true
|
||||
}
|
||||
});
|
||||
|
||||
if (!application) {
|
||||
const error: CustomError = new Error('Lamaran tidak ditemukan');
|
||||
error.statusCode = 404;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
data: mapToFrontend(application)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/lamaran-magang-api/update/{id}:
|
||||
* patch:
|
||||
* summary: Perbarui status lamaran
|
||||
* description: Mengubah status lamaran menjadi `DIPROSES`, `DITERIMA`, atau `DITOLAK`. Hanya admin.
|
||||
* tags: [Lamaran Magang]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* description: ID lamaran magang
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - status
|
||||
* properties:
|
||||
* status:
|
||||
* type: string
|
||||
* enum: [DIPROSES, DITERIMA, DITOLAK]
|
||||
* example: DITERIMA
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Status lamaran berhasil diperbarui
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* status:
|
||||
* type: boolean
|
||||
* example: true
|
||||
* message:
|
||||
* type: string
|
||||
* example: Status lamaran berhasil diupdate
|
||||
* 400:
|
||||
* description: Validasi status lamaran gagal
|
||||
* content:
|
||||
* application/json:
|
||||
* examples:
|
||||
* status_kosong:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: Mohon masukkan status baru
|
||||
* status_tidak_valid:
|
||||
* value:
|
||||
* status: error
|
||||
* statusCode: 400
|
||||
* message: Status tidak valid
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 403:
|
||||
* $ref: '#/components/responses/ForbiddenError'
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.patch('/update/:id', protect, restrictTo('ADMIN'), async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { status } = req.body;
|
||||
|
||||
if (!status) {
|
||||
const error: CustomError = new Error('Mohon masukkan status baru');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const formattedStatus = status.toUpperCase();
|
||||
if (formattedStatus !== 'DITERIMA' && formattedStatus !== 'DITOLAK' && formattedStatus !== 'DIPROSES') {
|
||||
const error: CustomError = new Error('Status tidak valid');
|
||||
error.statusCode = 400;
|
||||
return next(error);
|
||||
}
|
||||
|
||||
const updated = await prisma.lamaranMagang.update({
|
||||
where: { id: parseInt(id, 10) },
|
||||
data: {
|
||||
status: formattedStatus as any
|
||||
},
|
||||
include: {
|
||||
mahasiswa: {
|
||||
include: { user: true }
|
||||
},
|
||||
lowonganMagang: true
|
||||
}
|
||||
});
|
||||
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
message: 'Status lamaran berhasil diupdate',
|
||||
data: mapToFrontend(updated)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/lamaran-magang-api/delete:
|
||||
* delete:
|
||||
* summary: Hapus seluruh data lamaran
|
||||
* description: Menghapus seluruh data lamaran magang. Hanya dapat diakses oleh admin.
|
||||
* tags: [Lamaran Magang]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Seluruh data pelamar berhasil dihapus
|
||||
* content:
|
||||
* application/json:
|
||||
* example:
|
||||
* status: true
|
||||
* message: Seluruh data pelamar berhasil dihapus
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 403:
|
||||
* $ref: '#/components/responses/ForbiddenError'
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.delete('/delete', protect, restrictTo('ADMIN'), async (_req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
await prisma.lamaranMagang.deleteMany({});
|
||||
res.status(200).json({
|
||||
status: true,
|
||||
message: 'Seluruh data pelamar berhasil dihapus'
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/lamaran-magang-api/export:
|
||||
* get:
|
||||
* summary: Ekspor data lamaran ke file Excel
|
||||
* description: Mengunduh data lamaran dalam format `.xlsx`. Hanya dapat diakses oleh admin.
|
||||
* tags: [Lamaran Magang]
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* responses:
|
||||
* 200:
|
||||
* description: File Excel berhasil dibuat
|
||||
* content:
|
||||
* application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:
|
||||
* schema:
|
||||
* type: string
|
||||
* format: binary
|
||||
* 401:
|
||||
* $ref: '#/components/responses/UnauthorizedError'
|
||||
* 403:
|
||||
* $ref: '#/components/responses/ForbiddenError'
|
||||
* 500:
|
||||
* $ref: '#/components/responses/InternalServerError'
|
||||
*/
|
||||
router.get('/export', protect, restrictTo('ADMIN'), async (_req: AuthenticatedRequest, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const applications = await prisma.lamaranMagang.findMany({
|
||||
include: {
|
||||
mahasiswa: {
|
||||
include: { user: true }
|
||||
},
|
||||
lowonganMagang: true
|
||||
}
|
||||
});
|
||||
|
||||
const rows = applications.map((app) => ({
|
||||
ID: app.id,
|
||||
Nama: `${app.mahasiswa?.namaDepan} ${app.mahasiswa?.namaBelakang || ''}`.trim(),
|
||||
Email: app.mahasiswa?.user?.email || '',
|
||||
Kontak: app.mahasiswa?.kontak || '',
|
||||
Universitas: app.mahasiswa?.universitas || '',
|
||||
Jurusan: app.mahasiswa?.jurusan || '',
|
||||
Negara: app.mahasiswa?.negara || '',
|
||||
Posisi: app.lowonganMagang?.posisi || '',
|
||||
Status: app.status,
|
||||
Motivasi: app.mahasiswa?.motivasi || '',
|
||||
Skills: app.mahasiswa?.relevantSkills || ''
|
||||
}));
|
||||
|
||||
const worksheet = XLSX.utils.json_to_sheet(rows);
|
||||
const workbook = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, 'Applications');
|
||||
|
||||
const buffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' });
|
||||
|
||||
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
res.setHeader('Content-Disposition', 'attachment; filename="data.xlsx"');
|
||||
res.send(buffer);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user