Initial version

This commit is contained in:
Flatlogic Bot 2026-03-17 06:59:09 +00:00
commit 77076e6ef3
541 changed files with 157213 additions and 0 deletions

305
.cursorrules Normal file
View File

@ -0,0 +1,305 @@
# Cursor Rules - Group 1: Development Philosophy & Coding Conventions
1. Overall Architecture & Structure:
- Enforce a clear separation of concerns between the backend and the frontend:
- **Backend**: Use Express for routing, Passport for authentication, and Swagger for API documentation. Organize code into modules such as routes, services, and helpers.
- **Example**:
- Routes: `src/routes/auth.js` for authentication routes.
- Services: `src/services/auth.js` for authentication logic.
- Helpers: `src/helpers/wrapAsync.js` for wrapping asynchronous functions.
- **Frontend**: Use Next.js with React and TypeScript. Structure components using functional components, hooks, and layouts.
- **Example**:
- Pages: `pages/index.tsx` for the main page.
- Components: `components/Header.tsx` for the header component.
- Layouts: `layouts/MainLayout.tsx` for common page layouts.
- Ensure that backend modules and frontend components are organized for reusability and maintainability:
- **Backend**: Separate business logic into services and use middleware for common tasks.
- **Frontend**: Use reusable components and hooks to manage state and lifecycle.
2. Coding Style & Formatting:
- For the backend (JavaScript):
• Use ES6+ features (const/let, arrow functions) consistently.
• Follow Prettier and ESLint configurations (e.g., consistent 2-space indentation, semicolons, and single quotes).
• Maintain clear asynchronous patterns with helper wrappers (e.g., wrapAsync).
- **Example from auth.js**:
```javascript
router.post('/signin/local', wrapAsync(async (req, res) => {
const payload = await AuthService.signin(req.body.email, req.body.password, req);
res.status(200).send(payload);
}));
```
• Document API endpoints with inline Swagger comments to ensure API clarity and consistency.
- **Example**:
```javascript
/**
* @swagger
* /api/auth/signin:
* post:
* summary: Sign in a user
* responses:
* 200:
* description: Successful login
*/
```
- For the frontend (TypeScript/React):
• Use functional components with strict typing and separation of concerns.
- **Example**:
```typescript
const Button: React.FC<{ onClick: () => void }> = ({ onClick }) => (
<button onClick={onClick}>Click me</button>
);
```
• Follow naming conventions: PascalCase for components and types/interfaces, camelCase for variables, hooks, and function names.
- **Example**:
```typescript
const useCustomHook = () => {
const [state, setState] = useState(false);
return [state, setState];
};
```
• Utilize hooks (useEffect, useState) to manage state and lifecycle in a clear and concise manner.
- **Example**:
```typescript
useEffect(() => {
console.log('Component mounted');
}, []);
```
3. Code Quality & Best Practices:
- Ensure code modularity by splitting complex logic into smaller, testable units.
- **Example**: In `auth.js`, routes are separated from business logic, which is handled in `AuthService`.
- Write self-documenting code and add comments where the logic is non-trivial.
- **Example**: Use descriptive function and variable names in `auth.js`, and add comments for complex asynchronous operations.
- Embrace declarative programming and adhere to SOLID principles.
- **Example**: In service functions, ensure each function has a single responsibility and dependencies are injected rather than hardcoded.
4. Consistency & Tools Integration:
- Leverage existing tools like Prettier and ESLint to automatically enforce style and formatting rules.
- **Example**: Use `.prettierrc` and `.eslintrc.cjs` for configuration in your project.
- Use TypeScript in the frontend to ensure type safety and catch errors early.
- **Example**: Define interfaces and types in your React components to enforce strict typing.
- Maintain uniformity in API design and error handling strategies.
- **Example**: Consistently use Passport for authentication and a common error handling middleware in `auth.js`.
## Group 2 Naming Conventions
1. File Naming and Structure:
• Frontend:
- Page Files: Use lower-case filenames (e.g., index.tsx) as prescribed by Next.js conventions.
- **Example**: `pages/index.tsx`, `pages/about.tsx`
- Component Files: Use PascalCase for React component files (e.g., WebSiteHeader.tsx, NavBar.tsx).
- **Example**: `components/Header.tsx`, `components/Footer.tsx`
- Directories: Use clear, descriptive names (e.g., 'pages', 'components', 'WebPageComponents').
- **Example**: `src/pages`, `src/components`
• Backend:
- Use lower-case filenames for modules (e.g., index.js, auth.js, projects.js).
- **Example**: `routes/auth.js`, `services/user.js`
- When needed, use hyphenation for clarity, but maintain consistency.
- **Example**: `helpers/wrap-async.js`
2. Component and Module Naming:
• Frontend:
- React Components: Define components in PascalCase.
- TypeScript Interfaces/Types: Use PascalCase (e.g., WebSiteHeaderProps).
• Backend:
- Classes (if any) and constructors should be in PascalCase; most helper functions and modules use camelCase.
3. Variable, Function, and Hook Naming:
• Use camelCase for variables and function names in both frontend and backend.
- **Example**:
```javascript
const userName = 'John Doe';
function handleLogin() { ... }
```
• Custom Hooks: Prefix with 'use' (e.g., useAuth, useForm).
- **Example**:
```typescript
const useAuth = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
return { isAuthenticated, setIsAuthenticated };
};
```
4. Consistency and Readability:
• Maintain uniform naming across the project to ensure clarity and ease of maintenance.
- **Example**: Use consistent naming conventions for variables, functions, and components, such as camelCase for variables and functions, and PascalCase for components.
- **Example**: In `auth.js`, ensure that all function names clearly describe their purpose, such as `handleLogin` or `validateUserInput`.
## Group 3 Frontend & React Best Practices
1. Use of Functional Components & TypeScript:
• Build all components as functional components.
- **Example**:
```typescript
const Header: React.FC = () => {
return <header>Header Content</header>;
};
```
• Leverage TypeScript for static type checking and enforce strict prop and state types.
- **Example**:
```typescript
interface ButtonProps {
onClick: () => void;
}
const Button: React.FC<ButtonProps> = ({ onClick }) => (
<button onClick={onClick}>Click me</button>
);
```
2. Effective Use of React Hooks:
• Utilize useState and useEffect appropriately with proper dependency arrays.
- **Example**:
```typescript
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Component mounted');
}, []);
```
• Create custom hooks to encapsulate shared logic (e.g., useAppSelector).
- **Example**:
```typescript
const useAuth = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
return { isAuthenticated, setIsAuthenticated };
};
```
3. Component Composition & Separation of Concerns:
• Separate presentational (stateless) components from container components managing logic.
- **Example**: Use `LayoutGuest` to encapsulate common page structures.
4. Code Quality & Readability:
• Maintain consistent formatting and adhere to Prettier and ESLint rules.
• Use descriptive names for variables, functions, and components.
• Document non-trivial logic with inline comments and consider implementing error boundaries where needed.
• New code must adhere to these conventions to avoid ambiguity.
• Use descriptive names that reflect the purpose and domain, avoiding abbreviations unless standard in the project.
## Group 4 Backend & API Guidelines
1. API Endpoint Design & Documentation:
• Follow RESTful naming conventions; all route handlers should be named clearly and consistently.
- **Example**: Use verbs like `GET`, `POST`, `PUT`, `DELETE` to define actions, e.g., `GET /api/auth/me` to retrieve user info.
• Document endpoints with Swagger annotations to provide descriptions, expected request bodies, and response codes.
- **Example**:
```javascript
/**
* @swagger
* /api/auth/signin:
* post:
* summary: Sign in a user
* requestBody:
* description: User credentials
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Auth"
* responses:
* 200:
* description: Successful login
* 400:
* description: Invalid username/password supplied
*/
```
• Examples (for Auth endpoints):
- POST /api/auth/signin/local
• Description: Logs the user into the system.
• Request Body (application/json):
{ "email": "admin@flatlogic.com", "password": "password" }
• Responses:
- 200: Successful login (returns token and user data).
- 400: Invalid username/password supplied.
- GET /api/auth/me
• Description: Retrieves current authorized user information.
• Secured via Passport JWT; uses req.currentUser.
• Responses:
- 200: Returns current user info.
- 400: Invalid credentials or missing user data.
- POST /api/auth/signup
• Description: Registers a new user.
• Request Body (application/json):
{ "email": "admin@flatlogic.com", "password": "password" }
• Responses:
- 200: New user signed up successfully.
- 400: Invalid input supplied.
- 500: Server error.
## Group 5 Testing, Quality Assurance & Error Handling
1. Testing Guidelines:
• Write unit tests for critical backend and frontend components using frameworks such as Jest, React Testing Library, and Mocha/Chai.
- **Example**:
```javascript
test('should return user data', async () => {
const user = await getUserData();
expect(user).toHaveProperty('email');
});
```
• Practice test-driven development and maintain high test coverage.
• Regularly update tests following changes in business logic.
2. Quality Assurance:
• Enforce code quality with ESLint, Prettier, and static analysis tools.
• Integrate continuous testing workflows (CI/CD) to catch issues early.
- **Example**: Use GitHub Actions for automated testing and deployment.
• Ensure documentation is kept up-to-date with the implemented code.
3. Error Handling:
• Back-end:
- Wrap asynchronous route handlers with a helper (e.g., wrapAsync) to capture errors.
- **Example**:
```javascript
router.post('/signin', wrapAsync(async (req, res) => {
const user = await AuthService.signin(req.body);
res.send(user);
}));
```
- Use centralized error handling middleware (e.g., commonErrorHandler) for uniform error responses.
• Front-end:
- Implement error boundaries in React to gracefully handle runtime errors.
- Display user-friendly error messages and log errors for further analysis.
2. Authentication & Security:
• Protect endpoints by using Passport.js with JWT (e.g., passport.authenticate('jwt', { session: false })).
- **Example**:
```javascript
router.get('/profile', passport.authenticate('jwt', { session: false }), (req, res) => {
res.send(req.user);
});
```
• Ensure that secure routes check for existence of req.currentUser. If absent, return a ForbiddenError.
3. Consistent Error Handling & Middleware Usage:
• Wrap asynchronous route handlers with helpers like wrapAsync for error propagation.
• Use centralized error handling middleware (e.g., commonErrorHandler) to capture and format errors uniformly.
4. Modular Code Organization:
• Organize backend code into separate files for routes, services, and database access (e.g., auth.js, projects.js, tasks.js).
• Use descriptive, lowercase filenames for modules and routes.
5. Endpoint Security Best Practices:
• Validate input data and sanitize requests where necessary.
• Restrict sensitive operations to authenticated users with proper role-based permissions.
────────────────────────────────────────
Group 6 Accessibility, UI, and Styling Guidelines (Updated)
────────────────────────────────────────
1. Sidebar Styling:
• The sidebar is implemented in the authenticated layout via the AsideMenu component, with the actual element defined in AsideMenuLayer (located at frontend/src/components/AsideMenuLayer.tsx) as an <aside> element with id="asideMenu".
- **Example**:
```css
#asideMenu {
background-color: #F8F4E1 !important;
}
```
• When modifying sidebar styles, target #asideMenu and its child elements rather than generic selectors (e.g., avoid .app-sidebar) to ensure that the changes affect the actual rendered sidebar.
• Remove or override any conflicting background utilities (such as an unwanted bg-white) so our desired background color (#F8F4E1) is fully visible. Use a highly specific selector if necessary.
• Adjust spacing (padding/margins) at both the container (#asideMenu) and the individual menu item level to maintain a consistent, compact design.
2. General Project Styling and Tailwind CSS Usage:
• The application leverages Tailwind CSS extensively, with core styling defined in _theme.css using the @apply directive. Any new modifications should follow this pattern to ensure consistency.
- **Example**:
```css
.btn {
@apply bg-blue-500 text-white;
}
```
• The themed blocks (like .theme-pink and .theme-green) standardize the UI's appearance. When applying custom overrides, ensure they integrate cleanly into these structures and avoid conflicts or circular dependency errors (e.g., issues when redefining utilities such as text-blue-600).
• Adjustments via Tailwind CSS generally require modifying class names in the components and ensuring that global overrides are applied in the correct order. Consistent use of design tokens and custom color codes (e.g., #F8F4E1) throughout the app is crucial to a cohesive design.
• Specificity is key. If a change isn't visually reflected as expected, inspect the rendered HTML to identify which classes are taking precedence.

3
.dockerignore Normal file
View File

@ -0,0 +1,3 @@
backend/node_modules
frontend/node_modules
frontend/build

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules/
*/node_modules/
*/build/

187
502.html Normal file
View File

@ -0,0 +1,187 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Service Starting</title>
<style>
body {
font-family: sans-serif;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #EFF2FF;
margin: 0;
padding: 20px;
}
.container {
text-align: center;
padding: 30px 40px;
background-color: #fff;
border-radius: 20px;
margin-bottom: 20px;
max-width: 538px;
width: 100%;
box-shadow: 0 13px 34px 0 rgba(167, 187, 242, 0.2);
box-sizing: border-box;
}
#status-heading {
font-size: 24px;
font-weight: 700;
color: #02004E;
margin-bottom: 20px;
}
h2 {
color: #333;
margin-bottom: 15px;
}
p {
color: #666;
font-size: 1.1em;
margin-bottom: 10px;
}
.tip {
font-weight: 300;
font-size: 17px;
line-height: 150%;
letter-spacing: 0;
text-align: center;
margin-top: 30px;
}
.loader-container {
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.loader {
width: 100px;
aspect-ratio: 1;
border-radius: 50%;
background:
radial-gradient(farthest-side, #5C7EF1 94%, #0000) top/8px 8px no-repeat,
conic-gradient(#0000 30%, #5C7EF1);
-webkit-mask: radial-gradient(farthest-side, #0000 calc(100% - 8px), #000 0);
animation: l13 2s infinite linear;
}
@keyframes l13 {
100% {
transform: rotate(1turn)
}
}
.app-logo {
position: absolute;
width: 36px;
}
.panel {
padding: 0 18px;
display: none;
background-color: white;
overflow: hidden;
margin-top: 10px;
}
.show {
display: block;
}
.project-info {
border: 1px solid #8C9DFF;
border-radius: 10px;
padding: 12px 16px;
max-width: 600px;
margin: 40px auto;
background-color: #FBFCFF;
}
.project-info h2 {
color: #02004E;
font-size: 14px;
font-weight: 500;
margin-bottom: 10px;
text-align: left;
}
.project-info p {
color: #686791;
font-size: 12px;
font-weight: 400;
text-align: left;
}
</style>
</head>
<body>
<div class="container">
<h2 id="status-heading">Loading the app, just a moment…</h2>
<p class="tip">The application is currently launching. The page will automatically refresh once site is
available.</p>
<div class="project-info">
<h2>SMPN 1 Seponti Digital</h2>
<p>Platform sekolah digital terpadu untuk e-learning, raport KKTP, dashboard, dan AI analisis prestasi siswa.</p>
</div>
<div class="loader-container">
<img src="https://flatlogic.com/blog/wp-content/uploads/2025/05/logo-bot-1.png" alt="App Logo"
class="app-logo">
<div class="loader"></div>
</div>
<div class="panel">
<video width="100%" height="315" controls loop>
<source
src="https://flatlogic.com/blog/wp-content/uploads/2025/04/20250430_1336_professional_dynamo_spinner_simple_compose_01jt349yvtenxt7xhg8hhr85j8.mp4"
type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
<script>
function checkAvailability() {
fetch('/')
.then(response => {
if (response.ok) {
window.location.reload();
} else {
setTimeout(checkAvailability, 5000);
}
})
.catch(() => {
setTimeout(checkAvailability, 5000);
});
}
document.addEventListener('DOMContentLoaded', checkAvailability);
document.addEventListener('DOMContentLoaded', function () {
const appTitle = document.querySelector('#status-heading');
const panel = document.querySelector('.panel');
const video = panel.querySelector('video');
let clickCount = 0;
appTitle.addEventListener('click', function () {
clickCount++;
if (clickCount === 5) {
panel.classList.toggle('show');
if (panel.classList.contains('show')) {
video.play();
} else {
video.pause();
}
clickCount = 0;
}
});
});
</script>
</body>
</html>

21
Dockerfile Normal file
View File

@ -0,0 +1,21 @@
FROM node:20.15.1-alpine AS builder
RUN apk add --no-cache git
WORKDIR /app
COPY frontend/package.json frontend/yarn.lock ./
RUN yarn install --pure-lockfile
COPY frontend .
RUN yarn build
FROM node:20.15.1-alpine
WORKDIR /app
COPY backend/package.json backend/yarn.lock ./
RUN yarn install --pure-lockfile
COPY backend .
COPY --from=builder /app/build /app/public
CMD ["yarn", "start"]

85
Dockerfile.dev Normal file
View File

@ -0,0 +1,85 @@
# Base image for Node.js dependencies
FROM node:20.15.1-alpine AS frontend-deps
RUN apk add --no-cache git
WORKDIR /app/frontend
COPY frontend/package.json frontend/yarn.lock ./
RUN yarn install --pure-lockfile
FROM node:20.15.1-alpine AS backend-deps
RUN apk add --no-cache git
WORKDIR /app/backend
COPY backend/package.json backend/yarn.lock ./
RUN yarn install --pure-lockfile
FROM node:20.15.1-alpine AS app-shell-deps
RUN apk add --no-cache git
WORKDIR /app/app-shell
COPY app-shell/package.json app-shell/yarn.lock ./
RUN yarn install --pure-lockfile
# Nginx setup and application build
FROM node:20.15.1-alpine AS build
RUN apk add --no-cache git nginx curl
RUN apk add --no-cache lsof procps
RUN yarn global add concurrently
RUN apk add --no-cache \
chromium \
nss \
freetype \
harfbuzz \
ttf-freefont \
fontconfig
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
RUN mkdir -p /app/pids
# Make sure to add yarn global bin to PATH
ENV PATH /root/.yarn/bin:/root/.config/yarn/global/node_modules/.bin:$PATH
# Copy dependencies
WORKDIR /app
COPY --from=frontend-deps /app/frontend /app/frontend
COPY --from=backend-deps /app/backend /app/backend
COPY --from=app-shell-deps /app/app-shell /app/app-shell
COPY frontend /app/frontend
COPY backend /app/backend
COPY app-shell /app/app-shell
COPY docker /app/docker
# Copy all files from root to /app
COPY . /app
# Copy Nginx configuration
COPY nginx.conf /etc/nginx/nginx.conf
# Copy custom error page
COPY 502.html /usr/share/nginx/html/502.html
# Change owner and permissions of the error page
RUN chown nginx:nginx /usr/share/nginx/html/502.html && \
chmod 644 /usr/share/nginx/html/502.html
# Expose the port the app runs on
EXPOSE 8080
ENV NODE_ENV=dev_stage
ENV FRONT_PORT=3001
ENV BACKEND_PORT=3000
ENV APP_SHELL_PORT=4000
CMD ["sh", "-c", "\
yarn --cwd /app/frontend dev & echo $! > /app/pids/frontend.pid && \
yarn --cwd /app/backend start & echo $! > /app/pids/backend.pid && \
sleep 10 && nginx -g 'daemon off;' & \
NGINX_PID=$! && \
echo 'Waiting for backend (port 3000) to be available...' && \
while ! nc -z localhost ${BACKEND_PORT}; do \
sleep 2; \
done && \
echo 'Backend is up. Starting app_shell for Git check...' && \
yarn --cwd /app/app-shell start && \
wait $NGINX_PID"]

1
LICENSE Normal file
View File

@ -0,0 +1 @@
https://flatlogic.com/

244
README.md Normal file
View File

@ -0,0 +1,244 @@
# SMPN 1 Seponti Digital
## This project was generated by [Flatlogic Platform](https://flatlogic.com).
- Frontend: [React.js](https://flatlogic.com/templates?framework%5B%5D=react&sort=default)
- Backend: [NodeJS](https://flatlogic.com/templates?backend%5B%5D=nodejs&sort=default)
<details><summary>Backend Folder Structure</summary>
The generated application has the following backend folder structure:
`src` folder which contains your working files that will be used later to create the build. The src folder contains folders as:
- `auth` - config the library for authentication and authorization;
- `db` - contains such folders as:
- `api` - documentation that is automatically generated by jsdoc or other tools;
- `migrations` - is a skeleton of the database or all the actions that users do with the database;
- `models`- what will represent the database for the backend;
- `seeders` - the entity that creates the data for the database.
- `routes` - this folder would contain all the routes that you have created using Express Router and what they do would be exported from a Controller file;
- `services` - contains such folders as `emails` and `notifications`.
</details>
- Database: PostgreSQL
- app-shel: Core application framework that provides essential infrastructure services
for the entire application.
-----------------------
### We offer 2 ways how to start the project locally: by running Frontend and Backend or with Docker.
-----------------------
## To start the project:
### Backend:
> Please change current folder: `cd backend`
#### Install local dependencies:
`yarn install`
------------
#### Adjust local db:
##### 1. Install postgres:
MacOS:
`brew install postgres`
> if you dont have brew please install it (https://brew.sh) and repeat step `brew install postgres`.
Ubuntu:
`sudo apt update`
`sudo apt install postgresql postgresql-contrib`
##### 2. Create db and admin user:
Before run and test connection, make sure you have created a database as described in the above configuration. You can use the `psql` command to create a user and database.
`psql postgres --u postgres`
Next, type this command for creating a new user with password then give access for creating the database.
`postgres-# CREATE ROLE admin WITH LOGIN PASSWORD 'admin_pass';`
`postgres-# ALTER ROLE admin CREATEDB;`
Quit `psql` then log in again using the new user that previously created.
`postgres-# \q`
`psql postgres -U admin`
Type this command to creating a new database.
`postgres=> CREATE DATABASE db_{your_project_name};`
Then give that new user privileges to the new database then quit the `psql`.
`postgres=> GRANT ALL PRIVILEGES ON DATABASE db_{your_project_name} TO admin;`
`postgres=> \q`
------------
#### Create database:
`yarn db:create`
#### Start production build:
`yarn start`
### Frontend:
> Please change current folder: `cd frontend`
## To start the project with Docker:
### Description:
The project contains the **docker folder** and the `Dockerfile`.
The `Dockerfile` is used to Deploy the project to Google Cloud.
The **docker folder** contains a couple of helper scripts:
- `docker-compose.yml` (all our services: web, backend, db are described here)
- `start-backend.sh` (starts backend, but only after the database)
- `wait-for-it.sh` (imported from https://github.com/vishnubob/wait-for-it)
> To avoid breaking the application, we recommend you don't edit the following files: everything that includes the **docker folder** and `Dokerfile`.
## Run services:
1. Install docker compose (https://docs.docker.com/compose/install/)
2. Move to `docker` folder. All next steps should be done from this folder.
``` cd docker ```
3. Make executables from `wait-for-it.sh` and `start-backend.sh`:
``` chmod +x start-backend.sh && chmod +x wait-for-it.sh ```
4. Download dependend projects for services.
5. Review the docker-compose.yml file. Make sure that all services have Dockerfiles. Only db service doesn't require a Dockerfile.
6. Make sure you have needed ports (see them in `ports`) available on your local machine.
7. Start services:
7.1. With an empty database `rm -rf data && docker-compose up`
7.2. With a stored (from previus runs) database data `docker-compose up`
8. Check http://localhost:3000
9. Stop services:
9.1. Just press `Ctr+C`
## Most common errors:
1. `connection refused`
There could be many reasons, but the most common are:
- The port is not open on the destination machine.
- The port is open on the destination machine, but its backlog of pending connections is full.
- A firewall between the client and server is blocking access (also check local firewalls).
After checking for firewalls and that the port is open, use telnet to connect to the IP/port to test connectivity. This removes any potential issues from your application.
***MacOS:***
If you suspect that your SSH service might be down, you can run this command to find out:
`sudo service ssh status`
If the command line returns a status of down, then youve likely found the reason behind your connectivity error.
***Ubuntu:***
Sometimes a connection refused error can also indicate that there is an IP address conflict on your network. You can search for possible IP conflicts by running:
`arp-scan -I eth0 -l | grep <ipaddress>`
`arp-scan -I eth0 -l | grep <ipaddress>`
and
`arping <ipaddress>`
2. `yarn db:create` creates database with the assembled tables (on MacOS with Postgres database)
The workaround - put the next commands to your Postgres database terminal:
`DROP SCHEMA public CASCADE;`
`CREATE SCHEMA public;`
`GRANT ALL ON SCHEMA public TO postgres;`
`GRANT ALL ON SCHEMA public TO public;`
Afterwards, continue to start your project in the backend directory by running:
`yarn start`

14
backend/.env Normal file
View File

@ -0,0 +1,14 @@
DB_NAME=app_39224
DB_USER=app_39224
DB_PASS=48a92208-a252-4371-b6a4-4f214eaf4308
DB_HOST=127.0.0.1
DB_PORT=5432
PORT=3000
GOOGLE_CLIENT_ID=671001533244-kf1k1gmp6mnl0r030qmvdu6v36ghmim6.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=Yo4qbKZniqvojzUQ60iKlxqR
MS_CLIENT_ID=4696f457-31af-40de-897c-e00d7d4cff73
MS_CLIENT_SECRET=m8jzZ.5UpHF3=-dXzyxiZ4e[F8OF54@p
EMAIL_USER=AKIAVEW7G4PQUBGM52OF
EMAIL_PASS=BLnD4hKGb6YkSz3gaQrf8fnyLi3C3/EdjOOsLEDTDPTz
SECRET_KEY=HUEyqESqgQ1yTwzVlO6wprC9Kf1J1xuA
PEXELS_KEY=Vc99rnmOhHhJAbgGQoKLZtsaIVfkeownoQNbTj78VemUjKh08ZYRbf18

4
backend/.eslintignore Normal file
View File

@ -0,0 +1,4 @@
# Ignore generated and runtime files
node_modules/
tmp/
logs/

15
backend/.eslintrc.cjs Normal file
View File

@ -0,0 +1,15 @@
module.exports = {
env: {
node: true,
es2021: true
},
extends: [
'eslint:recommended'
],
plugins: [
'import'
],
rules: {
'import/no-unresolved': 'error'
}
};

11
backend/.prettierrc Normal file
View File

@ -0,0 +1,11 @@
{
"singleQuote": true,
"tabWidth": 2,
"printWidth": 80,
"trailingComma": "all",
"quoteProps": "as-needed",
"jsxSingleQuote": true,
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always"
}

7
backend/.sequelizerc Normal file
View File

@ -0,0 +1,7 @@
const path = require('path');
module.exports = {
"config": path.resolve("src", "db", "db.config.js"),
"models-path": path.resolve("src", "db", "models"),
"seeders-path": path.resolve("src", "db", "seeders"),
"migrations-path": path.resolve("src", "db", "migrations")
};

23
backend/Dockerfile Normal file
View File

@ -0,0 +1,23 @@
FROM node:20.15.1-alpine
RUN apk update && apk add bash
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN yarn install
# If you are building your code for production
# RUN npm ci --only=production
# Bundle app source
COPY . .
EXPOSE 8080
CMD [ "yarn", "start" ]

56
backend/README.md Normal file
View File

@ -0,0 +1,56 @@
#SMPN 1 Seponti Digital - template backend,
#### Run App on local machine:
##### Install local dependencies:
- `yarn install`
------------
##### Adjust local db:
###### 1. Install postgres:
- MacOS:
- `brew install postgres`
- Ubuntu:
- `sudo apt update`
- `sudo apt install postgresql postgresql-contrib`
###### 2. Create db and admin user:
- Before run and test connection, make sure you have created a database as described in the above configuration. You can use the `psql` command to create a user and database.
- `psql postgres --u postgres`
- Next, type this command for creating a new user with password then give access for creating the database.
- `postgres-# CREATE ROLE admin WITH LOGIN PASSWORD 'admin_pass';`
- `postgres-# ALTER ROLE admin CREATEDB;`
- Quit `psql` then log in again using the new user that previously created.
- `postgres-# \q`
- `psql postgres -U admin`
- Type this command to creating a new database.
- `postgres=> CREATE DATABASE db_smpn_1_seponti_digital;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_smpn_1_seponti_digital TO admin;`
- `postgres=> \q`
------------
#### Api Documentation (Swagger)
http://localhost:8080/api-docs (local host)
http://host_name/api-docs
------------
##### Setup database tables or update after schema change
- `yarn db:migrate`
##### Seed the initial data (admin accounts, relevant for the first setup):
- `yarn db:seed`
##### Start build:
- `yarn start`

56
backend/package.json Normal file
View File

@ -0,0 +1,56 @@
{
"name": "smpn1sepontidigital",
"description": "SMPN 1 Seponti Digital - template backend",
"scripts": {
"start": "npm run db:migrate && npm run db:seed && npm run watch",
"lint": "eslint . --ext .js",
"db:migrate": "sequelize-cli db:migrate",
"db:seed": "sequelize-cli db:seed:all",
"db:drop": "sequelize-cli db:drop",
"db:create": "sequelize-cli db:create",
"watch": "node watcher.js"
},
"dependencies": {
"@google-cloud/storage": "^5.18.2",
"axios": "^1.6.7",
"bcrypt": "5.1.1",
"chokidar": "^4.0.3",
"cors": "2.8.5",
"csv-parser": "^3.0.0",
"express": "4.18.2",
"formidable": "1.2.2",
"helmet": "4.1.1",
"json2csv": "^5.0.7",
"jsonwebtoken": "8.5.1",
"lodash": "4.17.21",
"moment": "2.30.1",
"multer": "^1.4.4",
"mysql2": "2.2.5",
"nodemailer": "6.9.9",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
"passport-jwt": "^4.0.1",
"passport-microsoft": "^0.1.0",
"pg": "8.4.1",
"pg-hstore": "2.3.4",
"sequelize": "6.35.2",
"sequelize-json-schema": "^2.1.1",
"sqlite": "4.0.15",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0",
"tedious": "^18.2.4"
},
"engines": {
"node": ">=18"
},
"private": true,
"devDependencies": {
"cross-env": "7.0.3",
"eslint": "^8.23.1",
"eslint-plugin-import": "^2.29.1",
"mocha": "8.1.3",
"node-mocks-http": "1.9.0",
"nodemon": "2.0.5",
"sequelize-cli": "6.6.2"
}
}

View File

@ -0,0 +1,484 @@
"use strict";
const fs = require("fs");
const path = require("path");
const http = require("http");
const https = require("https");
const { URL } = require("url");
let CONFIG_CACHE = null;
class LocalAIApi {
static createResponse(params, options) {
return createResponse(params, options);
}
static request(pathValue, payload, options) {
return request(pathValue, payload, options);
}
static fetchStatus(aiRequestId, options) {
return fetchStatus(aiRequestId, options);
}
static awaitResponse(aiRequestId, options) {
return awaitResponse(aiRequestId, options);
}
static extractText(response) {
return extractText(response);
}
static decodeJsonFromResponse(response) {
return decodeJsonFromResponse(response);
}
}
async function createResponse(params, options = {}) {
const payload = { ...(params || {}) };
if (!Array.isArray(payload.input) || payload.input.length === 0) {
return {
success: false,
error: "input_missing",
message: 'Parameter "input" is required and must be a non-empty array.',
};
}
const cfg = config();
if (!payload.model) {
payload.model = cfg.defaultModel;
}
const initial = await request(options.path, payload, options);
if (!initial.success) {
return initial;
}
const data = initial.data;
if (data && typeof data === "object" && data.ai_request_id) {
const pollTimeout = Number(options.poll_timeout ?? 300);
const pollInterval = Number(options.poll_interval ?? 5);
return await awaitResponse(data.ai_request_id, {
interval: pollInterval,
timeout: pollTimeout,
headers: options.headers,
timeout_per_call: options.timeout,
verify_tls: options.verify_tls,
});
}
return initial;
}
async function request(pathValue, payload = {}, options = {}) {
const cfg = config();
const resolvedPath = pathValue || options.path || cfg.responsesPath;
if (!resolvedPath) {
return {
success: false,
error: "project_id_missing",
message: "PROJECT_ID is not defined; cannot resolve AI proxy endpoint.",
};
}
if (!cfg.projectUuid) {
return {
success: false,
error: "project_uuid_missing",
message: "PROJECT_UUID is not defined; aborting AI request.",
};
}
const bodyPayload = { ...(payload || {}) };
if (!bodyPayload.project_uuid) {
bodyPayload.project_uuid = cfg.projectUuid;
}
const url = buildUrl(resolvedPath, cfg.baseUrl);
const timeout = resolveTimeout(options.timeout, cfg.timeout);
const verifyTls = resolveVerifyTls(options.verify_tls, cfg.verifyTls);
const headers = {
Accept: "application/json",
"Content-Type": "application/json",
[cfg.projectHeader]: cfg.projectUuid,
};
if (Array.isArray(options.headers)) {
for (const header of options.headers) {
if (typeof header === "string" && header.includes(":")) {
const [name, value] = header.split(":", 2);
headers[name.trim()] = value.trim();
}
}
}
const body = JSON.stringify(bodyPayload);
return sendRequest(url, "POST", body, headers, timeout, verifyTls);
}
async function fetchStatus(aiRequestId, options = {}) {
const cfg = config();
if (!cfg.projectUuid) {
return {
success: false,
error: "project_uuid_missing",
message: "PROJECT_UUID is not defined; aborting status check.",
};
}
const statusPath = resolveStatusPath(aiRequestId, cfg);
const url = buildUrl(statusPath, cfg.baseUrl);
const timeout = resolveTimeout(options.timeout, cfg.timeout);
const verifyTls = resolveVerifyTls(options.verify_tls, cfg.verifyTls);
const headers = {
Accept: "application/json",
[cfg.projectHeader]: cfg.projectUuid,
};
if (Array.isArray(options.headers)) {
for (const header of options.headers) {
if (typeof header === "string" && header.includes(":")) {
const [name, value] = header.split(":", 2);
headers[name.trim()] = value.trim();
}
}
}
return sendRequest(url, "GET", null, headers, timeout, verifyTls);
}
async function awaitResponse(aiRequestId, options = {}) {
const timeout = Number(options.timeout ?? 300);
const interval = Math.max(Number(options.interval ?? 5), 1);
const deadline = Date.now() + Math.max(timeout, interval) * 1000;
while (true) {
const statusResp = await fetchStatus(aiRequestId, {
headers: options.headers,
timeout: options.timeout_per_call,
verify_tls: options.verify_tls,
});
if (statusResp.success) {
const data = statusResp.data || {};
if (data && typeof data === "object") {
if (data.status === "success") {
return {
success: true,
status: 200,
data: data.response || data,
};
}
if (data.status === "failed") {
return {
success: false,
status: 500,
error: String(data.error || "AI request failed"),
data,
};
}
}
} else {
return statusResp;
}
if (Date.now() >= deadline) {
return {
success: false,
error: "timeout",
message: "Timed out waiting for AI response.",
};
}
await sleep(interval * 1000);
}
}
function extractText(response) {
const payload = response && typeof response === "object" ? response.data || response : null;
if (!payload || typeof payload !== "object") {
return "";
}
if (Array.isArray(payload.output)) {
let combined = "";
for (const item of payload.output) {
if (!item || !Array.isArray(item.content)) {
continue;
}
for (const block of item.content) {
if (
block &&
typeof block === "object" &&
block.type === "output_text" &&
typeof block.text === "string" &&
block.text.length > 0
) {
combined += block.text;
}
}
}
if (combined) {
return combined;
}
}
if (
payload.choices &&
payload.choices[0] &&
payload.choices[0].message &&
typeof payload.choices[0].message.content === "string"
) {
return payload.choices[0].message.content;
}
return "";
}
function decodeJsonFromResponse(response) {
const text = extractText(response);
if (!text) {
throw new Error("No text found in AI response.");
}
const parsed = parseJson(text);
if (parsed.ok && parsed.value && typeof parsed.value === "object") {
return parsed.value;
}
const stripped = stripJsonFence(text);
if (stripped !== text) {
const parsedStripped = parseJson(stripped);
if (parsedStripped.ok && parsedStripped.value && typeof parsedStripped.value === "object") {
return parsedStripped.value;
}
throw new Error(`JSON parse failed after stripping fences: ${parsedStripped.error}`);
}
throw new Error(`JSON parse failed: ${parsed.error}`);
}
function config() {
if (CONFIG_CACHE) {
return CONFIG_CACHE;
}
ensureEnvLoaded();
const baseUrl = process.env.AI_PROXY_BASE_URL || "https://flatlogic.com";
const projectId = process.env.PROJECT_ID || null;
let responsesPath = process.env.AI_RESPONSES_PATH || null;
if (!responsesPath && projectId) {
responsesPath = `/projects/${projectId}/ai-request`;
}
const timeout = resolveTimeout(process.env.AI_TIMEOUT, 30);
const verifyTls = resolveVerifyTls(process.env.AI_VERIFY_TLS, true);
CONFIG_CACHE = {
baseUrl,
responsesPath,
projectId,
projectUuid: process.env.PROJECT_UUID || null,
projectHeader: process.env.AI_PROJECT_HEADER || "project-uuid",
defaultModel: process.env.AI_DEFAULT_MODEL || "gpt-5-mini",
timeout,
verifyTls,
};
return CONFIG_CACHE;
}
function buildUrl(pathValue, baseUrl) {
const trimmed = String(pathValue || "").trim();
if (trimmed === "") {
return baseUrl;
}
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
return trimmed;
}
if (trimmed.startsWith("/")) {
return `${baseUrl}${trimmed}`;
}
return `${baseUrl}/${trimmed}`;
}
function resolveStatusPath(aiRequestId, cfg) {
const basePath = (cfg.responsesPath || "").replace(/\/+$/, "");
if (!basePath) {
return `/ai-request/${encodeURIComponent(String(aiRequestId))}/status`;
}
const normalized = basePath.endsWith("/ai-request") ? basePath : `${basePath}/ai-request`;
return `${normalized}/${encodeURIComponent(String(aiRequestId))}/status`;
}
function sendRequest(urlString, method, body, headers, timeoutSeconds, verifyTls) {
return new Promise((resolve) => {
let targetUrl;
try {
targetUrl = new URL(urlString);
} catch (err) {
resolve({
success: false,
error: "invalid_url",
message: err.message,
});
return;
}
const isHttps = targetUrl.protocol === "https:";
const requestFn = isHttps ? https.request : http.request;
const options = {
protocol: targetUrl.protocol,
hostname: targetUrl.hostname,
port: targetUrl.port || (isHttps ? 443 : 80),
path: `${targetUrl.pathname}${targetUrl.search}`,
method: method.toUpperCase(),
headers,
timeout: Math.max(Number(timeoutSeconds || 30), 1) * 1000,
};
if (isHttps) {
options.rejectUnauthorized = Boolean(verifyTls);
}
const req = requestFn(options, (res) => {
let responseBody = "";
res.setEncoding("utf8");
res.on("data", (chunk) => {
responseBody += chunk;
});
res.on("end", () => {
const status = res.statusCode || 0;
const parsed = parseJson(responseBody);
const payload = parsed.ok ? parsed.value : responseBody;
if (status >= 200 && status < 300) {
const result = {
success: true,
status,
data: payload,
};
if (!parsed.ok) {
result.json_error = parsed.error;
}
resolve(result);
return;
}
const errorMessage =
parsed.ok && payload && typeof payload === "object"
? String(payload.error || payload.message || "AI proxy request failed")
: String(responseBody || "AI proxy request failed");
resolve({
success: false,
status,
error: errorMessage,
response: payload,
json_error: parsed.ok ? undefined : parsed.error,
});
});
});
req.on("timeout", () => {
req.destroy(new Error("request_timeout"));
});
req.on("error", (err) => {
resolve({
success: false,
error: "request_failed",
message: err.message,
});
});
if (body) {
req.write(body);
}
req.end();
});
}
function parseJson(value) {
if (typeof value !== "string" || value.trim() === "") {
return { ok: false, error: "empty_response" };
}
try {
return { ok: true, value: JSON.parse(value) };
} catch (err) {
return { ok: false, error: err.message };
}
}
function stripJsonFence(text) {
const trimmed = text.trim();
if (trimmed.startsWith("```json")) {
return trimmed.replace(/^```json/, "").replace(/```$/, "").trim();
}
if (trimmed.startsWith("```")) {
return trimmed.replace(/^```/, "").replace(/```$/, "").trim();
}
return text;
}
function resolveTimeout(value, fallback) {
const parsed = Number.parseInt(String(value ?? fallback), 10);
return Number.isNaN(parsed) ? Number(fallback) : parsed;
}
function resolveVerifyTls(value, fallback) {
if (value === undefined || value === null) {
return Boolean(fallback);
}
return String(value).toLowerCase() !== "false" && String(value) !== "0";
}
function ensureEnvLoaded() {
if (process.env.PROJECT_UUID && process.env.PROJECT_ID) {
return;
}
const envPath = path.resolve(__dirname, "../../../../.env");
if (!fs.existsSync(envPath)) {
return;
}
let content;
try {
content = fs.readFileSync(envPath, "utf8");
} catch (err) {
throw new Error(`Failed to read executor .env: ${err.message}`);
}
for (const line of content.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#") || !trimmed.includes("=")) {
continue;
}
const [rawKey, ...rest] = trimmed.split("=");
const key = rawKey.trim();
if (!key) {
continue;
}
const value = rest.join("=").trim().replace(/^['"]|['"]$/g, "");
if (!process.env[key]) {
process.env[key] = value;
}
}
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
module.exports = {
LocalAIApi,
createResponse,
request,
fetchStatus,
awaitResponse,
extractText,
decodeJsonFromResponse,
};

68
backend/src/auth/auth.js Normal file
View File

@ -0,0 +1,68 @@
const config = require('../config');
const providers = config.providers;
const helpers = require('../helpers');
const db = require('../db/models');
const passport = require('passport');
const JWTstrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJwt;
const GoogleStrategy = require('passport-google-oauth2').Strategy;
const MicrosoftStrategy = require('passport-microsoft').Strategy;
const UsersDBApi = require('../db/api/users');
passport.use(new JWTstrategy({
passReqToCallback: true,
secretOrKey: config.secret_key,
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken()
}, async (req, token, done) => {
try {
const user = await UsersDBApi.findBy( {email: token.user.email});
if (user && user.disabled) {
return done (new Error(`User '${user.email}' is disabled`));
}
req.currentUser = user;
return done(null, user);
} catch (error) {
done(error);
}
}));
passport.use(new GoogleStrategy({
clientID: config.google.clientId,
clientSecret: config.google.clientSecret,
callbackURL: config.apiUrl + '/auth/signin/google/callback',
passReqToCallback: true
},
function (request, accessToken, refreshToken, profile, done) {
socialStrategy(profile.email, profile, providers.GOOGLE, done);
}
));
passport.use(new MicrosoftStrategy({
clientID: config.microsoft.clientId,
clientSecret: config.microsoft.clientSecret,
callbackURL: config.apiUrl + '/auth/signin/microsoft/callback',
passReqToCallback: true
},
function (request, accessToken, refreshToken, profile, done) {
const email = profile._json.mail || profile._json.userPrincipalName;
socialStrategy(email, profile, providers.MICROSOFT, done);
}
));
function socialStrategy(email, profile, provider, done) {
db.users.findOrCreate({where: {email, provider}}).then(([user, created]) => {
const body = {
id: user.id,
email: user.email,
name: profile.displayName,
};
const token = helpers.jwtSign({user: body});
return done(null, {token});
});
}

79
backend/src/config.js Normal file
View File

@ -0,0 +1,79 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "48a92208",
user_pass: "4f214eaf4308",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '48a92208-a252-4371-b6a4-4f214eaf4308',
remote: '',
port: process.env.NODE_ENV === "production" ? "" : "8080",
hostUI: process.env.NODE_ENV === "production" ? "" : "http://localhost",
portUI: process.env.NODE_ENV === "production" ? "" : "3000",
portUIProd: process.env.NODE_ENV === "production" ? "" : ":3000",
swaggerUI: process.env.NODE_ENV === "production" ? "" : "http://localhost",
swaggerPort: process.env.NODE_ENV === "production" ? "" : ":8080",
google: {
clientId: process.env.GOOGLE_CLIENT_ID || '',
clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
},
microsoft: {
clientId: process.env.MS_CLIENT_ID || '',
clientSecret: process.env.MS_CLIENT_SECRET || '',
},
uploadDir: os.tmpdir(),
email: {
from: 'SMPN 1 Seponti Digital <app@flatlogic.app>',
host: 'email-smtp.us-east-1.amazonaws.com',
port: 587,
auth: {
user: process.env.EMAIL_USER || '',
pass: process.env.EMAIL_PASS,
},
tls: {
rejectUnauthorized: false
}
},
roles: {
admin: 'Administrator',
user: 'Subject Teacher',
},
project_uuid: '48a92208-a252-4371-b6a4-4f214eaf4308',
flHost: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'dev_stage' ? 'https://flatlogic.com/projects' : 'http://localhost:3000/projects',
gpt_key: process.env.GPT_KEY || '',
};
config.pexelsKey = process.env.PEXELS_KEY || '';
config.pexelsQuery = 'Sunrise over mountain landscape';
config.host = process.env.NODE_ENV === "production" ? config.remote : "http://localhost";
config.apiUrl = `${config.host}${config.port ? `:${config.port}` : ``}/api`;
config.swaggerUrl = `${config.swaggerUI}${config.swaggerPort}`;
config.uiUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}/#`;
config.backUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}`;
module.exports = config;

View File

@ -0,0 +1,515 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class AbsensiDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const absensi = await db.absensi.create(
{
id: data.id || undefined,
tanggal: data.tanggal
||
null
,
status: data.status
||
null
,
keterangan: data.keterangan
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await absensi.setKelas( data.kelas || null, {
transaction,
});
await absensi.setSiswa( data.siswa || null, {
transaction,
});
await absensi.setDicatat_oleh( data.dicatat_oleh || null, {
transaction,
});
return absensi;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const absensiData = data.map((item, index) => ({
id: item.id || undefined,
tanggal: item.tanggal
||
null
,
status: item.status
||
null
,
keterangan: item.keterangan
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const absensi = await db.absensi.bulkCreate(absensiData, { transaction });
// For each item created, replace relation files
return absensi;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const absensi = await db.absensi.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.tanggal !== undefined) updatePayload.tanggal = data.tanggal;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.keterangan !== undefined) updatePayload.keterangan = data.keterangan;
updatePayload.updatedById = currentUser.id;
await absensi.update(updatePayload, {transaction});
if (data.kelas !== undefined) {
await absensi.setKelas(
data.kelas,
{ transaction }
);
}
if (data.siswa !== undefined) {
await absensi.setSiswa(
data.siswa,
{ transaction }
);
}
if (data.dicatat_oleh !== undefined) {
await absensi.setDicatat_oleh(
data.dicatat_oleh,
{ transaction }
);
}
return absensi;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const absensi = await db.absensi.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of absensi) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of absensi) {
await record.destroy({transaction});
}
});
return absensi;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const absensi = await db.absensi.findByPk(id, options);
await absensi.update({
deletedBy: currentUser.id
}, {
transaction,
});
await absensi.destroy({
transaction
});
return absensi;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const absensi = await db.absensi.findOne(
{ where },
{ transaction },
);
if (!absensi) {
return absensi;
}
const output = absensi.get({plain: true});
output.kelas = await absensi.getKelas({
transaction
});
output.siswa = await absensi.getSiswa({
transaction
});
output.dicatat_oleh = await absensi.getDicatat_oleh({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.kelas,
as: 'kelas',
where: filter.kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.kelas.split('|').map(term => Utils.uuid(term)) } },
{
nama_kelas: {
[Op.or]: filter.kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.siswa,
as: 'siswa',
where: filter.siswa ? {
[Op.or]: [
{ id: { [Op.in]: filter.siswa.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.siswa.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'dicatat_oleh',
where: filter.dicatat_oleh ? {
[Op.or]: [
{ id: { [Op.in]: filter.dicatat_oleh.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.dicatat_oleh.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.keterangan) {
where = {
...where,
[Op.and]: Utils.ilike(
'absensi',
'keterangan',
filter.keterangan,
),
};
}
if (filter.tanggalRange) {
const [start, end] = filter.tanggalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tanggal: {
...where.tanggal,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tanggal: {
...where.tanggal,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.absensi.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'absensi',
'keterangan',
query,
),
],
};
}
const records = await db.absensi.findAll({
attributes: [ 'id', 'keterangan' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['keterangan', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.keterangan,
}));
}
};

View File

@ -0,0 +1,576 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Ai_insightsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_insights = await db.ai_insights.create(
{
id: data.id || undefined,
jenis: data.jenis
||
null
,
skor_keyakinan: data.skor_keyakinan
||
null
,
ringkasan: data.ringkasan
||
null
,
rekomendasi: data.rekomendasi
||
null
,
generated_at: data.generated_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_insights.setSiswa( data.siswa || null, {
transaction,
});
await ai_insights.setKelas( data.kelas || null, {
transaction,
});
await ai_insights.setGenerated_by( data.generated_by || null, {
transaction,
});
return ai_insights;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const ai_insightsData = data.map((item, index) => ({
id: item.id || undefined,
jenis: item.jenis
||
null
,
skor_keyakinan: item.skor_keyakinan
||
null
,
ringkasan: item.ringkasan
||
null
,
rekomendasi: item.rekomendasi
||
null
,
generated_at: item.generated_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ai_insights = await db.ai_insights.bulkCreate(ai_insightsData, { transaction });
// For each item created, replace relation files
return ai_insights;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_insights = await db.ai_insights.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.jenis !== undefined) updatePayload.jenis = data.jenis;
if (data.skor_keyakinan !== undefined) updatePayload.skor_keyakinan = data.skor_keyakinan;
if (data.ringkasan !== undefined) updatePayload.ringkasan = data.ringkasan;
if (data.rekomendasi !== undefined) updatePayload.rekomendasi = data.rekomendasi;
if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
updatePayload.updatedById = currentUser.id;
await ai_insights.update(updatePayload, {transaction});
if (data.siswa !== undefined) {
await ai_insights.setSiswa(
data.siswa,
{ transaction }
);
}
if (data.kelas !== undefined) {
await ai_insights.setKelas(
data.kelas,
{ transaction }
);
}
if (data.generated_by !== undefined) {
await ai_insights.setGenerated_by(
data.generated_by,
{ transaction }
);
}
return ai_insights;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_insights = await db.ai_insights.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ai_insights) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ai_insights) {
await record.destroy({transaction});
}
});
return ai_insights;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_insights = await db.ai_insights.findByPk(id, options);
await ai_insights.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ai_insights.destroy({
transaction
});
return ai_insights;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ai_insights = await db.ai_insights.findOne(
{ where },
{ transaction },
);
if (!ai_insights) {
return ai_insights;
}
const output = ai_insights.get({plain: true});
output.siswa = await ai_insights.getSiswa({
transaction
});
output.kelas = await ai_insights.getKelas({
transaction
});
output.generated_by = await ai_insights.getGenerated_by({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.siswa,
as: 'siswa',
where: filter.siswa ? {
[Op.or]: [
{ id: { [Op.in]: filter.siswa.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.siswa.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.kelas,
as: 'kelas',
where: filter.kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.kelas.split('|').map(term => Utils.uuid(term)) } },
{
nama_kelas: {
[Op.or]: filter.kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'generated_by',
where: filter.generated_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.generated_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.generated_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.ringkasan) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_insights',
'ringkasan',
filter.ringkasan,
),
};
}
if (filter.rekomendasi) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_insights',
'rekomendasi',
filter.rekomendasi,
),
};
}
if (filter.skor_keyakinanRange) {
const [start, end] = filter.skor_keyakinanRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
skor_keyakinan: {
...where.skor_keyakinan,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
skor_keyakinan: {
...where.skor_keyakinan,
[Op.lte]: end,
},
};
}
}
if (filter.generated_atRange) {
const [start, end] = filter.generated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
generated_at: {
...where.generated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
generated_at: {
...where.generated_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.jenis) {
where = {
...where,
jenis: filter.jenis,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.ai_insights.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'ai_insights',
'ringkasan',
query,
),
],
};
}
const records = await db.ai_insights.findAll({
attributes: [ 'id', 'ringkasan' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['ringkasan', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.ringkasan,
}));
}
};

View File

@ -0,0 +1,537 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Audit_logsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.create(
{
id: data.id || undefined,
action: data.action
||
null
,
entity_name: data.entity_name
||
null
,
entity_key: data.entity_key
||
null
,
summary: data.summary
||
null
,
ip_address: data.ip_address
||
null
,
user_agent: data.user_agent
||
null
,
logged_at: data.logged_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audit_logs.setActor( data.actor || null, {
transaction,
});
return audit_logs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const audit_logsData = data.map((item, index) => ({
id: item.id || undefined,
action: item.action
||
null
,
entity_name: item.entity_name
||
null
,
entity_key: item.entity_key
||
null
,
summary: item.summary
||
null
,
ip_address: item.ip_address
||
null
,
user_agent: item.user_agent
||
null
,
logged_at: item.logged_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const audit_logs = await db.audit_logs.bulkCreate(audit_logsData, { transaction });
// For each item created, replace relation files
return audit_logs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.action !== undefined) updatePayload.action = data.action;
if (data.entity_name !== undefined) updatePayload.entity_name = data.entity_name;
if (data.entity_key !== undefined) updatePayload.entity_key = data.entity_key;
if (data.summary !== undefined) updatePayload.summary = data.summary;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
if (data.logged_at !== undefined) updatePayload.logged_at = data.logged_at;
updatePayload.updatedById = currentUser.id;
await audit_logs.update(updatePayload, {transaction});
if (data.actor !== undefined) {
await audit_logs.setActor(
data.actor,
{ transaction }
);
}
return audit_logs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of audit_logs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of audit_logs) {
await record.destroy({transaction});
}
});
return audit_logs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findByPk(id, options);
await audit_logs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await audit_logs.destroy({
transaction
});
return audit_logs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findOne(
{ where },
{ transaction },
);
if (!audit_logs) {
return audit_logs;
}
const output = audit_logs.get({plain: true});
output.actor = await audit_logs.getActor({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'actor',
where: filter.actor ? {
[Op.or]: [
{ id: { [Op.in]: filter.actor.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.actor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.entity_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'entity_name',
filter.entity_name,
),
};
}
if (filter.entity_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'entity_key',
filter.entity_key,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'summary',
filter.summary,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'ip_address',
filter.ip_address,
),
};
}
if (filter.user_agent) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'user_agent',
filter.user_agent,
),
};
}
if (filter.logged_atRange) {
const [start, end] = filter.logged_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
logged_at: {
...where.logged_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
logged_at: {
...where.logged_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.action) {
where = {
...where,
action: filter.action,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.audit_logs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'audit_logs',
'entity_name',
query,
),
],
};
}
const records = await db.audit_logs.findAll({
attributes: [ 'id', 'entity_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['entity_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.entity_name,
}));
}
};

View File

@ -0,0 +1,87 @@
const db = require('../models');
const assert = require('assert');
const services = require('../../services/file');
module.exports = class FileDBApi {
static async replaceRelationFiles(
relation,
rawFiles,
options,
) {
assert(relation.belongsTo, 'belongsTo is required');
assert(
relation.belongsToColumn,
'belongsToColumn is required',
);
assert(relation.belongsToId, 'belongsToId is required');
let files = [];
if (Array.isArray(rawFiles)) {
files = rawFiles;
} else {
files = rawFiles ? [rawFiles] : [];
}
await this._removeLegacyFiles(relation, files, options);
await this._addFiles(relation, files, options);
}
static async _addFiles(relation, files, options) {
const transaction = (options && options.transaction) || undefined;
const currentUser = (options && options.currentUser) || {id: null};
const inexistentFiles = files.filter(
(file) => !!file.new,
);
for (const file of inexistentFiles) {
await db.file.create(
{
belongsTo: relation.belongsTo,
belongsToColumn: relation.belongsToColumn,
belongsToId: relation.belongsToId,
name: file.name,
sizeInBytes: file.sizeInBytes,
privateUrl: file.privateUrl,
publicUrl: file.publicUrl,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{
transaction,
},
);
}
}
static async _removeLegacyFiles(
relation,
files,
options,
) {
const transaction = (options && options.transaction) || undefined;
const filesToDelete = await db.file.findAll({
where: {
belongsTo: relation.belongsTo,
belongsToId: relation.belongsToId,
belongsToColumn: relation.belongsToColumn,
id: {
[db.Sequelize.Op
.notIn]: files
.filter((file) => !file.new)
.map((file) => file.id)
},
},
transaction,
});
for (let file of filesToDelete) {
await services.deleteGCloud(file.privateUrl);
await file.destroy({
transaction,
});
}
}
};

583
backend/src/db/api/guru.js Normal file
View File

@ -0,0 +1,583 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class GuruDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const guru = await db.guru.create(
{
id: data.id || undefined,
nip: data.nip
||
null
,
nama: data.nama
||
null
,
jenis_kelamin: data.jenis_kelamin
||
null
,
tempat_lahir: data.tempat_lahir
||
null
,
tanggal_lahir: data.tanggal_lahir
||
null
,
alamat: data.alamat
||
null
,
no_hp: data.no_hp
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await guru.setUser( data.user || null, {
transaction,
});
return guru;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const guruData = data.map((item, index) => ({
id: item.id || undefined,
nip: item.nip
||
null
,
nama: item.nama
||
null
,
jenis_kelamin: item.jenis_kelamin
||
null
,
tempat_lahir: item.tempat_lahir
||
null
,
tanggal_lahir: item.tanggal_lahir
||
null
,
alamat: item.alamat
||
null
,
no_hp: item.no_hp
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const guru = await db.guru.bulkCreate(guruData, { transaction });
// For each item created, replace relation files
return guru;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const guru = await db.guru.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.nip !== undefined) updatePayload.nip = data.nip;
if (data.nama !== undefined) updatePayload.nama = data.nama;
if (data.jenis_kelamin !== undefined) updatePayload.jenis_kelamin = data.jenis_kelamin;
if (data.tempat_lahir !== undefined) updatePayload.tempat_lahir = data.tempat_lahir;
if (data.tanggal_lahir !== undefined) updatePayload.tanggal_lahir = data.tanggal_lahir;
if (data.alamat !== undefined) updatePayload.alamat = data.alamat;
if (data.no_hp !== undefined) updatePayload.no_hp = data.no_hp;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await guru.update(updatePayload, {transaction});
if (data.user !== undefined) {
await guru.setUser(
data.user,
{ transaction }
);
}
return guru;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const guru = await db.guru.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of guru) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of guru) {
await record.destroy({transaction});
}
});
return guru;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const guru = await db.guru.findByPk(id, options);
await guru.update({
deletedBy: currentUser.id
}, {
transaction,
});
await guru.destroy({
transaction
});
return guru;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const guru = await db.guru.findOne(
{ where },
{ transaction },
);
if (!guru) {
return guru;
}
const output = guru.get({plain: true});
output.mata_pelajaran_guru_pengampu = await guru.getMata_pelajaran_guru_pengampu({
transaction
});
output.nilai_guru_penginput = await guru.getNilai_guru_penginput({
transaction
});
output.materi_guru = await guru.getMateri_guru({
transaction
});
output.tugas_guru = await guru.getTugas_guru({
transaction
});
output.pengumpulan_tugas_dinilai_oleh = await guru.getPengumpulan_tugas_dinilai_oleh({
transaction
});
output.user = await guru.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.nip) {
where = {
...where,
[Op.and]: Utils.ilike(
'guru',
'nip',
filter.nip,
),
};
}
if (filter.nama) {
where = {
...where,
[Op.and]: Utils.ilike(
'guru',
'nama',
filter.nama,
),
};
}
if (filter.jenis_kelamin) {
where = {
...where,
[Op.and]: Utils.ilike(
'guru',
'jenis_kelamin',
filter.jenis_kelamin,
),
};
}
if (filter.tempat_lahir) {
where = {
...where,
[Op.and]: Utils.ilike(
'guru',
'tempat_lahir',
filter.tempat_lahir,
),
};
}
if (filter.alamat) {
where = {
...where,
[Op.and]: Utils.ilike(
'guru',
'alamat',
filter.alamat,
),
};
}
if (filter.no_hp) {
where = {
...where,
[Op.and]: Utils.ilike(
'guru',
'no_hp',
filter.no_hp,
),
};
}
if (filter.tanggal_lahirRange) {
const [start, end] = filter.tanggal_lahirRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tanggal_lahir: {
...where.tanggal_lahir,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tanggal_lahir: {
...where.tanggal_lahir,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.guru.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'guru',
'nama',
query,
),
],
};
}
const records = await db.guru.findAll({
attributes: [ 'id', 'nama' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['nama', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.nama,
}));
}
};

View File

@ -0,0 +1,651 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Import_jobsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const import_jobs = await db.import_jobs.create(
{
id: data.id || undefined,
jenis: data.jenis
||
null
,
status: data.status
||
null
,
total_rows: data.total_rows
||
null
,
success_rows: data.success_rows
||
null
,
failed_rows: data.failed_rows
||
null
,
error_report: data.error_report
||
null
,
started_at: data.started_at
||
null
,
finished_at: data.finished_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await import_jobs.setRequested_by( data.requested_by || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.import_jobs.getTableName(),
belongsToColumn: 'file_excel',
belongsToId: import_jobs.id,
},
data.file_excel,
options,
);
return import_jobs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const import_jobsData = data.map((item, index) => ({
id: item.id || undefined,
jenis: item.jenis
||
null
,
status: item.status
||
null
,
total_rows: item.total_rows
||
null
,
success_rows: item.success_rows
||
null
,
failed_rows: item.failed_rows
||
null
,
error_report: item.error_report
||
null
,
started_at: item.started_at
||
null
,
finished_at: item.finished_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const import_jobs = await db.import_jobs.bulkCreate(import_jobsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < import_jobs.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.import_jobs.getTableName(),
belongsToColumn: 'file_excel',
belongsToId: import_jobs[i].id,
},
data[i].file_excel,
options,
);
}
return import_jobs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const import_jobs = await db.import_jobs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.jenis !== undefined) updatePayload.jenis = data.jenis;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.total_rows !== undefined) updatePayload.total_rows = data.total_rows;
if (data.success_rows !== undefined) updatePayload.success_rows = data.success_rows;
if (data.failed_rows !== undefined) updatePayload.failed_rows = data.failed_rows;
if (data.error_report !== undefined) updatePayload.error_report = data.error_report;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
updatePayload.updatedById = currentUser.id;
await import_jobs.update(updatePayload, {transaction});
if (data.requested_by !== undefined) {
await import_jobs.setRequested_by(
data.requested_by,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.import_jobs.getTableName(),
belongsToColumn: 'file_excel',
belongsToId: import_jobs.id,
},
data.file_excel,
options,
);
return import_jobs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const import_jobs = await db.import_jobs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of import_jobs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of import_jobs) {
await record.destroy({transaction});
}
});
return import_jobs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const import_jobs = await db.import_jobs.findByPk(id, options);
await import_jobs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await import_jobs.destroy({
transaction
});
return import_jobs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const import_jobs = await db.import_jobs.findOne(
{ where },
{ transaction },
);
if (!import_jobs) {
return import_jobs;
}
const output = import_jobs.get({plain: true});
output.file_excel = await import_jobs.getFile_excel({
transaction
});
output.requested_by = await import_jobs.getRequested_by({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'file_excel',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.error_report) {
where = {
...where,
[Op.and]: Utils.ilike(
'import_jobs',
'error_report',
filter.error_report,
),
};
}
if (filter.total_rowsRange) {
const [start, end] = filter.total_rowsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_rows: {
...where.total_rows,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_rows: {
...where.total_rows,
[Op.lte]: end,
},
};
}
}
if (filter.success_rowsRange) {
const [start, end] = filter.success_rowsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
success_rows: {
...where.success_rows,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
success_rows: {
...where.success_rows,
[Op.lte]: end,
},
};
}
}
if (filter.failed_rowsRange) {
const [start, end] = filter.failed_rowsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
failed_rows: {
...where.failed_rows,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
failed_rows: {
...where.failed_rows,
[Op.lte]: end,
},
};
}
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.finished_atRange) {
const [start, end] = filter.finished_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.jenis) {
where = {
...where,
jenis: filter.jenis,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.import_jobs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'import_jobs',
'jenis',
query,
),
],
};
}
const records = await db.import_jobs.findAll({
attributes: [ 'id', 'jenis' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['jenis', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.jenis,
}));
}
};

492
backend/src/db/api/kelas.js Normal file
View File

@ -0,0 +1,492 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class KelasDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const kelas = await db.kelas.create(
{
id: data.id || undefined,
nama_kelas: data.nama_kelas
||
null
,
tingkat: data.tingkat
||
null
,
tahun_ajaran: data.tahun_ajaran
||
null
,
semester: data.semester
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await kelas.setWali_kelas( data.wali_kelas || null, {
transaction,
});
return kelas;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const kelasData = data.map((item, index) => ({
id: item.id || undefined,
nama_kelas: item.nama_kelas
||
null
,
tingkat: item.tingkat
||
null
,
tahun_ajaran: item.tahun_ajaran
||
null
,
semester: item.semester
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const kelas = await db.kelas.bulkCreate(kelasData, { transaction });
// For each item created, replace relation files
return kelas;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const kelas = await db.kelas.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.nama_kelas !== undefined) updatePayload.nama_kelas = data.nama_kelas;
if (data.tingkat !== undefined) updatePayload.tingkat = data.tingkat;
if (data.tahun_ajaran !== undefined) updatePayload.tahun_ajaran = data.tahun_ajaran;
if (data.semester !== undefined) updatePayload.semester = data.semester;
updatePayload.updatedById = currentUser.id;
await kelas.update(updatePayload, {transaction});
if (data.wali_kelas !== undefined) {
await kelas.setWali_kelas(
data.wali_kelas,
{ transaction }
);
}
return kelas;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const kelas = await db.kelas.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of kelas) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of kelas) {
await record.destroy({transaction});
}
});
return kelas;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const kelas = await db.kelas.findByPk(id, options);
await kelas.update({
deletedBy: currentUser.id
}, {
transaction,
});
await kelas.destroy({
transaction
});
return kelas;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const kelas = await db.kelas.findOne(
{ where },
{ transaction },
);
if (!kelas) {
return kelas;
}
const output = kelas.get({plain: true});
output.siswa_kelas = await kelas.getSiswa_kelas({
transaction
});
output.kktp_kelas = await kelas.getKktp_kelas({
transaction
});
output.nilai_kelas = await kelas.getNilai_kelas({
transaction
});
output.sikap_kelas = await kelas.getSikap_kelas({
transaction
});
output.materi_kelas = await kelas.getMateri_kelas({
transaction
});
output.tugas_kelas = await kelas.getTugas_kelas({
transaction
});
output.absensi_kelas = await kelas.getAbsensi_kelas({
transaction
});
output.pengumuman_kelas = await kelas.getPengumuman_kelas({
transaction
});
output.ai_insights_kelas = await kelas.getAi_insights_kelas({
transaction
});
output.raport_descriptions_kelas = await kelas.getRaport_descriptions_kelas({
transaction
});
output.wali_kelas = await kelas.getWali_kelas({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'wali_kelas',
where: filter.wali_kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.wali_kelas.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.wali_kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.nama_kelas) {
where = {
...where,
[Op.and]: Utils.ilike(
'kelas',
'nama_kelas',
filter.nama_kelas,
),
};
}
if (filter.tingkat) {
where = {
...where,
[Op.and]: Utils.ilike(
'kelas',
'tingkat',
filter.tingkat,
),
};
}
if (filter.tahun_ajaran) {
where = {
...where,
[Op.and]: Utils.ilike(
'kelas',
'tahun_ajaran',
filter.tahun_ajaran,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.semester) {
where = {
...where,
semester: filter.semester,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.kelas.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'kelas',
'nama_kelas',
query,
),
],
};
}
const records = await db.kelas.findAll({
attributes: [ 'id', 'nama_kelas' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['nama_kelas', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.nama_kelas,
}));
}
};

508
backend/src/db/api/kktp.js Normal file
View File

@ -0,0 +1,508 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class KktpDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const kktp = await db.kktp.create(
{
id: data.id || undefined,
fase: data.fase
||
null
,
nilai_minimum: data.nilai_minimum
||
null
,
deskripsi_umum: data.deskripsi_umum
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await kktp.setMata_pelajaran( data.mata_pelajaran || null, {
transaction,
});
await kktp.setKelas( data.kelas || null, {
transaction,
});
return kktp;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const kktpData = data.map((item, index) => ({
id: item.id || undefined,
fase: item.fase
||
null
,
nilai_minimum: item.nilai_minimum
||
null
,
deskripsi_umum: item.deskripsi_umum
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const kktp = await db.kktp.bulkCreate(kktpData, { transaction });
// For each item created, replace relation files
return kktp;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const kktp = await db.kktp.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.fase !== undefined) updatePayload.fase = data.fase;
if (data.nilai_minimum !== undefined) updatePayload.nilai_minimum = data.nilai_minimum;
if (data.deskripsi_umum !== undefined) updatePayload.deskripsi_umum = data.deskripsi_umum;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await kktp.update(updatePayload, {transaction});
if (data.mata_pelajaran !== undefined) {
await kktp.setMata_pelajaran(
data.mata_pelajaran,
{ transaction }
);
}
if (data.kelas !== undefined) {
await kktp.setKelas(
data.kelas,
{ transaction }
);
}
return kktp;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const kktp = await db.kktp.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of kktp) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of kktp) {
await record.destroy({transaction});
}
});
return kktp;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const kktp = await db.kktp.findByPk(id, options);
await kktp.update({
deletedBy: currentUser.id
}, {
transaction,
});
await kktp.destroy({
transaction
});
return kktp;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const kktp = await db.kktp.findOne(
{ where },
{ transaction },
);
if (!kktp) {
return kktp;
}
const output = kktp.get({plain: true});
output.kktp_detail_kktp = await kktp.getKktp_detail_kktp({
transaction
});
output.mata_pelajaran = await kktp.getMata_pelajaran({
transaction
});
output.kelas = await kktp.getKelas({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.mata_pelajaran,
as: 'mata_pelajaran',
where: filter.mata_pelajaran ? {
[Op.or]: [
{ id: { [Op.in]: filter.mata_pelajaran.split('|').map(term => Utils.uuid(term)) } },
{
nama_mapel: {
[Op.or]: filter.mata_pelajaran.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.kelas,
as: 'kelas',
where: filter.kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.kelas.split('|').map(term => Utils.uuid(term)) } },
{
nama_kelas: {
[Op.or]: filter.kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.fase) {
where = {
...where,
[Op.and]: Utils.ilike(
'kktp',
'fase',
filter.fase,
),
};
}
if (filter.deskripsi_umum) {
where = {
...where,
[Op.and]: Utils.ilike(
'kktp',
'deskripsi_umum',
filter.deskripsi_umum,
),
};
}
if (filter.nilai_minimumRange) {
const [start, end] = filter.nilai_minimumRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
nilai_minimum: {
...where.nilai_minimum,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
nilai_minimum: {
...where.nilai_minimum,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.kktp.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'kktp',
'fase',
query,
),
],
};
}
const records = await db.kktp.findAll({
attributes: [ 'id', 'fase' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['fase', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.fase,
}));
}
};

View File

@ -0,0 +1,478 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Kktp_detailDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const kktp_detail = await db.kktp_detail.create(
{
id: data.id || undefined,
predikat: data.predikat
||
null
,
nilai_min: data.nilai_min
||
null
,
nilai_max: data.nilai_max
||
null
,
deskripsi: data.deskripsi
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await kktp_detail.setKktp( data.kktp || null, {
transaction,
});
return kktp_detail;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const kktp_detailData = data.map((item, index) => ({
id: item.id || undefined,
predikat: item.predikat
||
null
,
nilai_min: item.nilai_min
||
null
,
nilai_max: item.nilai_max
||
null
,
deskripsi: item.deskripsi
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const kktp_detail = await db.kktp_detail.bulkCreate(kktp_detailData, { transaction });
// For each item created, replace relation files
return kktp_detail;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const kktp_detail = await db.kktp_detail.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.predikat !== undefined) updatePayload.predikat = data.predikat;
if (data.nilai_min !== undefined) updatePayload.nilai_min = data.nilai_min;
if (data.nilai_max !== undefined) updatePayload.nilai_max = data.nilai_max;
if (data.deskripsi !== undefined) updatePayload.deskripsi = data.deskripsi;
updatePayload.updatedById = currentUser.id;
await kktp_detail.update(updatePayload, {transaction});
if (data.kktp !== undefined) {
await kktp_detail.setKktp(
data.kktp,
{ transaction }
);
}
return kktp_detail;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const kktp_detail = await db.kktp_detail.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of kktp_detail) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of kktp_detail) {
await record.destroy({transaction});
}
});
return kktp_detail;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const kktp_detail = await db.kktp_detail.findByPk(id, options);
await kktp_detail.update({
deletedBy: currentUser.id
}, {
transaction,
});
await kktp_detail.destroy({
transaction
});
return kktp_detail;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const kktp_detail = await db.kktp_detail.findOne(
{ where },
{ transaction },
);
if (!kktp_detail) {
return kktp_detail;
}
const output = kktp_detail.get({plain: true});
output.kktp = await kktp_detail.getKktp({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.kktp,
as: 'kktp',
where: filter.kktp ? {
[Op.or]: [
{ id: { [Op.in]: filter.kktp.split('|').map(term => Utils.uuid(term)) } },
{
fase: {
[Op.or]: filter.kktp.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.deskripsi) {
where = {
...where,
[Op.and]: Utils.ilike(
'kktp_detail',
'deskripsi',
filter.deskripsi,
),
};
}
if (filter.nilai_minRange) {
const [start, end] = filter.nilai_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
nilai_min: {
...where.nilai_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
nilai_min: {
...where.nilai_min,
[Op.lte]: end,
},
};
}
}
if (filter.nilai_maxRange) {
const [start, end] = filter.nilai_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
nilai_max: {
...where.nilai_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
nilai_max: {
...where.nilai_max,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.predikat) {
where = {
...where,
predikat: filter.predikat,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.kktp_detail.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'kktp_detail',
'deskripsi',
query,
),
],
};
}
const records = await db.kktp_detail.findAll({
attributes: [ 'id', 'deskripsi' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['deskripsi', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.deskripsi,
}));
}
};

View File

@ -0,0 +1,507 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Mata_pelajaranDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mata_pelajaran = await db.mata_pelajaran.create(
{
id: data.id || undefined,
kode_mapel: data.kode_mapel
||
null
,
nama_mapel: data.nama_mapel
||
null
,
kelompok: data.kelompok
||
null
,
urutan: data.urutan
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await mata_pelajaran.setGuru_pengampu( data.guru_pengampu || null, {
transaction,
});
return mata_pelajaran;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const mata_pelajaranData = data.map((item, index) => ({
id: item.id || undefined,
kode_mapel: item.kode_mapel
||
null
,
nama_mapel: item.nama_mapel
||
null
,
kelompok: item.kelompok
||
null
,
urutan: item.urutan
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const mata_pelajaran = await db.mata_pelajaran.bulkCreate(mata_pelajaranData, { transaction });
// For each item created, replace relation files
return mata_pelajaran;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mata_pelajaran = await db.mata_pelajaran.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.kode_mapel !== undefined) updatePayload.kode_mapel = data.kode_mapel;
if (data.nama_mapel !== undefined) updatePayload.nama_mapel = data.nama_mapel;
if (data.kelompok !== undefined) updatePayload.kelompok = data.kelompok;
if (data.urutan !== undefined) updatePayload.urutan = data.urutan;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await mata_pelajaran.update(updatePayload, {transaction});
if (data.guru_pengampu !== undefined) {
await mata_pelajaran.setGuru_pengampu(
data.guru_pengampu,
{ transaction }
);
}
return mata_pelajaran;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mata_pelajaran = await db.mata_pelajaran.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of mata_pelajaran) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of mata_pelajaran) {
await record.destroy({transaction});
}
});
return mata_pelajaran;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mata_pelajaran = await db.mata_pelajaran.findByPk(id, options);
await mata_pelajaran.update({
deletedBy: currentUser.id
}, {
transaction,
});
await mata_pelajaran.destroy({
transaction
});
return mata_pelajaran;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const mata_pelajaran = await db.mata_pelajaran.findOne(
{ where },
{ transaction },
);
if (!mata_pelajaran) {
return mata_pelajaran;
}
const output = mata_pelajaran.get({plain: true});
output.kktp_mata_pelajaran = await mata_pelajaran.getKktp_mata_pelajaran({
transaction
});
output.nilai_mata_pelajaran = await mata_pelajaran.getNilai_mata_pelajaran({
transaction
});
output.materi_mata_pelajaran = await mata_pelajaran.getMateri_mata_pelajaran({
transaction
});
output.tugas_mata_pelajaran = await mata_pelajaran.getTugas_mata_pelajaran({
transaction
});
output.raport_descriptions_mata_pelajaran = await mata_pelajaran.getRaport_descriptions_mata_pelajaran({
transaction
});
output.guru_pengampu = await mata_pelajaran.getGuru_pengampu({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.guru,
as: 'guru_pengampu',
where: filter.guru_pengampu ? {
[Op.or]: [
{ id: { [Op.in]: filter.guru_pengampu.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.guru_pengampu.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.kode_mapel) {
where = {
...where,
[Op.and]: Utils.ilike(
'mata_pelajaran',
'kode_mapel',
filter.kode_mapel,
),
};
}
if (filter.nama_mapel) {
where = {
...where,
[Op.and]: Utils.ilike(
'mata_pelajaran',
'nama_mapel',
filter.nama_mapel,
),
};
}
if (filter.urutanRange) {
const [start, end] = filter.urutanRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
urutan: {
...where.urutan,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
urutan: {
...where.urutan,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.kelompok) {
where = {
...where,
kelompok: filter.kelompok,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.mata_pelajaran.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'mata_pelajaran',
'nama_mapel',
query,
),
],
};
}
const records = await db.mata_pelajaran.findAll({
attributes: [ 'id', 'nama_mapel' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['nama_mapel', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.nama_mapel,
}));
}
};

View File

@ -0,0 +1,627 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class MateriDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const materi = await db.materi.create(
{
id: data.id || undefined,
judul: data.judul
||
null
,
deskripsi: data.deskripsi
||
null
,
tipe_konten: data.tipe_konten
||
null
,
url_video: data.url_video
||
null
,
published_at: data.published_at
||
null
,
is_published: data.is_published
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await materi.setMata_pelajaran( data.mata_pelajaran || null, {
transaction,
});
await materi.setKelas( data.kelas || null, {
transaction,
});
await materi.setGuru( data.guru || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.materi.getTableName(),
belongsToColumn: 'lampiran',
belongsToId: materi.id,
},
data.lampiran,
options,
);
return materi;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const materiData = data.map((item, index) => ({
id: item.id || undefined,
judul: item.judul
||
null
,
deskripsi: item.deskripsi
||
null
,
tipe_konten: item.tipe_konten
||
null
,
url_video: item.url_video
||
null
,
published_at: item.published_at
||
null
,
is_published: item.is_published
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const materi = await db.materi.bulkCreate(materiData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < materi.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.materi.getTableName(),
belongsToColumn: 'lampiran',
belongsToId: materi[i].id,
},
data[i].lampiran,
options,
);
}
return materi;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const materi = await db.materi.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.judul !== undefined) updatePayload.judul = data.judul;
if (data.deskripsi !== undefined) updatePayload.deskripsi = data.deskripsi;
if (data.tipe_konten !== undefined) updatePayload.tipe_konten = data.tipe_konten;
if (data.url_video !== undefined) updatePayload.url_video = data.url_video;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
updatePayload.updatedById = currentUser.id;
await materi.update(updatePayload, {transaction});
if (data.mata_pelajaran !== undefined) {
await materi.setMata_pelajaran(
data.mata_pelajaran,
{ transaction }
);
}
if (data.kelas !== undefined) {
await materi.setKelas(
data.kelas,
{ transaction }
);
}
if (data.guru !== undefined) {
await materi.setGuru(
data.guru,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.materi.getTableName(),
belongsToColumn: 'lampiran',
belongsToId: materi.id,
},
data.lampiran,
options,
);
return materi;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const materi = await db.materi.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of materi) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of materi) {
await record.destroy({transaction});
}
});
return materi;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const materi = await db.materi.findByPk(id, options);
await materi.update({
deletedBy: currentUser.id
}, {
transaction,
});
await materi.destroy({
transaction
});
return materi;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const materi = await db.materi.findOne(
{ where },
{ transaction },
);
if (!materi) {
return materi;
}
const output = materi.get({plain: true});
output.mata_pelajaran = await materi.getMata_pelajaran({
transaction
});
output.kelas = await materi.getKelas({
transaction
});
output.guru = await materi.getGuru({
transaction
});
output.lampiran = await materi.getLampiran({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.mata_pelajaran,
as: 'mata_pelajaran',
where: filter.mata_pelajaran ? {
[Op.or]: [
{ id: { [Op.in]: filter.mata_pelajaran.split('|').map(term => Utils.uuid(term)) } },
{
nama_mapel: {
[Op.or]: filter.mata_pelajaran.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.kelas,
as: 'kelas',
where: filter.kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.kelas.split('|').map(term => Utils.uuid(term)) } },
{
nama_kelas: {
[Op.or]: filter.kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.guru,
as: 'guru',
where: filter.guru ? {
[Op.or]: [
{ id: { [Op.in]: filter.guru.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.guru.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'lampiran',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.judul) {
where = {
...where,
[Op.and]: Utils.ilike(
'materi',
'judul',
filter.judul,
),
};
}
if (filter.deskripsi) {
where = {
...where,
[Op.and]: Utils.ilike(
'materi',
'deskripsi',
filter.deskripsi,
),
};
}
if (filter.url_video) {
where = {
...where,
[Op.and]: Utils.ilike(
'materi',
'url_video',
filter.url_video,
),
};
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.tipe_konten) {
where = {
...where,
tipe_konten: filter.tipe_konten,
};
}
if (filter.is_published) {
where = {
...where,
is_published: filter.is_published,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.materi.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'materi',
'judul',
query,
),
],
};
}
const records = await db.materi.findAll({
attributes: [ 'id', 'judul' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['judul', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.judul,
}));
}
};

655
backend/src/db/api/nilai.js Normal file
View File

@ -0,0 +1,655 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class NilaiDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const nilai = await db.nilai.create(
{
id: data.id || undefined,
jenis_penilaian: data.jenis_penilaian
||
null
,
judul_penilaian: data.judul_penilaian
||
null
,
tanggal_penilaian: data.tanggal_penilaian
||
null
,
skor: data.skor
||
null
,
predikat: data.predikat
||
null
,
deskripsi_kktp: data.deskripsi_kktp
||
null
,
is_locked: data.is_locked
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await nilai.setSiswa( data.siswa || null, {
transaction,
});
await nilai.setMata_pelajaran( data.mata_pelajaran || null, {
transaction,
});
await nilai.setKelas( data.kelas || null, {
transaction,
});
await nilai.setGuru_penginput( data.guru_penginput || null, {
transaction,
});
return nilai;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const nilaiData = data.map((item, index) => ({
id: item.id || undefined,
jenis_penilaian: item.jenis_penilaian
||
null
,
judul_penilaian: item.judul_penilaian
||
null
,
tanggal_penilaian: item.tanggal_penilaian
||
null
,
skor: item.skor
||
null
,
predikat: item.predikat
||
null
,
deskripsi_kktp: item.deskripsi_kktp
||
null
,
is_locked: item.is_locked
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const nilai = await db.nilai.bulkCreate(nilaiData, { transaction });
// For each item created, replace relation files
return nilai;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const nilai = await db.nilai.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.jenis_penilaian !== undefined) updatePayload.jenis_penilaian = data.jenis_penilaian;
if (data.judul_penilaian !== undefined) updatePayload.judul_penilaian = data.judul_penilaian;
if (data.tanggal_penilaian !== undefined) updatePayload.tanggal_penilaian = data.tanggal_penilaian;
if (data.skor !== undefined) updatePayload.skor = data.skor;
if (data.predikat !== undefined) updatePayload.predikat = data.predikat;
if (data.deskripsi_kktp !== undefined) updatePayload.deskripsi_kktp = data.deskripsi_kktp;
if (data.is_locked !== undefined) updatePayload.is_locked = data.is_locked;
updatePayload.updatedById = currentUser.id;
await nilai.update(updatePayload, {transaction});
if (data.siswa !== undefined) {
await nilai.setSiswa(
data.siswa,
{ transaction }
);
}
if (data.mata_pelajaran !== undefined) {
await nilai.setMata_pelajaran(
data.mata_pelajaran,
{ transaction }
);
}
if (data.kelas !== undefined) {
await nilai.setKelas(
data.kelas,
{ transaction }
);
}
if (data.guru_penginput !== undefined) {
await nilai.setGuru_penginput(
data.guru_penginput,
{ transaction }
);
}
return nilai;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const nilai = await db.nilai.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of nilai) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of nilai) {
await record.destroy({transaction});
}
});
return nilai;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const nilai = await db.nilai.findByPk(id, options);
await nilai.update({
deletedBy: currentUser.id
}, {
transaction,
});
await nilai.destroy({
transaction
});
return nilai;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const nilai = await db.nilai.findOne(
{ where },
{ transaction },
);
if (!nilai) {
return nilai;
}
const output = nilai.get({plain: true});
output.siswa = await nilai.getSiswa({
transaction
});
output.mata_pelajaran = await nilai.getMata_pelajaran({
transaction
});
output.kelas = await nilai.getKelas({
transaction
});
output.guru_penginput = await nilai.getGuru_penginput({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.siswa,
as: 'siswa',
where: filter.siswa ? {
[Op.or]: [
{ id: { [Op.in]: filter.siswa.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.siswa.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.mata_pelajaran,
as: 'mata_pelajaran',
where: filter.mata_pelajaran ? {
[Op.or]: [
{ id: { [Op.in]: filter.mata_pelajaran.split('|').map(term => Utils.uuid(term)) } },
{
nama_mapel: {
[Op.or]: filter.mata_pelajaran.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.kelas,
as: 'kelas',
where: filter.kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.kelas.split('|').map(term => Utils.uuid(term)) } },
{
nama_kelas: {
[Op.or]: filter.kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.guru,
as: 'guru_penginput',
where: filter.guru_penginput ? {
[Op.or]: [
{ id: { [Op.in]: filter.guru_penginput.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.guru_penginput.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.judul_penilaian) {
where = {
...where,
[Op.and]: Utils.ilike(
'nilai',
'judul_penilaian',
filter.judul_penilaian,
),
};
}
if (filter.deskripsi_kktp) {
where = {
...where,
[Op.and]: Utils.ilike(
'nilai',
'deskripsi_kktp',
filter.deskripsi_kktp,
),
};
}
if (filter.tanggal_penilaianRange) {
const [start, end] = filter.tanggal_penilaianRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tanggal_penilaian: {
...where.tanggal_penilaian,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tanggal_penilaian: {
...where.tanggal_penilaian,
[Op.lte]: end,
},
};
}
}
if (filter.skorRange) {
const [start, end] = filter.skorRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
skor: {
...where.skor,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
skor: {
...where.skor,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.jenis_penilaian) {
where = {
...where,
jenis_penilaian: filter.jenis_penilaian,
};
}
if (filter.predikat) {
where = {
...where,
predikat: filter.predikat,
};
}
if (filter.is_locked) {
where = {
...where,
is_locked: filter.is_locked,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.nilai.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'nilai',
'judul_penilaian',
query,
),
],
};
}
const records = await db.nilai.findAll({
attributes: [ 'id', 'judul_penilaian' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['judul_penilaian', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.judul_penilaian,
}));
}
};

View File

@ -0,0 +1,507 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class NotifikasiDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifikasi = await db.notifikasi.create(
{
id: data.id || undefined,
judul: data.judul
||
null
,
pesan: data.pesan
||
null
,
channel: data.channel
||
null
,
kategori: data.kategori
||
null
,
is_read: data.is_read
||
false
,
sent_at: data.sent_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notifikasi.setUser( data.user || null, {
transaction,
});
return notifikasi;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const notifikasiData = data.map((item, index) => ({
id: item.id || undefined,
judul: item.judul
||
null
,
pesan: item.pesan
||
null
,
channel: item.channel
||
null
,
kategori: item.kategori
||
null
,
is_read: item.is_read
||
false
,
sent_at: item.sent_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const notifikasi = await db.notifikasi.bulkCreate(notifikasiData, { transaction });
// For each item created, replace relation files
return notifikasi;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notifikasi = await db.notifikasi.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.judul !== undefined) updatePayload.judul = data.judul;
if (data.pesan !== undefined) updatePayload.pesan = data.pesan;
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.kategori !== undefined) updatePayload.kategori = data.kategori;
if (data.is_read !== undefined) updatePayload.is_read = data.is_read;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
updatePayload.updatedById = currentUser.id;
await notifikasi.update(updatePayload, {transaction});
if (data.user !== undefined) {
await notifikasi.setUser(
data.user,
{ transaction }
);
}
return notifikasi;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifikasi = await db.notifikasi.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notifikasi) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notifikasi) {
await record.destroy({transaction});
}
});
return notifikasi;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notifikasi = await db.notifikasi.findByPk(id, options);
await notifikasi.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notifikasi.destroy({
transaction
});
return notifikasi;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notifikasi = await db.notifikasi.findOne(
{ where },
{ transaction },
);
if (!notifikasi) {
return notifikasi;
}
const output = notifikasi.get({plain: true});
output.user = await notifikasi.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.judul) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifikasi',
'judul',
filter.judul,
),
};
}
if (filter.pesan) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifikasi',
'pesan',
filter.pesan,
),
};
}
if (filter.sent_atRange) {
const [start, end] = filter.sent_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.channel) {
where = {
...where,
channel: filter.channel,
};
}
if (filter.kategori) {
where = {
...where,
kategori: filter.kategori,
};
}
if (filter.is_read) {
where = {
...where,
is_read: filter.is_read,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.notifikasi.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'notifikasi',
'judul',
query,
),
],
};
}
const records = await db.notifikasi.findAll({
attributes: [ 'id', 'judul' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['judul', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.judul,
}));
}
};

View File

@ -0,0 +1,655 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Pengumpulan_tugasDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const pengumpulan_tugas = await db.pengumpulan_tugas.create(
{
id: data.id || undefined,
dikumpulkan_pada: data.dikumpulkan_pada
||
null
,
status: data.status
||
null
,
jawaban_teks: data.jawaban_teks
||
null
,
nilai: data.nilai
||
null
,
feedback_guru: data.feedback_guru
||
null
,
dinilai_pada: data.dinilai_pada
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await pengumpulan_tugas.setTugas( data.tugas || null, {
transaction,
});
await pengumpulan_tugas.setSiswa( data.siswa || null, {
transaction,
});
await pengumpulan_tugas.setDinilai_oleh( data.dinilai_oleh || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.pengumpulan_tugas.getTableName(),
belongsToColumn: 'jawaban_file',
belongsToId: pengumpulan_tugas.id,
},
data.jawaban_file,
options,
);
return pengumpulan_tugas;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const pengumpulan_tugasData = data.map((item, index) => ({
id: item.id || undefined,
dikumpulkan_pada: item.dikumpulkan_pada
||
null
,
status: item.status
||
null
,
jawaban_teks: item.jawaban_teks
||
null
,
nilai: item.nilai
||
null
,
feedback_guru: item.feedback_guru
||
null
,
dinilai_pada: item.dinilai_pada
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const pengumpulan_tugas = await db.pengumpulan_tugas.bulkCreate(pengumpulan_tugasData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < pengumpulan_tugas.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.pengumpulan_tugas.getTableName(),
belongsToColumn: 'jawaban_file',
belongsToId: pengumpulan_tugas[i].id,
},
data[i].jawaban_file,
options,
);
}
return pengumpulan_tugas;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const pengumpulan_tugas = await db.pengumpulan_tugas.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.dikumpulkan_pada !== undefined) updatePayload.dikumpulkan_pada = data.dikumpulkan_pada;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.jawaban_teks !== undefined) updatePayload.jawaban_teks = data.jawaban_teks;
if (data.nilai !== undefined) updatePayload.nilai = data.nilai;
if (data.feedback_guru !== undefined) updatePayload.feedback_guru = data.feedback_guru;
if (data.dinilai_pada !== undefined) updatePayload.dinilai_pada = data.dinilai_pada;
updatePayload.updatedById = currentUser.id;
await pengumpulan_tugas.update(updatePayload, {transaction});
if (data.tugas !== undefined) {
await pengumpulan_tugas.setTugas(
data.tugas,
{ transaction }
);
}
if (data.siswa !== undefined) {
await pengumpulan_tugas.setSiswa(
data.siswa,
{ transaction }
);
}
if (data.dinilai_oleh !== undefined) {
await pengumpulan_tugas.setDinilai_oleh(
data.dinilai_oleh,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.pengumpulan_tugas.getTableName(),
belongsToColumn: 'jawaban_file',
belongsToId: pengumpulan_tugas.id,
},
data.jawaban_file,
options,
);
return pengumpulan_tugas;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const pengumpulan_tugas = await db.pengumpulan_tugas.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of pengumpulan_tugas) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of pengumpulan_tugas) {
await record.destroy({transaction});
}
});
return pengumpulan_tugas;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const pengumpulan_tugas = await db.pengumpulan_tugas.findByPk(id, options);
await pengumpulan_tugas.update({
deletedBy: currentUser.id
}, {
transaction,
});
await pengumpulan_tugas.destroy({
transaction
});
return pengumpulan_tugas;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const pengumpulan_tugas = await db.pengumpulan_tugas.findOne(
{ where },
{ transaction },
);
if (!pengumpulan_tugas) {
return pengumpulan_tugas;
}
const output = pengumpulan_tugas.get({plain: true});
output.tugas = await pengumpulan_tugas.getTugas({
transaction
});
output.siswa = await pengumpulan_tugas.getSiswa({
transaction
});
output.jawaban_file = await pengumpulan_tugas.getJawaban_file({
transaction
});
output.dinilai_oleh = await pengumpulan_tugas.getDinilai_oleh({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tugas,
as: 'tugas',
where: filter.tugas ? {
[Op.or]: [
{ id: { [Op.in]: filter.tugas.split('|').map(term => Utils.uuid(term)) } },
{
judul: {
[Op.or]: filter.tugas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.siswa,
as: 'siswa',
where: filter.siswa ? {
[Op.or]: [
{ id: { [Op.in]: filter.siswa.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.siswa.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.guru,
as: 'dinilai_oleh',
where: filter.dinilai_oleh ? {
[Op.or]: [
{ id: { [Op.in]: filter.dinilai_oleh.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.dinilai_oleh.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'jawaban_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.jawaban_teks) {
where = {
...where,
[Op.and]: Utils.ilike(
'pengumpulan_tugas',
'jawaban_teks',
filter.jawaban_teks,
),
};
}
if (filter.feedback_guru) {
where = {
...where,
[Op.and]: Utils.ilike(
'pengumpulan_tugas',
'feedback_guru',
filter.feedback_guru,
),
};
}
if (filter.dikumpulkan_padaRange) {
const [start, end] = filter.dikumpulkan_padaRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
dikumpulkan_pada: {
...where.dikumpulkan_pada,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
dikumpulkan_pada: {
...where.dikumpulkan_pada,
[Op.lte]: end,
},
};
}
}
if (filter.nilaiRange) {
const [start, end] = filter.nilaiRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
nilai: {
...where.nilai,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
nilai: {
...where.nilai,
[Op.lte]: end,
},
};
}
}
if (filter.dinilai_padaRange) {
const [start, end] = filter.dinilai_padaRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
dinilai_pada: {
...where.dinilai_pada,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
dinilai_pada: {
...where.dinilai_pada,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.pengumpulan_tugas.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'pengumpulan_tugas',
'status',
query,
),
],
};
}
const records = await db.pengumpulan_tugas.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,621 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PengumumanDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const pengumuman = await db.pengumuman.create(
{
id: data.id || undefined,
judul: data.judul
||
null
,
isi: data.isi
||
null
,
target_audience: data.target_audience
||
null
,
published_at: data.published_at
||
null
,
expires_at: data.expires_at
||
null
,
is_published: data.is_published
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await pengumuman.setKelas( data.kelas || null, {
transaction,
});
await pengumuman.setAuthor( data.author || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.pengumuman.getTableName(),
belongsToColumn: 'attachments',
belongsToId: pengumuman.id,
},
data.attachments,
options,
);
return pengumuman;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const pengumumanData = data.map((item, index) => ({
id: item.id || undefined,
judul: item.judul
||
null
,
isi: item.isi
||
null
,
target_audience: item.target_audience
||
null
,
published_at: item.published_at
||
null
,
expires_at: item.expires_at
||
null
,
is_published: item.is_published
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const pengumuman = await db.pengumuman.bulkCreate(pengumumanData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < pengumuman.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.pengumuman.getTableName(),
belongsToColumn: 'attachments',
belongsToId: pengumuman[i].id,
},
data[i].attachments,
options,
);
}
return pengumuman;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const pengumuman = await db.pengumuman.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.judul !== undefined) updatePayload.judul = data.judul;
if (data.isi !== undefined) updatePayload.isi = data.isi;
if (data.target_audience !== undefined) updatePayload.target_audience = data.target_audience;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
updatePayload.updatedById = currentUser.id;
await pengumuman.update(updatePayload, {transaction});
if (data.kelas !== undefined) {
await pengumuman.setKelas(
data.kelas,
{ transaction }
);
}
if (data.author !== undefined) {
await pengumuman.setAuthor(
data.author,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.pengumuman.getTableName(),
belongsToColumn: 'attachments',
belongsToId: pengumuman.id,
},
data.attachments,
options,
);
return pengumuman;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const pengumuman = await db.pengumuman.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of pengumuman) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of pengumuman) {
await record.destroy({transaction});
}
});
return pengumuman;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const pengumuman = await db.pengumuman.findByPk(id, options);
await pengumuman.update({
deletedBy: currentUser.id
}, {
transaction,
});
await pengumuman.destroy({
transaction
});
return pengumuman;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const pengumuman = await db.pengumuman.findOne(
{ where },
{ transaction },
);
if (!pengumuman) {
return pengumuman;
}
const output = pengumuman.get({plain: true});
output.kelas = await pengumuman.getKelas({
transaction
});
output.author = await pengumuman.getAuthor({
transaction
});
output.attachments = await pengumuman.getAttachments({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.kelas,
as: 'kelas',
where: filter.kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.kelas.split('|').map(term => Utils.uuid(term)) } },
{
nama_kelas: {
[Op.or]: filter.kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'author',
where: filter.author ? {
[Op.or]: [
{ id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.judul) {
where = {
...where,
[Op.and]: Utils.ilike(
'pengumuman',
'judul',
filter.judul,
),
};
}
if (filter.isi) {
where = {
...where,
[Op.and]: Utils.ilike(
'pengumuman',
'isi',
filter.isi,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
published_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
expires_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.target_audience) {
where = {
...where,
target_audience: filter.target_audience,
};
}
if (filter.is_published) {
where = {
...where,
is_published: filter.is_published,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.pengumuman.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'pengumuman',
'judul',
query,
),
],
};
}
const records = await db.pengumuman.findAll({
attributes: [ 'id', 'judul' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['judul', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.judul,
}));
}
};

View File

@ -0,0 +1,347 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PermissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return permissions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const permissionsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const permissions = await db.permissions.bulkCreate(permissionsData, { transaction });
// For each item created, replace relation files
return permissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await permissions.update(updatePayload, {transaction});
return permissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of permissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of permissions) {
await record.destroy({transaction});
}
});
return permissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findByPk(id, options);
await permissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await permissions.destroy({
transaction
});
return permissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findOne(
{ where },
{ transaction },
);
if (!permissions) {
return permissions;
}
const output = permissions.get({plain: true});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'permissions',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.permissions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'permissions',
'name',
query,
),
],
};
}
const records = await db.permissions.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,755 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Raport_descriptionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const raport_descriptions = await db.raport_descriptions.create(
{
id: data.id || undefined,
tahun_ajaran: data.tahun_ajaran
||
null
,
semester: data.semester
||
null
,
nilai_akhir: data.nilai_akhir
||
null
,
predikat: data.predikat
||
null
,
deskripsi_kktp: data.deskripsi_kktp
||
null
,
ranking_kelas: data.ranking_kelas
||
null
,
rata_rata_kelas: data.rata_rata_kelas
||
null
,
ai_prompt: data.ai_prompt
||
null
,
ai_output: data.ai_output
||
null
,
generated_at: data.generated_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await raport_descriptions.setSiswa( data.siswa || null, {
transaction,
});
await raport_descriptions.setKelas( data.kelas || null, {
transaction,
});
await raport_descriptions.setMata_pelajaran( data.mata_pelajaran || null, {
transaction,
});
await raport_descriptions.setGenerated_by( data.generated_by || null, {
transaction,
});
return raport_descriptions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const raport_descriptionsData = data.map((item, index) => ({
id: item.id || undefined,
tahun_ajaran: item.tahun_ajaran
||
null
,
semester: item.semester
||
null
,
nilai_akhir: item.nilai_akhir
||
null
,
predikat: item.predikat
||
null
,
deskripsi_kktp: item.deskripsi_kktp
||
null
,
ranking_kelas: item.ranking_kelas
||
null
,
rata_rata_kelas: item.rata_rata_kelas
||
null
,
ai_prompt: item.ai_prompt
||
null
,
ai_output: item.ai_output
||
null
,
generated_at: item.generated_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const raport_descriptions = await db.raport_descriptions.bulkCreate(raport_descriptionsData, { transaction });
// For each item created, replace relation files
return raport_descriptions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const raport_descriptions = await db.raport_descriptions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.tahun_ajaran !== undefined) updatePayload.tahun_ajaran = data.tahun_ajaran;
if (data.semester !== undefined) updatePayload.semester = data.semester;
if (data.nilai_akhir !== undefined) updatePayload.nilai_akhir = data.nilai_akhir;
if (data.predikat !== undefined) updatePayload.predikat = data.predikat;
if (data.deskripsi_kktp !== undefined) updatePayload.deskripsi_kktp = data.deskripsi_kktp;
if (data.ranking_kelas !== undefined) updatePayload.ranking_kelas = data.ranking_kelas;
if (data.rata_rata_kelas !== undefined) updatePayload.rata_rata_kelas = data.rata_rata_kelas;
if (data.ai_prompt !== undefined) updatePayload.ai_prompt = data.ai_prompt;
if (data.ai_output !== undefined) updatePayload.ai_output = data.ai_output;
if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
updatePayload.updatedById = currentUser.id;
await raport_descriptions.update(updatePayload, {transaction});
if (data.siswa !== undefined) {
await raport_descriptions.setSiswa(
data.siswa,
{ transaction }
);
}
if (data.kelas !== undefined) {
await raport_descriptions.setKelas(
data.kelas,
{ transaction }
);
}
if (data.mata_pelajaran !== undefined) {
await raport_descriptions.setMata_pelajaran(
data.mata_pelajaran,
{ transaction }
);
}
if (data.generated_by !== undefined) {
await raport_descriptions.setGenerated_by(
data.generated_by,
{ transaction }
);
}
return raport_descriptions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const raport_descriptions = await db.raport_descriptions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of raport_descriptions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of raport_descriptions) {
await record.destroy({transaction});
}
});
return raport_descriptions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const raport_descriptions = await db.raport_descriptions.findByPk(id, options);
await raport_descriptions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await raport_descriptions.destroy({
transaction
});
return raport_descriptions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const raport_descriptions = await db.raport_descriptions.findOne(
{ where },
{ transaction },
);
if (!raport_descriptions) {
return raport_descriptions;
}
const output = raport_descriptions.get({plain: true});
output.siswa = await raport_descriptions.getSiswa({
transaction
});
output.kelas = await raport_descriptions.getKelas({
transaction
});
output.mata_pelajaran = await raport_descriptions.getMata_pelajaran({
transaction
});
output.generated_by = await raport_descriptions.getGenerated_by({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.siswa,
as: 'siswa',
where: filter.siswa ? {
[Op.or]: [
{ id: { [Op.in]: filter.siswa.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.siswa.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.kelas,
as: 'kelas',
where: filter.kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.kelas.split('|').map(term => Utils.uuid(term)) } },
{
nama_kelas: {
[Op.or]: filter.kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.mata_pelajaran,
as: 'mata_pelajaran',
where: filter.mata_pelajaran ? {
[Op.or]: [
{ id: { [Op.in]: filter.mata_pelajaran.split('|').map(term => Utils.uuid(term)) } },
{
nama_mapel: {
[Op.or]: filter.mata_pelajaran.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'generated_by',
where: filter.generated_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.generated_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.generated_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.tahun_ajaran) {
where = {
...where,
[Op.and]: Utils.ilike(
'raport_descriptions',
'tahun_ajaran',
filter.tahun_ajaran,
),
};
}
if (filter.deskripsi_kktp) {
where = {
...where,
[Op.and]: Utils.ilike(
'raport_descriptions',
'deskripsi_kktp',
filter.deskripsi_kktp,
),
};
}
if (filter.ai_prompt) {
where = {
...where,
[Op.and]: Utils.ilike(
'raport_descriptions',
'ai_prompt',
filter.ai_prompt,
),
};
}
if (filter.ai_output) {
where = {
...where,
[Op.and]: Utils.ilike(
'raport_descriptions',
'ai_output',
filter.ai_output,
),
};
}
if (filter.nilai_akhirRange) {
const [start, end] = filter.nilai_akhirRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
nilai_akhir: {
...where.nilai_akhir,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
nilai_akhir: {
...where.nilai_akhir,
[Op.lte]: end,
},
};
}
}
if (filter.ranking_kelasRange) {
const [start, end] = filter.ranking_kelasRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ranking_kelas: {
...where.ranking_kelas,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ranking_kelas: {
...where.ranking_kelas,
[Op.lte]: end,
},
};
}
}
if (filter.rata_rata_kelasRange) {
const [start, end] = filter.rata_rata_kelasRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rata_rata_kelas: {
...where.rata_rata_kelas,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rata_rata_kelas: {
...where.rata_rata_kelas,
[Op.lte]: end,
},
};
}
}
if (filter.generated_atRange) {
const [start, end] = filter.generated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
generated_at: {
...where.generated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
generated_at: {
...where.generated_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.semester) {
where = {
...where,
semester: filter.semester,
};
}
if (filter.predikat) {
where = {
...where,
predikat: filter.predikat,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.raport_descriptions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'raport_descriptions',
'ai_output',
query,
),
],
};
}
const records = await db.raport_descriptions.findAll({
attributes: [ 'id', 'ai_output' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['ai_output', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.ai_output,
}));
}
};

417
backend/src/db/api/roles.js Normal file
View File

@ -0,0 +1,417 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class RolesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.create(
{
id: data.id || undefined,
name: data.name
||
null
,
role_customization: data.role_customization
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await roles.setPermissions(data.permissions || [], {
transaction,
});
return roles;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const rolesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
role_customization: item.role_customization
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const roles = await db.roles.bulkCreate(rolesData, { transaction });
// For each item created, replace relation files
return roles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.role_customization !== undefined) updatePayload.role_customization = data.role_customization;
updatePayload.updatedById = currentUser.id;
await roles.update(updatePayload, {transaction});
if (data.permissions !== undefined) {
await roles.setPermissions(data.permissions, { transaction });
}
return roles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of roles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of roles) {
await record.destroy({transaction});
}
});
return roles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findByPk(id, options);
await roles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await roles.destroy({
transaction
});
return roles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findOne(
{ where },
{ transaction },
);
if (!roles) {
return roles;
}
const output = roles.get({plain: true});
output.users_app_role = await roles.getUsers_app_role({
transaction
});
output.permissions = await roles.getPermissions({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.permissions,
as: 'permissions',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'roles',
'name',
filter.name,
),
};
}
if (filter.role_customization) {
where = {
...where,
[Op.and]: Utils.ilike(
'roles',
'role_customization',
filter.role_customization,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.permissions) {
const searchTerms = filter.permissions.split('|');
include = [
{
model: db.permissions,
as: 'permissions_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.roles.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'roles',
'name',
query,
),
],
};
}
const records = await db.roles.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

522
backend/src/db/api/sikap.js Normal file
View File

@ -0,0 +1,522 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class SikapDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sikap = await db.sikap.create(
{
id: data.id || undefined,
semester: data.semester
||
null
,
tahun_ajaran: data.tahun_ajaran
||
null
,
predikat_sikap: data.predikat_sikap
||
null
,
catatan_wali_kelas: data.catatan_wali_kelas
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await sikap.setSiswa( data.siswa || null, {
transaction,
});
await sikap.setKelas( data.kelas || null, {
transaction,
});
await sikap.setWali_kelas( data.wali_kelas || null, {
transaction,
});
return sikap;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const sikapData = data.map((item, index) => ({
id: item.id || undefined,
semester: item.semester
||
null
,
tahun_ajaran: item.tahun_ajaran
||
null
,
predikat_sikap: item.predikat_sikap
||
null
,
catatan_wali_kelas: item.catatan_wali_kelas
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const sikap = await db.sikap.bulkCreate(sikapData, { transaction });
// For each item created, replace relation files
return sikap;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const sikap = await db.sikap.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.semester !== undefined) updatePayload.semester = data.semester;
if (data.tahun_ajaran !== undefined) updatePayload.tahun_ajaran = data.tahun_ajaran;
if (data.predikat_sikap !== undefined) updatePayload.predikat_sikap = data.predikat_sikap;
if (data.catatan_wali_kelas !== undefined) updatePayload.catatan_wali_kelas = data.catatan_wali_kelas;
updatePayload.updatedById = currentUser.id;
await sikap.update(updatePayload, {transaction});
if (data.siswa !== undefined) {
await sikap.setSiswa(
data.siswa,
{ transaction }
);
}
if (data.kelas !== undefined) {
await sikap.setKelas(
data.kelas,
{ transaction }
);
}
if (data.wali_kelas !== undefined) {
await sikap.setWali_kelas(
data.wali_kelas,
{ transaction }
);
}
return sikap;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sikap = await db.sikap.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of sikap) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of sikap) {
await record.destroy({transaction});
}
});
return sikap;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const sikap = await db.sikap.findByPk(id, options);
await sikap.update({
deletedBy: currentUser.id
}, {
transaction,
});
await sikap.destroy({
transaction
});
return sikap;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const sikap = await db.sikap.findOne(
{ where },
{ transaction },
);
if (!sikap) {
return sikap;
}
const output = sikap.get({plain: true});
output.siswa = await sikap.getSiswa({
transaction
});
output.kelas = await sikap.getKelas({
transaction
});
output.wali_kelas = await sikap.getWali_kelas({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.siswa,
as: 'siswa',
where: filter.siswa ? {
[Op.or]: [
{ id: { [Op.in]: filter.siswa.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.siswa.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.kelas,
as: 'kelas',
where: filter.kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.kelas.split('|').map(term => Utils.uuid(term)) } },
{
nama_kelas: {
[Op.or]: filter.kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'wali_kelas',
where: filter.wali_kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.wali_kelas.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.wali_kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.tahun_ajaran) {
where = {
...where,
[Op.and]: Utils.ilike(
'sikap',
'tahun_ajaran',
filter.tahun_ajaran,
),
};
}
if (filter.catatan_wali_kelas) {
where = {
...where,
[Op.and]: Utils.ilike(
'sikap',
'catatan_wali_kelas',
filter.catatan_wali_kelas,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.semester) {
where = {
...where,
semester: filter.semester,
};
}
if (filter.predikat_sikap) {
where = {
...where,
predikat_sikap: filter.predikat_sikap,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.sikap.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'sikap',
'catatan_wali_kelas',
query,
),
],
};
}
const records = await db.sikap.findAll({
attributes: [ 'id', 'catatan_wali_kelas' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['catatan_wali_kelas', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.catatan_wali_kelas,
}));
}
};

672
backend/src/db/api/siswa.js Normal file
View File

@ -0,0 +1,672 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class SiswaDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const siswa = await db.siswa.create(
{
id: data.id || undefined,
nisn: data.nisn
||
null
,
nis: data.nis
||
null
,
nama: data.nama
||
null
,
jenis_kelamin: data.jenis_kelamin
||
null
,
tempat_lahir: data.tempat_lahir
||
null
,
tanggal_lahir: data.tanggal_lahir
||
null
,
alamat: data.alamat
||
null
,
nama_ortu: data.nama_ortu
||
null
,
no_hp_ortu: data.no_hp_ortu
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await siswa.setUser( data.user || null, {
transaction,
});
await siswa.setKelas( data.kelas || null, {
transaction,
});
return siswa;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const siswaData = data.map((item, index) => ({
id: item.id || undefined,
nisn: item.nisn
||
null
,
nis: item.nis
||
null
,
nama: item.nama
||
null
,
jenis_kelamin: item.jenis_kelamin
||
null
,
tempat_lahir: item.tempat_lahir
||
null
,
tanggal_lahir: item.tanggal_lahir
||
null
,
alamat: item.alamat
||
null
,
nama_ortu: item.nama_ortu
||
null
,
no_hp_ortu: item.no_hp_ortu
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const siswa = await db.siswa.bulkCreate(siswaData, { transaction });
// For each item created, replace relation files
return siswa;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const siswa = await db.siswa.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.nisn !== undefined) updatePayload.nisn = data.nisn;
if (data.nis !== undefined) updatePayload.nis = data.nis;
if (data.nama !== undefined) updatePayload.nama = data.nama;
if (data.jenis_kelamin !== undefined) updatePayload.jenis_kelamin = data.jenis_kelamin;
if (data.tempat_lahir !== undefined) updatePayload.tempat_lahir = data.tempat_lahir;
if (data.tanggal_lahir !== undefined) updatePayload.tanggal_lahir = data.tanggal_lahir;
if (data.alamat !== undefined) updatePayload.alamat = data.alamat;
if (data.nama_ortu !== undefined) updatePayload.nama_ortu = data.nama_ortu;
if (data.no_hp_ortu !== undefined) updatePayload.no_hp_ortu = data.no_hp_ortu;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await siswa.update(updatePayload, {transaction});
if (data.user !== undefined) {
await siswa.setUser(
data.user,
{ transaction }
);
}
if (data.kelas !== undefined) {
await siswa.setKelas(
data.kelas,
{ transaction }
);
}
return siswa;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const siswa = await db.siswa.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of siswa) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of siswa) {
await record.destroy({transaction});
}
});
return siswa;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const siswa = await db.siswa.findByPk(id, options);
await siswa.update({
deletedBy: currentUser.id
}, {
transaction,
});
await siswa.destroy({
transaction
});
return siswa;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const siswa = await db.siswa.findOne(
{ where },
{ transaction },
);
if (!siswa) {
return siswa;
}
const output = siswa.get({plain: true});
output.nilai_siswa = await siswa.getNilai_siswa({
transaction
});
output.sikap_siswa = await siswa.getSikap_siswa({
transaction
});
output.pengumpulan_tugas_siswa = await siswa.getPengumpulan_tugas_siswa({
transaction
});
output.absensi_siswa = await siswa.getAbsensi_siswa({
transaction
});
output.ai_insights_siswa = await siswa.getAi_insights_siswa({
transaction
});
output.raport_descriptions_siswa = await siswa.getRaport_descriptions_siswa({
transaction
});
output.user = await siswa.getUser({
transaction
});
output.kelas = await siswa.getKelas({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.kelas,
as: 'kelas',
where: filter.kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.kelas.split('|').map(term => Utils.uuid(term)) } },
{
nama_kelas: {
[Op.or]: filter.kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.nisn) {
where = {
...where,
[Op.and]: Utils.ilike(
'siswa',
'nisn',
filter.nisn,
),
};
}
if (filter.nis) {
where = {
...where,
[Op.and]: Utils.ilike(
'siswa',
'nis',
filter.nis,
),
};
}
if (filter.nama) {
where = {
...where,
[Op.and]: Utils.ilike(
'siswa',
'nama',
filter.nama,
),
};
}
if (filter.jenis_kelamin) {
where = {
...where,
[Op.and]: Utils.ilike(
'siswa',
'jenis_kelamin',
filter.jenis_kelamin,
),
};
}
if (filter.tempat_lahir) {
where = {
...where,
[Op.and]: Utils.ilike(
'siswa',
'tempat_lahir',
filter.tempat_lahir,
),
};
}
if (filter.alamat) {
where = {
...where,
[Op.and]: Utils.ilike(
'siswa',
'alamat',
filter.alamat,
),
};
}
if (filter.nama_ortu) {
where = {
...where,
[Op.and]: Utils.ilike(
'siswa',
'nama_ortu',
filter.nama_ortu,
),
};
}
if (filter.no_hp_ortu) {
where = {
...where,
[Op.and]: Utils.ilike(
'siswa',
'no_hp_ortu',
filter.no_hp_ortu,
),
};
}
if (filter.tanggal_lahirRange) {
const [start, end] = filter.tanggal_lahirRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tanggal_lahir: {
...where.tanggal_lahir,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tanggal_lahir: {
...where.tanggal_lahir,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.siswa.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'siswa',
'nama',
query,
),
],
};
}
const records = await db.siswa.findAll({
attributes: [ 'id', 'nama' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['nama', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.nama,
}));
}
};

699
backend/src/db/api/tugas.js Normal file
View File

@ -0,0 +1,699 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class TugasDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tugas = await db.tugas.create(
{
id: data.id || undefined,
jenis: data.jenis
||
null
,
judul: data.judul
||
null
,
instruksi: data.instruksi
||
null
,
dibuka_pada: data.dibuka_pada
||
null
,
deadline_pada: data.deadline_pada
||
null
,
maks_nilai: data.maks_nilai
||
null
,
is_published: data.is_published
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tugas.setMata_pelajaran( data.mata_pelajaran || null, {
transaction,
});
await tugas.setKelas( data.kelas || null, {
transaction,
});
await tugas.setGuru( data.guru || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tugas.getTableName(),
belongsToColumn: 'lampiran',
belongsToId: tugas.id,
},
data.lampiran,
options,
);
return tugas;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const tugasData = data.map((item, index) => ({
id: item.id || undefined,
jenis: item.jenis
||
null
,
judul: item.judul
||
null
,
instruksi: item.instruksi
||
null
,
dibuka_pada: item.dibuka_pada
||
null
,
deadline_pada: item.deadline_pada
||
null
,
maks_nilai: item.maks_nilai
||
null
,
is_published: item.is_published
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tugas = await db.tugas.bulkCreate(tugasData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < tugas.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tugas.getTableName(),
belongsToColumn: 'lampiran',
belongsToId: tugas[i].id,
},
data[i].lampiran,
options,
);
}
return tugas;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tugas = await db.tugas.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.jenis !== undefined) updatePayload.jenis = data.jenis;
if (data.judul !== undefined) updatePayload.judul = data.judul;
if (data.instruksi !== undefined) updatePayload.instruksi = data.instruksi;
if (data.dibuka_pada !== undefined) updatePayload.dibuka_pada = data.dibuka_pada;
if (data.deadline_pada !== undefined) updatePayload.deadline_pada = data.deadline_pada;
if (data.maks_nilai !== undefined) updatePayload.maks_nilai = data.maks_nilai;
if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
updatePayload.updatedById = currentUser.id;
await tugas.update(updatePayload, {transaction});
if (data.mata_pelajaran !== undefined) {
await tugas.setMata_pelajaran(
data.mata_pelajaran,
{ transaction }
);
}
if (data.kelas !== undefined) {
await tugas.setKelas(
data.kelas,
{ transaction }
);
}
if (data.guru !== undefined) {
await tugas.setGuru(
data.guru,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tugas.getTableName(),
belongsToColumn: 'lampiran',
belongsToId: tugas.id,
},
data.lampiran,
options,
);
return tugas;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tugas = await db.tugas.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tugas) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tugas) {
await record.destroy({transaction});
}
});
return tugas;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tugas = await db.tugas.findByPk(id, options);
await tugas.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tugas.destroy({
transaction
});
return tugas;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tugas = await db.tugas.findOne(
{ where },
{ transaction },
);
if (!tugas) {
return tugas;
}
const output = tugas.get({plain: true});
output.pengumpulan_tugas_tugas = await tugas.getPengumpulan_tugas_tugas({
transaction
});
output.mata_pelajaran = await tugas.getMata_pelajaran({
transaction
});
output.kelas = await tugas.getKelas({
transaction
});
output.guru = await tugas.getGuru({
transaction
});
output.lampiran = await tugas.getLampiran({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.mata_pelajaran,
as: 'mata_pelajaran',
where: filter.mata_pelajaran ? {
[Op.or]: [
{ id: { [Op.in]: filter.mata_pelajaran.split('|').map(term => Utils.uuid(term)) } },
{
nama_mapel: {
[Op.or]: filter.mata_pelajaran.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.kelas,
as: 'kelas',
where: filter.kelas ? {
[Op.or]: [
{ id: { [Op.in]: filter.kelas.split('|').map(term => Utils.uuid(term)) } },
{
nama_kelas: {
[Op.or]: filter.kelas.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.guru,
as: 'guru',
where: filter.guru ? {
[Op.or]: [
{ id: { [Op.in]: filter.guru.split('|').map(term => Utils.uuid(term)) } },
{
nama: {
[Op.or]: filter.guru.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'lampiran',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.judul) {
where = {
...where,
[Op.and]: Utils.ilike(
'tugas',
'judul',
filter.judul,
),
};
}
if (filter.instruksi) {
where = {
...where,
[Op.and]: Utils.ilike(
'tugas',
'instruksi',
filter.instruksi,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
dibuka_pada: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
deadline_pada: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.dibuka_padaRange) {
const [start, end] = filter.dibuka_padaRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
dibuka_pada: {
...where.dibuka_pada,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
dibuka_pada: {
...where.dibuka_pada,
[Op.lte]: end,
},
};
}
}
if (filter.deadline_padaRange) {
const [start, end] = filter.deadline_padaRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
deadline_pada: {
...where.deadline_pada,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
deadline_pada: {
...where.deadline_pada,
[Op.lte]: end,
},
};
}
}
if (filter.maks_nilaiRange) {
const [start, end] = filter.maks_nilaiRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
maks_nilai: {
...where.maks_nilai,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
maks_nilai: {
...where.maks_nilai,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.jenis) {
where = {
...where,
jenis: filter.jenis,
};
}
if (filter.is_published) {
where = {
...where,
is_published: filter.is_published,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.tugas.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'tugas',
'judul',
query,
),
],
};
}
const records = await db.tugas.findAll({
attributes: [ 'id', 'judul' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['judul', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.judul,
}));
}
};

989
backend/src/db/api/users.js Normal file
View File

@ -0,0 +1,989 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const bcrypt = require('bcrypt');
const config = require('../../config');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class UsersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.create(
{
id: data.data.id || undefined,
firstName: data.data.firstName
||
null
,
lastName: data.data.lastName
||
null
,
phoneNumber: data.data.phoneNumber
||
null
,
email: data.data.email
||
null
,
disabled: data.data.disabled
||
false
,
password: data.data.password
||
null
,
emailVerified: data.data.emailVerified
||
true
,
emailVerificationToken: data.data.emailVerificationToken
||
null
,
emailVerificationTokenExpiresAt: data.data.emailVerificationTokenExpiresAt
||
null
,
passwordResetToken: data.data.passwordResetToken
||
null
,
passwordResetTokenExpiresAt: data.data.passwordResetTokenExpiresAt
||
null
,
provider: data.data.provider
||
null
,
importHash: data.data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
if (!data.data.app_role) {
const role = await db.roles.findOne({
where: { name: 'User' },
});
if (role) {
await users.setApp_role(role, {
transaction,
});
}
}else{
await users.setApp_role(data.data.app_role || null, {
transaction,
});
}
await users.setCustom_permissions(data.data.custom_permissions || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users.id,
},
data.data.avatar,
options,
);
return users;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const usersData = data.map((item, index) => ({
id: item.id || undefined,
firstName: item.firstName
||
null
,
lastName: item.lastName
||
null
,
phoneNumber: item.phoneNumber
||
null
,
email: item.email
||
null
,
disabled: item.disabled
||
false
,
password: item.password
||
null
,
emailVerified: item.emailVerified
||
false
,
emailVerificationToken: item.emailVerificationToken
||
null
,
emailVerificationTokenExpiresAt: item.emailVerificationTokenExpiresAt
||
null
,
passwordResetToken: item.passwordResetToken
||
null
,
passwordResetTokenExpiresAt: item.passwordResetTokenExpiresAt
||
null
,
provider: item.provider
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const users = await db.users.bulkCreate(usersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < users.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users[i].id,
},
data[i].avatar,
options,
);
}
return users;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {}, {transaction});
if (!data?.app_role) {
data.app_role = users?.app_role?.id;
}
if (!data?.custom_permissions) {
data.custom_permissions = users?.custom_permissions?.map(item => item.id);
}
if (data.password) {
data.password = bcrypt.hashSync(
data.password,
config.bcrypt.saltRounds,
);
} else {
data.password = users.password;
}
const updatePayload = {};
if (data.firstName !== undefined) updatePayload.firstName = data.firstName;
if (data.lastName !== undefined) updatePayload.lastName = data.lastName;
if (data.phoneNumber !== undefined) updatePayload.phoneNumber = data.phoneNumber;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.disabled !== undefined) updatePayload.disabled = data.disabled;
if (data.password !== undefined) updatePayload.password = data.password;
if (data.emailVerified !== undefined) updatePayload.emailVerified = data.emailVerified;
else updatePayload.emailVerified = true;
if (data.emailVerificationToken !== undefined) updatePayload.emailVerificationToken = data.emailVerificationToken;
if (data.emailVerificationTokenExpiresAt !== undefined) updatePayload.emailVerificationTokenExpiresAt = data.emailVerificationTokenExpiresAt;
if (data.passwordResetToken !== undefined) updatePayload.passwordResetToken = data.passwordResetToken;
if (data.passwordResetTokenExpiresAt !== undefined) updatePayload.passwordResetTokenExpiresAt = data.passwordResetTokenExpiresAt;
if (data.provider !== undefined) updatePayload.provider = data.provider;
updatePayload.updatedById = currentUser.id;
await users.update(updatePayload, {transaction});
if (data.app_role !== undefined) {
await users.setApp_role(
data.app_role,
{ transaction }
);
}
if (data.custom_permissions !== undefined) {
await users.setCustom_permissions(data.custom_permissions, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users.id,
},
data.avatar,
options,
);
return users;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of users) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of users) {
await record.destroy({transaction});
}
});
return users;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, options);
await users.update({
deletedBy: currentUser.id
}, {
transaction,
});
await users.destroy({
transaction
});
return users;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findOne(
{ where },
{ transaction },
);
if (!users) {
return users;
}
const output = users.get({plain: true});
output.kelas_wali_kelas = await users.getKelas_wali_kelas({
transaction
});
output.guru_user = await users.getGuru_user({
transaction
});
output.siswa_user = await users.getSiswa_user({
transaction
});
output.sikap_wali_kelas = await users.getSikap_wali_kelas({
transaction
});
output.absensi_dicatat_oleh = await users.getAbsensi_dicatat_oleh({
transaction
});
output.pengumuman_author = await users.getPengumuman_author({
transaction
});
output.notifikasi_user = await users.getNotifikasi_user({
transaction
});
output.ai_insights_generated_by = await users.getAi_insights_generated_by({
transaction
});
output.raport_descriptions_generated_by = await users.getRaport_descriptions_generated_by({
transaction
});
output.audit_logs_actor = await users.getAudit_logs_actor({
transaction
});
output.import_jobs_requested_by = await users.getImport_jobs_requested_by({
transaction
});
output.avatar = await users.getAvatar({
transaction
});
output.app_role = await users.getApp_role({
transaction
});
if (output.app_role) {
output.app_role_permissions = await output.app_role.getPermissions({
transaction,
});
}
output.custom_permissions = await users.getCustom_permissions({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.roles,
as: 'app_role',
where: filter.app_role ? {
[Op.or]: [
{ id: { [Op.in]: filter.app_role.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.app_role.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.permissions,
as: 'custom_permissions',
required: false,
},
{
model: db.file,
as: 'avatar',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.firstName) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'firstName',
filter.firstName,
),
};
}
if (filter.lastName) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'lastName',
filter.lastName,
),
};
}
if (filter.phoneNumber) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'phoneNumber',
filter.phoneNumber,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'email',
filter.email,
),
};
}
if (filter.password) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'password',
filter.password,
),
};
}
if (filter.emailVerificationToken) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'emailVerificationToken',
filter.emailVerificationToken,
),
};
}
if (filter.passwordResetToken) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'passwordResetToken',
filter.passwordResetToken,
),
};
}
if (filter.provider) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'provider',
filter.provider,
),
};
}
if (filter.emailVerificationTokenExpiresAtRange) {
const [start, end] = filter.emailVerificationTokenExpiresAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
emailVerificationTokenExpiresAt: {
...where.emailVerificationTokenExpiresAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
emailVerificationTokenExpiresAt: {
...where.emailVerificationTokenExpiresAt,
[Op.lte]: end,
},
};
}
}
if (filter.passwordResetTokenExpiresAtRange) {
const [start, end] = filter.passwordResetTokenExpiresAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
passwordResetTokenExpiresAt: {
...where.passwordResetTokenExpiresAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
passwordResetTokenExpiresAt: {
...where.passwordResetTokenExpiresAt,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.disabled) {
where = {
...where,
disabled: filter.disabled,
};
}
if (filter.emailVerified) {
where = {
...where,
emailVerified: filter.emailVerified,
};
}
if (filter.custom_permissions) {
const searchTerms = filter.custom_permissions.split('|');
include = [
{
model: db.permissions,
as: 'custom_permissions_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.users.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'users',
'firstName',
query,
),
],
};
}
const records = await db.users.findAll({
attributes: [ 'id', 'firstName' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['firstName', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.firstName,
}));
}
static async createFromAuth(data, options) {
const transaction = (options && options.transaction) || undefined;
const users = await db.users.create(
{
email: data.email,
firstName: data.firstName,
authenticationUid: data.authenticationUid,
password: data.password,
},
{ transaction },
);
const app_role = await db.roles.findOne({
where: { name: config.roles?.user || "User" },
});
if (app_role?.id) {
await users.setApp_role(app_role?.id || null, {
transaction,
});
}
await users.update(
{
authenticationUid: users.id,
},
{ transaction },
);
delete users.password;
return users;
}
static async updatePassword(id, password, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {
transaction,
});
await users.update(
{
password,
authenticationUid: id,
updatedById: currentUser.id,
},
{ transaction },
);
return users;
}
static async generateEmailVerificationToken(email, options) {
return this._generateToken(['emailVerificationToken', 'emailVerificationTokenExpiresAt'], email, options);
}
static async generatePasswordResetToken(email, options) {
return this._generateToken(['passwordResetToken', 'passwordResetTokenExpiresAt'], email, options);
}
static async findByPasswordResetToken(token, options) {
const transaction = (options && options.transaction) || undefined;
return db.users.findOne(
{
where: {
passwordResetToken: token,
passwordResetTokenExpiresAt: {
[db.Sequelize.Op.gt]: Date.now(),
},
},
},
{ transaction },
);
}
static async findByEmailVerificationToken(
token,
options,
) {
const transaction = (options && options.transaction) || undefined;
return db.users.findOne(
{
where: {
emailVerificationToken: token,
emailVerificationTokenExpiresAt: {
[db.Sequelize.Op.gt]: Date.now(),
},
},
},
{ transaction },
);
}
static async markEmailVerified(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {
transaction,
});
await users.update(
{
emailVerified: true,
updatedById: currentUser.id,
},
{ transaction },
);
return true;
}
static async _generateToken(keyNames, email, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findOne(
{
where: { email: email.toLowerCase() },
},
{
transaction,
},
);
const token = crypto
.randomBytes(20)
.toString('hex');
const tokenExpiresAt = Date.now() + 360000;
if(users){
await users.update(
{
[keyNames[0]]: token,
[keyNames[1]]: tokenExpiresAt,
updatedById: currentUser.id,
},
{transaction},
);
}
return token;
}
};

View File

@ -0,0 +1,33 @@
module.exports = {
production: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
},
development: {
username: 'postgres',
dialect: 'postgres',
password: '',
database: 'db_smpn_1_seponti_digital',
host: process.env.DB_HOST || 'localhost',
logging: console.log,
seederStorage: 'sequelize',
},
dev_stage: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
}
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,124 @@
module.exports = {
async up(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.files') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (tableName) {
await transaction.commit();
return;
}
await queryInterface.createTable(
'files',
{
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV4,
primaryKey: true,
},
belongsTo: {
type: Sequelize.DataTypes.STRING(255),
allowNull: true,
},
belongsToId: {
type: Sequelize.DataTypes.UUID,
allowNull: true,
},
belongsToColumn: {
type: Sequelize.DataTypes.STRING(255),
allowNull: true,
},
name: {
type: Sequelize.DataTypes.STRING(2083),
allowNull: false,
},
sizeInBytes: {
type: Sequelize.DataTypes.INTEGER,
allowNull: true,
},
privateUrl: {
type: Sequelize.DataTypes.STRING(2083),
allowNull: true,
},
publicUrl: {
type: Sequelize.DataTypes.STRING(2083),
allowNull: false,
},
createdAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
deletedAt: {
type: Sequelize.DataTypes.DATE,
allowNull: true,
},
createdById: {
type: Sequelize.DataTypes.UUID,
allowNull: true,
references: {
key: 'id',
model: 'users',
},
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
},
updatedById: {
type: Sequelize.DataTypes.UUID,
allowNull: true,
references: {
key: 'id',
model: 'users',
},
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
async down(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.files') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (!tableName) {
await transaction.commit();
return;
}
await queryInterface.dropTable('files', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,77 @@
module.exports = {
async up(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.\"usersCustom_permissionsPermissions\"') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (tableName) {
await transaction.commit();
return;
}
await queryInterface.createTable(
'usersCustom_permissionsPermissions',
{
createdAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
users_custom_permissionsId: {
type: Sequelize.DataTypes.UUID,
allowNull: false,
primaryKey: true,
},
permissionId: {
type: Sequelize.DataTypes.UUID,
allowNull: false,
primaryKey: true,
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
async down(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.\"usersCustom_permissionsPermissions\"') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (!tableName) {
await transaction.commit();
return;
}
await queryInterface.dropTable('usersCustom_permissionsPermissions', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,139 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const absensi = sequelize.define(
'absensi',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
tanggal: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"hadir",
"izin",
"sakit",
"alpa"
],
},
keterangan: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
absensi.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.absensi.belongsTo(db.kelas, {
as: 'kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.absensi.belongsTo(db.siswa, {
as: 'siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.absensi.belongsTo(db.users, {
as: 'dicatat_oleh',
foreignKey: {
name: 'dicatat_olehId',
},
constraints: false,
});
db.absensi.belongsTo(db.users, {
as: 'createdBy',
});
db.absensi.belongsTo(db.users, {
as: 'updatedBy',
});
};
return absensi;
};

View File

@ -0,0 +1,156 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ai_insights = sequelize.define(
'ai_insights',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
jenis: {
type: DataTypes.ENUM,
values: [
"prediksi_prestasi",
"deteksi_kelemahan",
"rekomendasi_belajar",
"insight_wali_kelas",
"ringkasan_kelas"
],
},
skor_keyakinan: {
type: DataTypes.DECIMAL,
},
ringkasan: {
type: DataTypes.TEXT,
},
rekomendasi: {
type: DataTypes.TEXT,
},
generated_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ai_insights.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.ai_insights.belongsTo(db.siswa, {
as: 'siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.ai_insights.belongsTo(db.kelas, {
as: 'kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.ai_insights.belongsTo(db.users, {
as: 'generated_by',
foreignKey: {
name: 'generated_byId',
},
constraints: false,
});
db.ai_insights.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_insights.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_insights;
};

View File

@ -0,0 +1,166 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_logs = sequelize.define(
'audit_logs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
action: {
type: DataTypes.ENUM,
values: [
"create",
"update",
"delete",
"import",
"export",
"login",
"logout",
"generate_ai",
"print_pdf"
],
},
entity_name: {
type: DataTypes.TEXT,
},
entity_key: {
type: DataTypes.TEXT,
},
summary: {
type: DataTypes.TEXT,
},
ip_address: {
type: DataTypes.TEXT,
},
user_agent: {
type: DataTypes.TEXT,
},
logged_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
audit_logs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.audit_logs.belongsTo(db.users, {
as: 'actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.audit_logs.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_logs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_logs;
};

View File

@ -0,0 +1,53 @@
module.exports = function(sequelize, DataTypes) {
const file = sequelize.define(
'file',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
belongsTo: DataTypes.STRING(255),
belongsToId: DataTypes.UUID,
belongsToColumn: DataTypes.STRING(255),
name: {
type: DataTypes.STRING(2083),
allowNull: false,
validate: {
notEmpty: true,
},
},
sizeInBytes: {
type: DataTypes.INTEGER,
allowNull: true,
},
privateUrl: {
type: DataTypes.STRING(2083),
allowNull: true,
},
publicUrl: {
type: DataTypes.STRING(2083),
allowNull: false,
validate: {
notEmpty: true,
},
},
},
{
timestamps: true,
paranoid: true,
},
);
file.associate = (db) => {
db.file.belongsTo(db.users, {
as: 'createdBy',
});
db.file.belongsTo(db.users, {
as: 'updatedBy',
});
};
return file;
};

View File

@ -0,0 +1,186 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const guru = sequelize.define(
'guru',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
nip: {
type: DataTypes.TEXT,
},
nama: {
type: DataTypes.TEXT,
},
jenis_kelamin: {
type: DataTypes.TEXT,
},
tempat_lahir: {
type: DataTypes.TEXT,
},
tanggal_lahir: {
type: DataTypes.DATE,
},
alamat: {
type: DataTypes.TEXT,
},
no_hp: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
guru.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.guru.hasMany(db.mata_pelajaran, {
as: 'mata_pelajaran_guru_pengampu',
foreignKey: {
name: 'guru_pengampuId',
},
constraints: false,
});
db.guru.hasMany(db.nilai, {
as: 'nilai_guru_penginput',
foreignKey: {
name: 'guru_penginputId',
},
constraints: false,
});
db.guru.hasMany(db.materi, {
as: 'materi_guru',
foreignKey: {
name: 'guruId',
},
constraints: false,
});
db.guru.hasMany(db.tugas, {
as: 'tugas_guru',
foreignKey: {
name: 'guruId',
},
constraints: false,
});
db.guru.hasMany(db.pengumpulan_tugas, {
as: 'pengumpulan_tugas_dinilai_oleh',
foreignKey: {
name: 'dinilai_olehId',
},
constraints: false,
});
//end loop
db.guru.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.guru.belongsTo(db.users, {
as: 'createdBy',
});
db.guru.belongsTo(db.users, {
as: 'updatedBy',
});
};
return guru;
};

View File

@ -0,0 +1,189 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const import_jobs = sequelize.define(
'import_jobs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
jenis: {
type: DataTypes.ENUM,
values: [
"dapodik_guru",
"dapodik_siswa",
"kelas",
"mata_pelajaran",
"nilai"
],
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"processing",
"success",
"failed",
"partial"
],
},
total_rows: {
type: DataTypes.INTEGER,
},
success_rows: {
type: DataTypes.INTEGER,
},
failed_rows: {
type: DataTypes.INTEGER,
},
error_report: {
type: DataTypes.TEXT,
},
started_at: {
type: DataTypes.DATE,
},
finished_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
import_jobs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.import_jobs.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.import_jobs.hasMany(db.file, {
as: 'file_excel',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.import_jobs.getTableName(),
belongsToColumn: 'file_excel',
},
});
db.import_jobs.belongsTo(db.users, {
as: 'createdBy',
});
db.import_jobs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return import_jobs;
};

View File

@ -0,0 +1,38 @@
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require("../db.config")[env];
const db = {};
let sequelize;
console.log(env);
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes)
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;

View File

@ -0,0 +1,204 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const kelas = sequelize.define(
'kelas',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
nama_kelas: {
type: DataTypes.TEXT,
},
tingkat: {
type: DataTypes.TEXT,
},
tahun_ajaran: {
type: DataTypes.TEXT,
},
semester: {
type: DataTypes.ENUM,
values: [
"ganjil",
"genap"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
kelas.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.kelas.hasMany(db.siswa, {
as: 'siswa_kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.kelas.hasMany(db.kktp, {
as: 'kktp_kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.kelas.hasMany(db.nilai, {
as: 'nilai_kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.kelas.hasMany(db.sikap, {
as: 'sikap_kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.kelas.hasMany(db.materi, {
as: 'materi_kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.kelas.hasMany(db.tugas, {
as: 'tugas_kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.kelas.hasMany(db.absensi, {
as: 'absensi_kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.kelas.hasMany(db.pengumuman, {
as: 'pengumuman_kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.kelas.hasMany(db.ai_insights, {
as: 'ai_insights_kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.kelas.hasMany(db.raport_descriptions, {
as: 'raport_descriptions_kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
//end loop
db.kelas.belongsTo(db.users, {
as: 'wali_kelas',
foreignKey: {
name: 'wali_kelasId',
},
constraints: false,
});
db.kelas.belongsTo(db.users, {
as: 'createdBy',
});
db.kelas.belongsTo(db.users, {
as: 'updatedBy',
});
};
return kelas;
};

View File

@ -0,0 +1,134 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const kktp = sequelize.define(
'kktp',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
fase: {
type: DataTypes.TEXT,
},
nilai_minimum: {
type: DataTypes.INTEGER,
},
deskripsi_umum: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
kktp.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.kktp.hasMany(db.kktp_detail, {
as: 'kktp_detail_kktp',
foreignKey: {
name: 'kktpId',
},
constraints: false,
});
//end loop
db.kktp.belongsTo(db.mata_pelajaran, {
as: 'mata_pelajaran',
foreignKey: {
name: 'mata_pelajaranId',
},
constraints: false,
});
db.kktp.belongsTo(db.kelas, {
as: 'kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.kktp.belongsTo(db.users, {
as: 'createdBy',
});
db.kktp.belongsTo(db.users, {
as: 'updatedBy',
});
};
return kktp;
};

View File

@ -0,0 +1,130 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const kktp_detail = sequelize.define(
'kktp_detail',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
predikat: {
type: DataTypes.ENUM,
values: [
"A",
"B",
"C",
"D"
],
},
nilai_min: {
type: DataTypes.INTEGER,
},
nilai_max: {
type: DataTypes.INTEGER,
},
deskripsi: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
kktp_detail.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.kktp_detail.belongsTo(db.kktp, {
as: 'kktp',
foreignKey: {
name: 'kktpId',
},
constraints: false,
});
db.kktp_detail.belongsTo(db.users, {
as: 'createdBy',
});
db.kktp_detail.belongsTo(db.users, {
as: 'updatedBy',
});
};
return kktp_detail;
};

View File

@ -0,0 +1,177 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const mata_pelajaran = sequelize.define(
'mata_pelajaran',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
kode_mapel: {
type: DataTypes.TEXT,
},
nama_mapel: {
type: DataTypes.TEXT,
},
kelompok: {
type: DataTypes.ENUM,
values: [
"umum",
"muatan_lokal",
"pilihan"
],
},
urutan: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
mata_pelajaran.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.mata_pelajaran.hasMany(db.kktp, {
as: 'kktp_mata_pelajaran',
foreignKey: {
name: 'mata_pelajaranId',
},
constraints: false,
});
db.mata_pelajaran.hasMany(db.nilai, {
as: 'nilai_mata_pelajaran',
foreignKey: {
name: 'mata_pelajaranId',
},
constraints: false,
});
db.mata_pelajaran.hasMany(db.materi, {
as: 'materi_mata_pelajaran',
foreignKey: {
name: 'mata_pelajaranId',
},
constraints: false,
});
db.mata_pelajaran.hasMany(db.tugas, {
as: 'tugas_mata_pelajaran',
foreignKey: {
name: 'mata_pelajaranId',
},
constraints: false,
});
db.mata_pelajaran.hasMany(db.raport_descriptions, {
as: 'raport_descriptions_mata_pelajaran',
foreignKey: {
name: 'mata_pelajaranId',
},
constraints: false,
});
//end loop
db.mata_pelajaran.belongsTo(db.guru, {
as: 'guru_pengampu',
foreignKey: {
name: 'guru_pengampuId',
},
constraints: false,
});
db.mata_pelajaran.belongsTo(db.users, {
as: 'createdBy',
});
db.mata_pelajaran.belongsTo(db.users, {
as: 'updatedBy',
});
};
return mata_pelajaran;
};

View File

@ -0,0 +1,173 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const materi = sequelize.define(
'materi',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
judul: {
type: DataTypes.TEXT,
},
deskripsi: {
type: DataTypes.TEXT,
},
tipe_konten: {
type: DataTypes.ENUM,
values: [
"pdf",
"video",
"link",
"teks"
],
},
url_video: {
type: DataTypes.TEXT,
},
published_at: {
type: DataTypes.DATE,
},
is_published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
materi.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.materi.belongsTo(db.mata_pelajaran, {
as: 'mata_pelajaran',
foreignKey: {
name: 'mata_pelajaranId',
},
constraints: false,
});
db.materi.belongsTo(db.kelas, {
as: 'kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.materi.belongsTo(db.guru, {
as: 'guru',
foreignKey: {
name: 'guruId',
},
constraints: false,
});
db.materi.hasMany(db.file, {
as: 'lampiran',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.materi.getTableName(),
belongsToColumn: 'lampiran',
},
});
db.materi.belongsTo(db.users, {
as: 'createdBy',
});
db.materi.belongsTo(db.users, {
as: 'updatedBy',
});
};
return materi;
};

View File

@ -0,0 +1,205 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const nilai = sequelize.define(
'nilai',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
jenis_penilaian: {
type: DataTypes.ENUM,
values: [
"tugas",
"kuis",
"ulangan_harian",
"pts",
"pas",
"praktik",
"proyek",
"lainnya"
],
},
judul_penilaian: {
type: DataTypes.TEXT,
},
tanggal_penilaian: {
type: DataTypes.DATE,
},
skor: {
type: DataTypes.DECIMAL,
},
predikat: {
type: DataTypes.ENUM,
values: [
"A",
"B",
"C",
"D"
],
},
deskripsi_kktp: {
type: DataTypes.TEXT,
},
is_locked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
nilai.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.nilai.belongsTo(db.siswa, {
as: 'siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.nilai.belongsTo(db.mata_pelajaran, {
as: 'mata_pelajaran',
foreignKey: {
name: 'mata_pelajaranId',
},
constraints: false,
});
db.nilai.belongsTo(db.kelas, {
as: 'kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.nilai.belongsTo(db.guru, {
as: 'guru_penginput',
foreignKey: {
name: 'guru_penginputId',
},
constraints: false,
});
db.nilai.belongsTo(db.users, {
as: 'createdBy',
});
db.nilai.belongsTo(db.users, {
as: 'updatedBy',
});
};
return nilai;
};

View File

@ -0,0 +1,162 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const notifikasi = sequelize.define(
'notifikasi',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
judul: {
type: DataTypes.TEXT,
},
pesan: {
type: DataTypes.TEXT,
},
channel: {
type: DataTypes.ENUM,
values: [
"in_app",
"fcm"
],
},
kategori: {
type: DataTypes.ENUM,
values: [
"pengumuman",
"tugas",
"nilai",
"absensi",
"sistem",
"lainnya"
],
},
is_read: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
sent_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notifikasi.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.notifikasi.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.notifikasi.belongsTo(db.users, {
as: 'createdBy',
});
db.notifikasi.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notifikasi;
};

View File

@ -0,0 +1,173 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const pengumpulan_tugas = sequelize.define(
'pengumpulan_tugas',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
dikumpulkan_pada: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"submitted",
"late",
"graded",
"returned"
],
},
jawaban_teks: {
type: DataTypes.TEXT,
},
nilai: {
type: DataTypes.DECIMAL,
},
feedback_guru: {
type: DataTypes.TEXT,
},
dinilai_pada: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
pengumpulan_tugas.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.pengumpulan_tugas.belongsTo(db.tugas, {
as: 'tugas',
foreignKey: {
name: 'tugasId',
},
constraints: false,
});
db.pengumpulan_tugas.belongsTo(db.siswa, {
as: 'siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.pengumpulan_tugas.belongsTo(db.guru, {
as: 'dinilai_oleh',
foreignKey: {
name: 'dinilai_olehId',
},
constraints: false,
});
db.pengumpulan_tugas.hasMany(db.file, {
as: 'jawaban_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.pengumpulan_tugas.getTableName(),
belongsToColumn: 'jawaban_file',
},
});
db.pengumpulan_tugas.belongsTo(db.users, {
as: 'createdBy',
});
db.pengumpulan_tugas.belongsTo(db.users, {
as: 'updatedBy',
});
};
return pengumpulan_tugas;
};

View File

@ -0,0 +1,171 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const pengumuman = sequelize.define(
'pengumuman',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
judul: {
type: DataTypes.TEXT,
},
isi: {
type: DataTypes.TEXT,
},
target_audience: {
type: DataTypes.ENUM,
values: [
"semua",
"guru",
"siswa",
"wali_kelas",
"kepala_sekolah",
"kelas_tertentu"
],
},
published_at: {
type: DataTypes.DATE,
},
expires_at: {
type: DataTypes.DATE,
},
is_published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
pengumuman.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.pengumuman.belongsTo(db.kelas, {
as: 'kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.pengumuman.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.pengumuman.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.pengumuman.getTableName(),
belongsToColumn: 'attachments',
},
});
db.pengumuman.belongsTo(db.users, {
as: 'createdBy',
});
db.pengumuman.belongsTo(db.users, {
as: 'updatedBy',
});
};
return pengumuman;
};

View File

@ -0,0 +1,86 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const permissions = sequelize.define(
'permissions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
permissions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.permissions.belongsTo(db.users, {
as: 'createdBy',
});
db.permissions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return permissions;
};

View File

@ -0,0 +1,205 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const raport_descriptions = sequelize.define(
'raport_descriptions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
tahun_ajaran: {
type: DataTypes.TEXT,
},
semester: {
type: DataTypes.ENUM,
values: [
"ganjil",
"genap"
],
},
nilai_akhir: {
type: DataTypes.DECIMAL,
},
predikat: {
type: DataTypes.ENUM,
values: [
"A",
"B",
"C",
"D"
],
},
deskripsi_kktp: {
type: DataTypes.TEXT,
},
ranking_kelas: {
type: DataTypes.INTEGER,
},
rata_rata_kelas: {
type: DataTypes.DECIMAL,
},
ai_prompt: {
type: DataTypes.TEXT,
},
ai_output: {
type: DataTypes.TEXT,
},
generated_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
raport_descriptions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.raport_descriptions.belongsTo(db.siswa, {
as: 'siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.raport_descriptions.belongsTo(db.kelas, {
as: 'kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.raport_descriptions.belongsTo(db.mata_pelajaran, {
as: 'mata_pelajaran',
foreignKey: {
name: 'mata_pelajaranId',
},
constraints: false,
});
db.raport_descriptions.belongsTo(db.users, {
as: 'generated_by',
foreignKey: {
name: 'generated_byId',
},
constraints: false,
});
db.raport_descriptions.belongsTo(db.users, {
as: 'createdBy',
});
db.raport_descriptions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return raport_descriptions;
};

View File

@ -0,0 +1,119 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const roles = sequelize.define(
'roles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
role_customization: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
roles.associate = (db) => {
db.roles.belongsToMany(db.permissions, {
as: 'permissions',
foreignKey: {
name: 'roles_permissionsId',
},
constraints: false,
through: 'rolesPermissionsPermissions',
});
db.roles.belongsToMany(db.permissions, {
as: 'permissions_filter',
foreignKey: {
name: 'roles_permissionsId',
},
constraints: false,
through: 'rolesPermissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.roles.hasMany(db.users, {
as: 'users_app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
//end loop
db.roles.belongsTo(db.users, {
as: 'createdBy',
});
db.roles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return roles;
};

View File

@ -0,0 +1,155 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const sikap = sequelize.define(
'sikap',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
semester: {
type: DataTypes.ENUM,
values: [
"ganjil",
"genap"
],
},
tahun_ajaran: {
type: DataTypes.TEXT,
},
predikat_sikap: {
type: DataTypes.ENUM,
values: [
"sangat_baik",
"baik",
"cukup",
"perlu_bimbingan"
],
},
catatan_wali_kelas: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
sikap.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.sikap.belongsTo(db.siswa, {
as: 'siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.sikap.belongsTo(db.kelas, {
as: 'kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.sikap.belongsTo(db.users, {
as: 'wali_kelas',
foreignKey: {
name: 'wali_kelasId',
},
constraints: false,
});
db.sikap.belongsTo(db.users, {
as: 'createdBy',
});
db.sikap.belongsTo(db.users, {
as: 'updatedBy',
});
};
return sikap;
};

View File

@ -0,0 +1,216 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const siswa = sequelize.define(
'siswa',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
nisn: {
type: DataTypes.TEXT,
},
nis: {
type: DataTypes.TEXT,
},
nama: {
type: DataTypes.TEXT,
},
jenis_kelamin: {
type: DataTypes.TEXT,
},
tempat_lahir: {
type: DataTypes.TEXT,
},
tanggal_lahir: {
type: DataTypes.DATE,
},
alamat: {
type: DataTypes.TEXT,
},
nama_ortu: {
type: DataTypes.TEXT,
},
no_hp_ortu: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
siswa.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.siswa.hasMany(db.nilai, {
as: 'nilai_siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.siswa.hasMany(db.sikap, {
as: 'sikap_siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.siswa.hasMany(db.pengumpulan_tugas, {
as: 'pengumpulan_tugas_siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.siswa.hasMany(db.absensi, {
as: 'absensi_siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.siswa.hasMany(db.ai_insights, {
as: 'ai_insights_siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
db.siswa.hasMany(db.raport_descriptions, {
as: 'raport_descriptions_siswa',
foreignKey: {
name: 'siswaId',
},
constraints: false,
});
//end loop
db.siswa.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.siswa.belongsTo(db.kelas, {
as: 'kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.siswa.belongsTo(db.users, {
as: 'createdBy',
});
db.siswa.belongsTo(db.users, {
as: 'updatedBy',
});
};
return siswa;
};

View File

@ -0,0 +1,182 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const tugas = sequelize.define(
'tugas',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
jenis: {
type: DataTypes.ENUM,
values: [
"tugas",
"kuis"
],
},
judul: {
type: DataTypes.TEXT,
},
instruksi: {
type: DataTypes.TEXT,
},
dibuka_pada: {
type: DataTypes.DATE,
},
deadline_pada: {
type: DataTypes.DATE,
},
maks_nilai: {
type: DataTypes.INTEGER,
},
is_published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tugas.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.tugas.hasMany(db.pengumpulan_tugas, {
as: 'pengumpulan_tugas_tugas',
foreignKey: {
name: 'tugasId',
},
constraints: false,
});
//end loop
db.tugas.belongsTo(db.mata_pelajaran, {
as: 'mata_pelajaran',
foreignKey: {
name: 'mata_pelajaranId',
},
constraints: false,
});
db.tugas.belongsTo(db.kelas, {
as: 'kelas',
foreignKey: {
name: 'kelasId',
},
constraints: false,
});
db.tugas.belongsTo(db.guru, {
as: 'guru',
foreignKey: {
name: 'guruId',
},
constraints: false,
});
db.tugas.hasMany(db.file, {
as: 'lampiran',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.tugas.getTableName(),
belongsToColumn: 'lampiran',
},
});
db.tugas.belongsTo(db.users, {
as: 'createdBy',
});
db.tugas.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tugas;
};

View File

@ -0,0 +1,332 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const users = sequelize.define(
'users',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
firstName: {
type: DataTypes.TEXT,
},
lastName: {
type: DataTypes.TEXT,
},
phoneNumber: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
disabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
password: {
type: DataTypes.TEXT,
},
emailVerified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
emailVerificationToken: {
type: DataTypes.TEXT,
},
emailVerificationTokenExpiresAt: {
type: DataTypes.DATE,
},
passwordResetToken: {
type: DataTypes.TEXT,
},
passwordResetTokenExpiresAt: {
type: DataTypes.DATE,
},
provider: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
users.associate = (db) => {
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions_filter',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.users.hasMany(db.kelas, {
as: 'kelas_wali_kelas',
foreignKey: {
name: 'wali_kelasId',
},
constraints: false,
});
db.users.hasMany(db.guru, {
as: 'guru_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.siswa, {
as: 'siswa_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.sikap, {
as: 'sikap_wali_kelas',
foreignKey: {
name: 'wali_kelasId',
},
constraints: false,
});
db.users.hasMany(db.absensi, {
as: 'absensi_dicatat_oleh',
foreignKey: {
name: 'dicatat_olehId',
},
constraints: false,
});
db.users.hasMany(db.pengumuman, {
as: 'pengumuman_author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.users.hasMany(db.notifikasi, {
as: 'notifikasi_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.ai_insights, {
as: 'ai_insights_generated_by',
foreignKey: {
name: 'generated_byId',
},
constraints: false,
});
db.users.hasMany(db.raport_descriptions, {
as: 'raport_descriptions_generated_by',
foreignKey: {
name: 'generated_byId',
},
constraints: false,
});
db.users.hasMany(db.audit_logs, {
as: 'audit_logs_actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.users.hasMany(db.import_jobs, {
as: 'import_jobs_requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

16
backend/src/db/reset.js Normal file
View File

@ -0,0 +1,16 @@
const db = require('./models');
const {execSync} = require("child_process");
console.log('Resetting Database');
db.sequelize
.sync({ force: true })
.then(() => {
execSync("sequelize db:seed:all");
console.log('OK');
process.exit();
})
.catch((error) => {
console.error(error);
process.exit(1);
});

View File

@ -0,0 +1,66 @@
'use strict';
const bcrypt = require("bcrypt");
const config = require("../../config");
const ids = [
'193bf4b5-9f07-4bd5-9a43-e7e41f3e96af',
'af5a87be-8f9c-4630-902a-37a60b7005ba',
'5bc531ab-611f-41f3-9373-b7cc5d09c93d',
]
module.exports = {
up: async (queryInterface, Sequelize) => {
let admin_hash = bcrypt.hashSync(config.admin_pass, config.bcrypt.saltRounds);
let user_hash = bcrypt.hashSync(config.user_pass, config.bcrypt.saltRounds);
try {
await queryInterface.bulkInsert('users', [
{
id: ids[0],
firstName: 'Admin',
email: config.admin_email,
emailVerified: true,
provider: config.providers.LOCAL,
password: admin_hash,
createdAt: new Date(),
updatedAt: new Date()
},
{
id: ids[1],
firstName: 'John',
email: 'john@doe.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: user_hash,
createdAt: new Date(),
updatedAt: new Date()
},
{
id: ids[2],
firstName: 'Client',
email: 'client@hello.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: user_hash,
createdAt: new Date(),
updatedAt: new Date()
},
]);
} catch (error) {
console.error('Error during bulkInsert:', error);
throw error;
}
},
down: async (queryInterface, Sequelize) => {
try {
await queryInterface.bulkDelete('users', {
id: {
[Sequelize.Op.in]: ids,
},
}, {});
} catch (error) {
console.error('Error during bulkDelete:', error);
throw error;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

27
backend/src/db/utils.js Normal file
View File

@ -0,0 +1,27 @@
const validator = require('validator');
const { v4: uuid } = require('uuid');
const Sequelize = require('./models').Sequelize;
module.exports = class Utils {
static uuid(value) {
let id = value;
if (!validator.isUUID(id)) {
id = uuid();
}
return id;
}
static ilike(model, column, value) {
return Sequelize.where(
Sequelize.fn(
'lower',
Sequelize.col(`${model}.${column}`),
),
{
[Sequelize.Op.like]: `%${value}%`.toLowerCase(),
},
);
}
};

23
backend/src/helpers.js Normal file
View File

@ -0,0 +1,23 @@
const jwt = require('jsonwebtoken');
const config = require('./config');
module.exports = class Helpers {
static wrapAsync(fn) {
return function (req, res, next) {
fn(req, res, next).catch(next);
};
}
static commonErrorHandler(error, req, res, next) {
if ([400, 403, 404].includes(error.code)) {
return res.status(error.code).send(error.message);
}
console.error(error);
return res.status(500).send(error.message);
}
static jwtSign(data) {
return jwt.sign(data, config.secret_key, {expiresIn: '6h'});
};
};

208
backend/src/index.js Normal file
View File

@ -0,0 +1,208 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const kelasRoutes = require('./routes/kelas');
const guruRoutes = require('./routes/guru');
const siswaRoutes = require('./routes/siswa');
const mata_pelajaranRoutes = require('./routes/mata_pelajaran');
const kktpRoutes = require('./routes/kktp');
const kktp_detailRoutes = require('./routes/kktp_detail');
const nilaiRoutes = require('./routes/nilai');
const sikapRoutes = require('./routes/sikap');
const materiRoutes = require('./routes/materi');
const tugasRoutes = require('./routes/tugas');
const pengumpulan_tugasRoutes = require('./routes/pengumpulan_tugas');
const absensiRoutes = require('./routes/absensi');
const pengumumanRoutes = require('./routes/pengumuman');
const notifikasiRoutes = require('./routes/notifikasi');
const ai_insightsRoutes = require('./routes/ai_insights');
const raport_descriptionsRoutes = require('./routes/raport_descriptions');
const audit_logsRoutes = require('./routes/audit_logs');
const import_jobsRoutes = require('./routes/import_jobs');
const getBaseUrl = (url) => {
if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url;
};
const options = {
definition: {
openapi: "3.0.0",
info: {
version: "1.0.0",
title: "SMPN 1 Seponti Digital",
description: "SMPN 1 Seponti Digital Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
},
servers: [
{
url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
description: "Development server",
}
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
},
responses: {
UnauthorizedError: {
description: "Access token is missing or invalid"
}
}
},
security: [{
bearerAuth: []
}]
},
apis: ["./src/routes/*.js"],
};
const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
next()
}, swaggerUI.serve, swaggerUI.setup(specs))
app.use(cors({origin: true}));
require('./auth/auth');
app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');
app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);
app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);
app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);
app.use('/api/kelas', passport.authenticate('jwt', {session: false}), kelasRoutes);
app.use('/api/guru', passport.authenticate('jwt', {session: false}), guruRoutes);
app.use('/api/siswa', passport.authenticate('jwt', {session: false}), siswaRoutes);
app.use('/api/mata_pelajaran', passport.authenticate('jwt', {session: false}), mata_pelajaranRoutes);
app.use('/api/kktp', passport.authenticate('jwt', {session: false}), kktpRoutes);
app.use('/api/kktp_detail', passport.authenticate('jwt', {session: false}), kktp_detailRoutes);
app.use('/api/nilai', passport.authenticate('jwt', {session: false}), nilaiRoutes);
app.use('/api/sikap', passport.authenticate('jwt', {session: false}), sikapRoutes);
app.use('/api/materi', passport.authenticate('jwt', {session: false}), materiRoutes);
app.use('/api/tugas', passport.authenticate('jwt', {session: false}), tugasRoutes);
app.use('/api/pengumpulan_tugas', passport.authenticate('jwt', {session: false}), pengumpulan_tugasRoutes);
app.use('/api/absensi', passport.authenticate('jwt', {session: false}), absensiRoutes);
app.use('/api/pengumuman', passport.authenticate('jwt', {session: false}), pengumumanRoutes);
app.use('/api/notifikasi', passport.authenticate('jwt', {session: false}), notifikasiRoutes);
app.use('/api/ai_insights', passport.authenticate('jwt', {session: false}), ai_insightsRoutes);
app.use('/api/raport_descriptions', passport.authenticate('jwt', {session: false}), raport_descriptionsRoutes);
app.use('/api/audit_logs', passport.authenticate('jwt', {session: false}), audit_logsRoutes);
app.use('/api/import_jobs', passport.authenticate('jwt', {session: false}), import_jobsRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
module.exports = app;

View File

@ -0,0 +1,149 @@
const ValidationError = require('../services/notifications/errors/validation');
const RolesDBApi = require('../db/api/roles');
// Cache for the 'Public' role object
let publicRoleCache = null;
// Function to asynchronously fetch and cache the 'Public' role
async function fetchAndCachePublicRole() {
try {
// Use RolesDBApi to find the role by name 'Public'
publicRoleCache = await RolesDBApi.findBy({ name: 'Public' });
if (!publicRoleCache) {
console.error("WARNING: Role 'Public' not found in database during middleware startup. Check your migrations.");
// The system might not function correctly without this role. May need to throw an error or use a fallback stub.
} else {
console.log("'Public' role successfully loaded and cached.");
}
} catch (error) {
console.error("Error fetching 'Public' role during middleware startup:", error);
// Handle the error during startup fetch
throw error; // Important to know if the app can proceed without the Public role
}
}
// Trigger the role fetching when the check-permissions.js module is imported/loaded
// This should happen during application startup when routes are being configured.
fetchAndCachePublicRole().catch(error => {
// Handle the case where the fetchAndCachePublicRole promise is rejected
console.error("Critical error during permissions middleware initialization:", error);
// Decide here if the process should exit if the Public role is essential.
// process.exit(1);
});
/**
* Middleware creator to check if the current user (or Public role) has a specific permission.
* @param {string} permission - The name of the required permission.
* @return {import("express").RequestHandler} Express middleware function.
*/
function checkPermissions(permission) {
return async (req, res, next) => {
const { currentUser } = req;
// 1. Check self-access bypass (only if the user is authenticated)
if (currentUser && (currentUser.id === req.params.id || currentUser.id === req.body.id)) {
return next(); // User has access to their own resource
}
// 2. Check Custom Permissions (only if the user is authenticated)
if (currentUser) {
// Ensure custom_permissions is an array before using find
const customPermissions = Array.isArray(currentUser.custom_permissions)
? currentUser.custom_permissions
: [];
const userPermission = customPermissions.find(
(cp) => cp.name === permission,
);
if (userPermission) {
return next(); // User has a custom permission
}
}
// 3. Determine the "effective" role for permission check
let effectiveRole = null;
try {
if (currentUser && currentUser.app_role) {
// User is authenticated and has an assigned role
effectiveRole = currentUser.app_role;
} else {
// User is NOT authenticated OR is authenticated but has no role
// Use the cached 'Public' role
if (!publicRoleCache) {
// If the cache is unexpectedly empty (e.g., startup error caught),
// we can try fetching the role again synchronously (less ideal) or just deny access.
console.error("Public role cache is empty. Attempting synchronous fetch...");
// Less efficient fallback option:
effectiveRole = await RolesDBApi.findBy({ name: 'Public' }); // Could be slow
if (!effectiveRole) {
// If even the synchronous attempt failed
return next(new Error("Internal Server Error: Public role missing and cannot be fetched."));
}
} else {
effectiveRole = publicRoleCache; // Use the cached object
}
}
// Check if we got a valid role object
if (!effectiveRole) {
return next(new Error("Internal Server Error: Could not determine effective role."));
}
// 4. Check Permissions on the "effective" role
// Assume the effectiveRole object (from app_role or RolesDBApi) has a getPermissions() method
// or a 'permissions' property (if permissions are eagerly loaded).
let rolePermissions = [];
if (typeof effectiveRole.getPermissions === 'function') {
rolePermissions = await effectiveRole.getPermissions(); // Get permissions asynchronously if the method exists
} else if (Array.isArray(effectiveRole.permissions)) {
rolePermissions = effectiveRole.permissions; // Or take from property if permissions are pre-loaded
} else {
console.error("Role object lacks getPermissions() method or permissions property:", effectiveRole);
return next(new Error("Internal Server Error: Invalid role object format."));
}
if (rolePermissions.find((p) => p.name === permission)) {
next(); // The "effective" role has the required permission
} else {
// The "effective" role does not have the required permission
const roleName = effectiveRole.name || 'unknown role';
next(new ValidationError('auth.forbidden', `Role '${roleName}' denied access to '${permission}'.`));
}
} catch (e) {
// Handle errors during role or permission fetching
console.error("Error during permission check:", e);
next(e); // Pass the error to the next middleware
}
};
}
const METHOD_MAP = {
POST: 'CREATE',
GET: 'READ',
PUT: 'UPDATE',
PATCH: 'UPDATE',
DELETE: 'DELETE',
};
/**
* Middleware creator to check standard CRUD permissions based on HTTP method and entity name.
* @param {string} name - The name of the entity.
* @return {import("express").RequestHandler} Express middleware function.
*/
function checkCrudPermissions(name) {
return (req, res, next) => {
// Dynamically determine the permission name (e.g., 'READ_USERS')
const permissionName = `${METHOD_MAP[req.method]}_${name.toUpperCase()}`;
// Call the checkPermissions middleware with the determined permission
checkPermissions(permissionName)(req, res, next);
};
}
module.exports = {
checkPermissions,
checkCrudPermissions,
};

View File

@ -0,0 +1,11 @@
const util = require('util');
const Multer = require('multer');
const maxSize = 10 * 1024 * 1024;
let processFile = Multer({
storage: Multer.memoryStorage(),
limits: { fileSize: maxSize },
}).single("file");
let processFileMiddleware = util.promisify(processFile);
module.exports = processFileMiddleware;

View File

@ -0,0 +1,430 @@
const express = require('express');
const AbsensiService = require('../services/absensi');
const AbsensiDBApi = require('../db/api/absensi');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('absensi'));
/**
* @swagger
* components:
* schemas:
* Absensi:
* type: object
* properties:
* keterangan:
* type: string
* default: keterangan
*
*/
/**
* @swagger
* tags:
* name: Absensi
* description: The Absensi managing API
*/
/**
* @swagger
* /api/absensi:
* post:
* security:
* - bearerAuth: []
* tags: [Absensi]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Absensi"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Absensi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await AbsensiService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Absensi]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Absensi"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Absensi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await AbsensiService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/absensi/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Absensi]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Absensi"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Absensi"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await AbsensiService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/absensi/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Absensi]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Absensi"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await AbsensiService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/absensi/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Absensi]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Absensi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await AbsensiService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/absensi:
* get:
* security:
* - bearerAuth: []
* tags: [Absensi]
* summary: Get all absensi
* description: Get all absensi
* responses:
* 200:
* description: Absensi list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Absensi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await AbsensiDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','keterangan',
'tanggal',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/absensi/count:
* get:
* security:
* - bearerAuth: []
* tags: [Absensi]
* summary: Count all absensi
* description: Count all absensi
* responses:
* 200:
* description: Absensi count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Absensi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await AbsensiDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/absensi/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Absensi]
* summary: Find all absensi that match search criteria
* description: Find all absensi that match search criteria
* responses:
* 200:
* description: Absensi list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Absensi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await AbsensiDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/absensi/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Absensi]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Absensi"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await AbsensiDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,436 @@
const express = require('express');
const Ai_insightsService = require('../services/ai_insights');
const Ai_insightsDBApi = require('../db/api/ai_insights');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('ai_insights'));
/**
* @swagger
* components:
* schemas:
* Ai_insights:
* type: object
* properties:
* ringkasan:
* type: string
* default: ringkasan
* rekomendasi:
* type: string
* default: rekomendasi
* skor_keyakinan:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Ai_insights
* description: The Ai_insights managing API
*/
/**
* @swagger
* /api/ai_insights:
* post:
* security:
* - bearerAuth: []
* tags: [Ai_insights]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Ai_insights"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_insights"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Ai_insightsService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Ai_insights]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Ai_insights"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_insights"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Ai_insightsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_insights/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Ai_insights]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Ai_insights"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_insights"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await Ai_insightsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_insights/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Ai_insights]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_insights"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await Ai_insightsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_insights/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Ai_insights]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_insights"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Ai_insightsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_insights:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_insights]
* summary: Get all ai_insights
* description: Get all ai_insights
* responses:
* 200:
* description: Ai_insights list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Ai_insights"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await Ai_insightsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','ringkasan','rekomendasi',
'skor_keyakinan',
'generated_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/ai_insights/count:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_insights]
* summary: Count all ai_insights
* description: Count all ai_insights
* responses:
* 200:
* description: Ai_insights count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Ai_insights"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Ai_insightsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_insights/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_insights]
* summary: Find all ai_insights that match search criteria
* description: Find all ai_insights that match search criteria
* responses:
* 200:
* description: Ai_insights list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Ai_insights"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Ai_insightsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/ai_insights/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_insights]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_insights"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await Ai_insightsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,442 @@
const express = require('express');
const Audit_logsService = require('../services/audit_logs');
const Audit_logsDBApi = require('../db/api/audit_logs');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('audit_logs'));
/**
* @swagger
* components:
* schemas:
* Audit_logs:
* type: object
* properties:
* entity_name:
* type: string
* default: entity_name
* entity_key:
* type: string
* default: entity_key
* summary:
* type: string
* default: summary
* ip_address:
* type: string
* default: ip_address
* user_agent:
* type: string
* default: user_agent
*
*/
/**
* @swagger
* tags:
* name: Audit_logs
* description: The Audit_logs managing API
*/
/**
* @swagger
* /api/audit_logs:
* post:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Audit_logs"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Audit_logsService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Audit_logs"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Audit_logsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Audit_logs"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await Audit_logsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await Audit_logsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Audit_logsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Get all audit_logs
* description: Get all audit_logs
* responses:
* 200:
* description: Audit_logs list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Audit_logs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await Audit_logsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','entity_name','entity_key','summary','ip_address','user_agent',
'logged_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/audit_logs/count:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Count all audit_logs
* description: Count all audit_logs
* responses:
* 200:
* description: Audit_logs count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Audit_logs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Audit_logsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Find all audit_logs that match search criteria
* description: Find all audit_logs that match search criteria
* responses:
* 200:
* description: Audit_logs list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Audit_logs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Audit_logsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/audit_logs/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await Audit_logsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

207
backend/src/routes/auth.js Normal file
View File

@ -0,0 +1,207 @@
const express = require('express');
const passport = require('passport');
const config = require('../config');
const AuthService = require('../services/auth');
const ForbiddenError = require('../services/notifications/errors/forbidden');
const EmailSender = require('../services/email');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
/**
* @swagger
* components:
* schemas:
* Auth:
* type: object
* required:
* - email
* - password
* properties:
* email:
* type: string
* default: admin@flatlogic.com
* description: User email
* password:
* type: string
* default: password
* description: User password
*/
/**
* @swagger
* tags:
* name: Auth
* description: Authorization operations
*/
/**
* @swagger
* /api/auth/signin/local:
* post:
* tags: [Auth]
* summary: Logs user into the system
* description: Logs user into the system
* requestBody:
* description: Set valid user email and password
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Auth"
* responses:
* 200:
* description: Successful login
* 400:
* description: Invalid username/password supplied
* x-codegen-request-body-name: body
*/
router.post('/signin/local', wrapAsync(async (req, res) => {
const payload = await AuthService.signin(req.body.email, req.body.password, req,);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/auth/me:
* get:
* security:
* - bearerAuth: []
* tags: [Auth]
* summary: Get current authorized user info
* description: Get current authorized user info
* responses:
* 200:
* description: Successful retrieval of current authorized user data
* 400:
* description: Invalid username/password supplied
* x-codegen-request-body-name: body
*/
router.get('/me', passport.authenticate('jwt', {session: false}), (req, res) => {
if (!req.currentUser || !req.currentUser.id) {
throw new ForbiddenError();
}
const payload = req.currentUser;
delete payload.password;
res.status(200).send(payload);
});
router.put('/password-reset', wrapAsync(async (req, res) => {
const payload = await AuthService.passwordReset(req.body.token, req.body.password, req,);
res.status(200).send(payload);
}));
router.put('/password-update', passport.authenticate('jwt', {session: false}), wrapAsync(async (req, res) => {
const payload = await AuthService.passwordUpdate(req.body.currentPassword, req.body.newPassword, req);
res.status(200).send(payload);
}));
router.post('/send-email-address-verification-email', passport.authenticate('jwt', {session: false}), wrapAsync(async (req, res) => {
if (!req.currentUser) {
throw new ForbiddenError();
}
await AuthService.sendEmailAddressVerificationEmail(req.currentUser.email);
const payload = true;
res.status(200).send(payload);
}));
router.post('/send-password-reset-email', wrapAsync(async (req, res) => {
const link = new URL(req.headers.referer);
await AuthService.sendPasswordResetEmail(req.body.email, 'register', link.host,);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/auth/signup:
* post:
* tags: [Auth]
* summary: Register new user into the system
* description: Register new user into the system
* requestBody:
* description: Set valid user email and password
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Auth"
* responses:
* 200:
* description: New user successfully signed up
* 400:
* description: Invalid username/password supplied
* 500:
* description: Some server error
* x-codegen-request-body-name: body
*/
router.post('/signup', wrapAsync(async (req, res) => {
const link = new URL(req.headers.referer);
const payload = await AuthService.signup(
req.body.email,
req.body.password,
req,
link.host,
)
res.status(200).send(payload);
}));
router.put('/profile', passport.authenticate('jwt', {session: false}), wrapAsync(async (req, res) => {
if (!req.currentUser || !req.currentUser.id) {
throw new ForbiddenError();
}
await AuthService.updateProfile(req.body.profile, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
router.put('/verify-email', wrapAsync(async (req, res) => {
const payload = await AuthService.verifyEmail(req.body.token, req, req.headers.referer)
res.status(200).send(payload);
}));
router.get('/email-configured', (req, res) => {
const payload = EmailSender.isConfigured;
res.status(200).send(payload);
});
router.get('/signin/google', (req, res, next) => {
passport.authenticate("google", {scope: ["profile", "email"], state: req.query.app})(req, res, next);
});
router.get('/signin/google/callback', passport.authenticate("google", {failureRedirect: "/login", session: false}),
function (req, res) {
socialRedirect(res, req.query.state, req.user.token, config);
}
);
router.get('/signin/microsoft', (req, res, next) => {
passport.authenticate("microsoft", {
scope: ["https://graph.microsoft.com/user.read openid"],
state: req.query.app
})(req, res, next);
});
router.get('/signin/microsoft/callback', passport.authenticate("microsoft", {
failureRedirect: "/login",
session: false
}),
function (req, res) {
socialRedirect(res, req.query.state, req.user.token, config);
}
);
router.use('/', require('../helpers').commonErrorHandler);
function socialRedirect(res, state, token, config) {
res.redirect(config.uiUrl + "/login?token=" + token);
}
module.exports = router;

View File

View File

@ -0,0 +1,32 @@
const express = require('express');
const config = require('../config');
const path = require('path');
const passport = require('passport');
const services = require('../services/file');
const router = express.Router();
router.get('/download', (req, res) => {
if (process.env.NODE_ENV == "production" || process.env.NEXT_PUBLIC_BACK_API) {
services.downloadGCloud(req, res);
}
else {
services.downloadLocal(req, res);
}
});
router.post('/upload/:table/:field', passport.authenticate('jwt', {session: false}), (req, res) => {
const fileName = `${req.params.table}/${req.params.field}`;
if (process.env.NODE_ENV == "production" || process.env.NEXT_PUBLIC_BACK_API) {
services.uploadGCloud(fileName, req, res);
}
else {
services.uploadLocal(fileName, {
entity: null,
maxFileSize: 10 * 1024 * 1024,
folderIncludesAuthenticationUid: false,
})(req, res);
}
});
module.exports = router;

444
backend/src/routes/guru.js Normal file
View File

@ -0,0 +1,444 @@
const express = require('express');
const GuruService = require('../services/guru');
const GuruDBApi = require('../db/api/guru');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('guru'));
/**
* @swagger
* components:
* schemas:
* Guru:
* type: object
* properties:
* nip:
* type: string
* default: nip
* nama:
* type: string
* default: nama
* jenis_kelamin:
* type: string
* default: jenis_kelamin
* tempat_lahir:
* type: string
* default: tempat_lahir
* alamat:
* type: string
* default: alamat
* no_hp:
* type: string
* default: no_hp
*/
/**
* @swagger
* tags:
* name: Guru
* description: The Guru managing API
*/
/**
* @swagger
* /api/guru:
* post:
* security:
* - bearerAuth: []
* tags: [Guru]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Guru"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Guru"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await GuruService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Guru]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Guru"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Guru"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await GuruService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/guru/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Guru]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Guru"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Guru"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await GuruService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/guru/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Guru]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Guru"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await GuruService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/guru/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Guru]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Guru"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await GuruService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/guru:
* get:
* security:
* - bearerAuth: []
* tags: [Guru]
* summary: Get all guru
* description: Get all guru
* responses:
* 200:
* description: Guru list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Guru"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await GuruDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','nip','nama','jenis_kelamin','tempat_lahir','alamat','no_hp',
'tanggal_lahir',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/guru/count:
* get:
* security:
* - bearerAuth: []
* tags: [Guru]
* summary: Count all guru
* description: Count all guru
* responses:
* 200:
* description: Guru count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Guru"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await GuruDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/guru/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Guru]
* summary: Find all guru that match search criteria
* description: Find all guru that match search criteria
* responses:
* 200:
* description: Guru list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Guru"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await GuruDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/guru/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Guru]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Guru"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await GuruDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,440 @@
const express = require('express');
const Import_jobsService = require('../services/import_jobs');
const Import_jobsDBApi = require('../db/api/import_jobs');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('import_jobs'));
/**
* @swagger
* components:
* schemas:
* Import_jobs:
* type: object
* properties:
* error_report:
* type: string
* default: error_report
* total_rows:
* type: integer
* format: int64
* success_rows:
* type: integer
* format: int64
* failed_rows:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Import_jobs
* description: The Import_jobs managing API
*/
/**
* @swagger
* /api/import_jobs:
* post:
* security:
* - bearerAuth: []
* tags: [Import_jobs]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Import_jobs"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Import_jobs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Import_jobsService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Import_jobs]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Import_jobs"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Import_jobs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Import_jobsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/import_jobs/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Import_jobs]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Import_jobs"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Import_jobs"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await Import_jobsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/import_jobs/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Import_jobs]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Import_jobs"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await Import_jobsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/import_jobs/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Import_jobs]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Import_jobs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Import_jobsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/import_jobs:
* get:
* security:
* - bearerAuth: []
* tags: [Import_jobs]
* summary: Get all import_jobs
* description: Get all import_jobs
* responses:
* 200:
* description: Import_jobs list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Import_jobs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await Import_jobsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','error_report',
'total_rows','success_rows','failed_rows',
'started_at','finished_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/import_jobs/count:
* get:
* security:
* - bearerAuth: []
* tags: [Import_jobs]
* summary: Count all import_jobs
* description: Count all import_jobs
* responses:
* 200:
* description: Import_jobs count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Import_jobs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Import_jobsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/import_jobs/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Import_jobs]
* summary: Find all import_jobs that match search criteria
* description: Find all import_jobs that match search criteria
* responses:
* 200:
* description: Import_jobs list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Import_jobs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Import_jobsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/import_jobs/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Import_jobs]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Import_jobs"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await Import_jobsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

436
backend/src/routes/kelas.js Normal file
View File

@ -0,0 +1,436 @@
const express = require('express');
const KelasService = require('../services/kelas');
const KelasDBApi = require('../db/api/kelas');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('kelas'));
/**
* @swagger
* components:
* schemas:
* Kelas:
* type: object
* properties:
* nama_kelas:
* type: string
* default: nama_kelas
* tingkat:
* type: string
* default: tingkat
* tahun_ajaran:
* type: string
* default: tahun_ajaran
*
*/
/**
* @swagger
* tags:
* name: Kelas
* description: The Kelas managing API
*/
/**
* @swagger
* /api/kelas:
* post:
* security:
* - bearerAuth: []
* tags: [Kelas]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Kelas"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kelas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await KelasService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Kelas]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Kelas"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kelas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await KelasService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kelas/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Kelas]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Kelas"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kelas"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await KelasService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kelas/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Kelas]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kelas"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await KelasService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kelas/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Kelas]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kelas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await KelasService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kelas:
* get:
* security:
* - bearerAuth: []
* tags: [Kelas]
* summary: Get all kelas
* description: Get all kelas
* responses:
* 200:
* description: Kelas list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Kelas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await KelasDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','nama_kelas','tingkat','tahun_ajaran',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/kelas/count:
* get:
* security:
* - bearerAuth: []
* tags: [Kelas]
* summary: Count all kelas
* description: Count all kelas
* responses:
* 200:
* description: Kelas count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Kelas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await KelasDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kelas/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Kelas]
* summary: Find all kelas that match search criteria
* description: Find all kelas that match search criteria
* responses:
* 200:
* description: Kelas list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Kelas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await KelasDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/kelas/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Kelas]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kelas"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await KelasDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

435
backend/src/routes/kktp.js Normal file
View File

@ -0,0 +1,435 @@
const express = require('express');
const KktpService = require('../services/kktp');
const KktpDBApi = require('../db/api/kktp');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('kktp'));
/**
* @swagger
* components:
* schemas:
* Kktp:
* type: object
* properties:
* fase:
* type: string
* default: fase
* deskripsi_umum:
* type: string
* default: deskripsi_umum
* nilai_minimum:
* type: integer
* format: int64
*/
/**
* @swagger
* tags:
* name: Kktp
* description: The Kktp managing API
*/
/**
* @swagger
* /api/kktp:
* post:
* security:
* - bearerAuth: []
* tags: [Kktp]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Kktp"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await KktpService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Kktp]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Kktp"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await KktpService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kktp/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Kktp]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Kktp"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await KktpService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kktp/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Kktp]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await KktpService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kktp/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Kktp]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await KktpService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kktp:
* get:
* security:
* - bearerAuth: []
* tags: [Kktp]
* summary: Get all kktp
* description: Get all kktp
* responses:
* 200:
* description: Kktp list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Kktp"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await KktpDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','fase','deskripsi_umum',
'nilai_minimum',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/kktp/count:
* get:
* security:
* - bearerAuth: []
* tags: [Kktp]
* summary: Count all kktp
* description: Count all kktp
* responses:
* 200:
* description: Kktp count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Kktp"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await KktpDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kktp/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Kktp]
* summary: Find all kktp that match search criteria
* description: Find all kktp that match search criteria
* responses:
* 200:
* description: Kktp list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Kktp"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await KktpDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/kktp/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Kktp]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await KktpDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,436 @@
const express = require('express');
const Kktp_detailService = require('../services/kktp_detail');
const Kktp_detailDBApi = require('../db/api/kktp_detail');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('kktp_detail'));
/**
* @swagger
* components:
* schemas:
* Kktp_detail:
* type: object
* properties:
* deskripsi:
* type: string
* default: deskripsi
* nilai_min:
* type: integer
* format: int64
* nilai_max:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Kktp_detail
* description: The Kktp_detail managing API
*/
/**
* @swagger
* /api/kktp_detail:
* post:
* security:
* - bearerAuth: []
* tags: [Kktp_detail]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Kktp_detail"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp_detail"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Kktp_detailService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Kktp_detail]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Kktp_detail"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp_detail"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Kktp_detailService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kktp_detail/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Kktp_detail]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Kktp_detail"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp_detail"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await Kktp_detailService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kktp_detail/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Kktp_detail]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp_detail"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await Kktp_detailService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kktp_detail/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Kktp_detail]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp_detail"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Kktp_detailService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kktp_detail:
* get:
* security:
* - bearerAuth: []
* tags: [Kktp_detail]
* summary: Get all kktp_detail
* description: Get all kktp_detail
* responses:
* 200:
* description: Kktp_detail list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Kktp_detail"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await Kktp_detailDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','deskripsi',
'nilai_min','nilai_max',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/kktp_detail/count:
* get:
* security:
* - bearerAuth: []
* tags: [Kktp_detail]
* summary: Count all kktp_detail
* description: Count all kktp_detail
* responses:
* 200:
* description: Kktp_detail count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Kktp_detail"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Kktp_detailDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/kktp_detail/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Kktp_detail]
* summary: Find all kktp_detail that match search criteria
* description: Find all kktp_detail that match search criteria
* responses:
* 200:
* description: Kktp_detail list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Kktp_detail"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Kktp_detailDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/kktp_detail/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Kktp_detail]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Kktp_detail"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await Kktp_detailDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,436 @@
const express = require('express');
const Mata_pelajaranService = require('../services/mata_pelajaran');
const Mata_pelajaranDBApi = require('../db/api/mata_pelajaran');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('mata_pelajaran'));
/**
* @swagger
* components:
* schemas:
* Mata_pelajaran:
* type: object
* properties:
* kode_mapel:
* type: string
* default: kode_mapel
* nama_mapel:
* type: string
* default: nama_mapel
* urutan:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Mata_pelajaran
* description: The Mata_pelajaran managing API
*/
/**
* @swagger
* /api/mata_pelajaran:
* post:
* security:
* - bearerAuth: []
* tags: [Mata_pelajaran]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Mata_pelajaran"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Mata_pelajaran"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Mata_pelajaranService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Mata_pelajaran]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Mata_pelajaran"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Mata_pelajaran"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Mata_pelajaranService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/mata_pelajaran/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Mata_pelajaran]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Mata_pelajaran"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Mata_pelajaran"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await Mata_pelajaranService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/mata_pelajaran/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Mata_pelajaran]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Mata_pelajaran"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await Mata_pelajaranService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/mata_pelajaran/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Mata_pelajaran]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Mata_pelajaran"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Mata_pelajaranService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/mata_pelajaran:
* get:
* security:
* - bearerAuth: []
* tags: [Mata_pelajaran]
* summary: Get all mata_pelajaran
* description: Get all mata_pelajaran
* responses:
* 200:
* description: Mata_pelajaran list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Mata_pelajaran"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await Mata_pelajaranDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','kode_mapel','nama_mapel',
'urutan',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/mata_pelajaran/count:
* get:
* security:
* - bearerAuth: []
* tags: [Mata_pelajaran]
* summary: Count all mata_pelajaran
* description: Count all mata_pelajaran
* responses:
* 200:
* description: Mata_pelajaran count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Mata_pelajaran"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Mata_pelajaranDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/mata_pelajaran/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Mata_pelajaran]
* summary: Find all mata_pelajaran that match search criteria
* description: Find all mata_pelajaran that match search criteria
* responses:
* 200:
* description: Mata_pelajaran list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Mata_pelajaran"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Mata_pelajaranDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/mata_pelajaran/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Mata_pelajaran]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Mata_pelajaran"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await Mata_pelajaranDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,436 @@
const express = require('express');
const MateriService = require('../services/materi');
const MateriDBApi = require('../db/api/materi');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('materi'));
/**
* @swagger
* components:
* schemas:
* Materi:
* type: object
* properties:
* judul:
* type: string
* default: judul
* deskripsi:
* type: string
* default: deskripsi
* url_video:
* type: string
* default: url_video
*
*/
/**
* @swagger
* tags:
* name: Materi
* description: The Materi managing API
*/
/**
* @swagger
* /api/materi:
* post:
* security:
* - bearerAuth: []
* tags: [Materi]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Materi"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Materi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await MateriService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Materi]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Materi"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Materi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await MateriService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/materi/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Materi]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Materi"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Materi"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await MateriService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/materi/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Materi]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Materi"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await MateriService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/materi/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Materi]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Materi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await MateriService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/materi:
* get:
* security:
* - bearerAuth: []
* tags: [Materi]
* summary: Get all materi
* description: Get all materi
* responses:
* 200:
* description: Materi list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Materi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await MateriDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','judul','deskripsi','url_video',
'published_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/materi/count:
* get:
* security:
* - bearerAuth: []
* tags: [Materi]
* summary: Count all materi
* description: Count all materi
* responses:
* 200:
* description: Materi count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Materi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await MateriDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/materi/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Materi]
* summary: Find all materi that match search criteria
* description: Find all materi that match search criteria
* responses:
* 200:
* description: Materi list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Materi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await MateriDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/materi/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Materi]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Materi"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await MateriDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

437
backend/src/routes/nilai.js Normal file
View File

@ -0,0 +1,437 @@
const express = require('express');
const NilaiService = require('../services/nilai');
const NilaiDBApi = require('../db/api/nilai');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('nilai'));
/**
* @swagger
* components:
* schemas:
* Nilai:
* type: object
* properties:
* judul_penilaian:
* type: string
* default: judul_penilaian
* deskripsi_kktp:
* type: string
* default: deskripsi_kktp
* skor:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Nilai
* description: The Nilai managing API
*/
/**
* @swagger
* /api/nilai:
* post:
* security:
* - bearerAuth: []
* tags: [Nilai]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Nilai"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Nilai"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await NilaiService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Nilai]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Nilai"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Nilai"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await NilaiService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/nilai/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Nilai]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Nilai"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Nilai"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await NilaiService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/nilai/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Nilai]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Nilai"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await NilaiService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/nilai/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Nilai]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Nilai"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await NilaiService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/nilai:
* get:
* security:
* - bearerAuth: []
* tags: [Nilai]
* summary: Get all nilai
* description: Get all nilai
* responses:
* 200:
* description: Nilai list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Nilai"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await NilaiDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','judul_penilaian','deskripsi_kktp',
'skor',
'tanggal_penilaian',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/nilai/count:
* get:
* security:
* - bearerAuth: []
* tags: [Nilai]
* summary: Count all nilai
* description: Count all nilai
* responses:
* 200:
* description: Nilai count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Nilai"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await NilaiDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/nilai/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Nilai]
* summary: Find all nilai that match search criteria
* description: Find all nilai that match search criteria
* responses:
* 200:
* description: Nilai list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Nilai"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await NilaiDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/nilai/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Nilai]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Nilai"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await NilaiDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,434 @@
const express = require('express');
const NotifikasiService = require('../services/notifikasi');
const NotifikasiDBApi = require('../db/api/notifikasi');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('notifikasi'));
/**
* @swagger
* components:
* schemas:
* Notifikasi:
* type: object
* properties:
* judul:
* type: string
* default: judul
* pesan:
* type: string
* default: pesan
*
*
*/
/**
* @swagger
* tags:
* name: Notifikasi
* description: The Notifikasi managing API
*/
/**
* @swagger
* /api/notifikasi:
* post:
* security:
* - bearerAuth: []
* tags: [Notifikasi]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Notifikasi"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Notifikasi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await NotifikasiService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Notifikasi]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Notifikasi"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Notifikasi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await NotifikasiService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/notifikasi/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Notifikasi]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Notifikasi"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Notifikasi"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await NotifikasiService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/notifikasi/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Notifikasi]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Notifikasi"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await NotifikasiService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/notifikasi/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Notifikasi]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Notifikasi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await NotifikasiService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/notifikasi:
* get:
* security:
* - bearerAuth: []
* tags: [Notifikasi]
* summary: Get all notifikasi
* description: Get all notifikasi
* responses:
* 200:
* description: Notifikasi list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Notifikasi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await NotifikasiDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','judul','pesan',
'sent_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/notifikasi/count:
* get:
* security:
* - bearerAuth: []
* tags: [Notifikasi]
* summary: Count all notifikasi
* description: Count all notifikasi
* responses:
* 200:
* description: Notifikasi count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Notifikasi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await NotifikasiDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/notifikasi/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Notifikasi]
* summary: Find all notifikasi that match search criteria
* description: Find all notifikasi that match search criteria
* responses:
* 200:
* description: Notifikasi list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Notifikasi"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await NotifikasiDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/notifikasi/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Notifikasi]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Notifikasi"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await NotifikasiDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,328 @@
const express = require('express');
const db = require('../db/models');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const sjs = require('sequelize-json-schema');
const { getWidget, askGpt } = require('../services/openai');
const { LocalAIApi } = require('../ai/LocalAIApi');
const loadRolesModules = () => {
try {
return {
RolesService: require('../services/roles'),
RolesDBApi: require('../db/api/roles'),
};
} catch (error) {
console.error('Roles modules are missing. Advanced roles are required for this endpoint.', error);
const err = new Error('Roles modules are missing. Advanced roles are required for this endpoint.');
err.originalError = error;
throw err;
}
};
/**
* @swagger
* /api/roles/roles-info/{infoId}:
* delete:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Remove role information by ID
* description: Remove specific role information by ID
* parameters:
* - in: path
* name: infoId
* description: ID of role information to remove
* required: true
* schema:
* type: string
* - in: query
* name: userId
* description: ID of the user
* required: true
* schema:
* type: string
* - in: query
* name: key
* description: Key of the role information to remove
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Role information successfully removed
* content:
* application/json:
* schema:
* type: object
* properties:
* user:
* type: string
* description: The user information
* 400:
* description: Invalid ID or key supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Role not found
* 500:
* description: Some server error
*/
router.delete(
'/roles-info/:infoId',
wrapAsync(async (req, res) => {
const { RolesService } = loadRolesModules();
const role = await RolesService.removeRoleInfoById(
req.query.infoId,
req.query.roleId,
req.query.key,
req.currentUser,
);
res.status(200).send(role);
}),
);
/**
* @swagger
* /api/roles/role-info/{roleId}:
* get:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Get role information by key
* description: Get specific role information by key
* parameters:
* - in: path
* name: roleId
* description: ID of role to get information for
* required: true
* schema:
* type: string
* - in: query
* name: key
* description: Key of the role information to retrieve
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Role information successfully received
* content:
* application/json:
* schema:
* type: object
* properties:
* info:
* type: string
* description: The role information
* 400:
* description: Invalid ID or key supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Role not found
* 500:
* description: Some server error
*/
router.get(
'/info-by-key',
wrapAsync(async (req, res) => {
const { RolesService, RolesDBApi } = loadRolesModules();
const roleId = req.query.roleId;
const key = req.query.key;
const currentUser = req.currentUser;
let info = await RolesService.getRoleInfoByKey(
key,
roleId,
currentUser,
);
const role = await RolesDBApi.findBy({ id: roleId });
if (!role?.role_customization) {
await Promise.all(["pie", "bar"].map(async (e) => {
const schema = await sjs.getSequelizeSchema(db.sequelize, {});
const payload = {
description: `Create some cool ${e} chart`,
modelDefinition: schema.definitions,
};
const widgetId = await getWidget(payload, currentUser?.id, roleId);
if (widgetId) {
await RolesService.addRoleInfo(
roleId,
currentUser?.id,
'widgets',
widgetId,
req.currentUser,
);
}
}))
info = await RolesService.getRoleInfoByKey(
key,
roleId,
currentUser,
);
}
res.status(200).send(info);
}),
);
router.post(
'/create_widget',
wrapAsync(async (req, res) => {
const { RolesService } = loadRolesModules();
const { description, userId, roleId } = req.body;
const currentUser = req.currentUser;
const schema = await sjs.getSequelizeSchema(db.sequelize, {});
const payload = {
description,
modelDefinition: schema.definitions,
};
const widgetId = await getWidget(payload, userId, roleId);
if (widgetId) {
await RolesService.addRoleInfo(
roleId,
userId,
'widgets',
widgetId,
currentUser,
);
return res.status(200).send(widgetId);
} else {
return res.status(400).send(widgetId);
}
}),
);
/**
* @swagger
* /api/openai/response:
* post:
* security:
* - bearerAuth: []
* tags: [OpenAI]
* summary: Proxy a Responses API request
* description: Sends the payload to the Flatlogic AI proxy and returns the response.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* input:
* type: array
* description: List of messages with roles and content.
* items:
* type: object
* properties:
* role:
* type: string
* content:
* type: string
* options:
* type: object
* description: Optional polling controls.
* properties:
* poll_interval:
* type: number
* poll_timeout:
* type: number
* responses:
* 200:
* description: AI response received
* 400:
* description: Invalid request
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 502:
* description: Proxy error
*/
router.post(
'/response',
wrapAsync(async (req, res) => {
const body = req.body || {};
const options = body.options || {};
const payload = { ...body };
delete payload.options;
const response = await LocalAIApi.createResponse(payload, options);
if (response.success) {
return res.status(200).send(response);
}
console.error('AI proxy error:', response);
const status = response.error === 'input_missing' ? 400 : 502;
return res.status(status).send(response);
}),
);
/**
* @swagger
* /api/openai/ask:
* post:
* security:
* - bearerAuth: []
* tags: [OpenAI]
* summary: Ask a question to ChatGPT
* description: Send a question through the Flatlogic AI proxy and get a response
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* prompt:
* type: string
* description: The question to ask ChatGPT
* responses:
* 200:
* description: Question successfully answered
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* description: Whether the request was successful
* data:
* type: string
* description: The answer from ChatGPT
* 400:
* description: Invalid request
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 500:
* description: Some server error
*/
router.post(
'/ask-gpt',
wrapAsync(async (req, res) => {
const { prompt } = req.body;
if (!prompt) {
return res.status(400).send({
success: false,
error: 'Prompt is required',
});
}
const response = await askGpt(prompt);
if (response.success) {
return res.status(200).send(response);
} else {
return res.status(500).send(response);
}
}),
);
module.exports = router;

View File

@ -0,0 +1,2 @@

View File

@ -0,0 +1,436 @@
const express = require('express');
const Pengumpulan_tugasService = require('../services/pengumpulan_tugas');
const Pengumpulan_tugasDBApi = require('../db/api/pengumpulan_tugas');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('pengumpulan_tugas'));
/**
* @swagger
* components:
* schemas:
* Pengumpulan_tugas:
* type: object
* properties:
* jawaban_teks:
* type: string
* default: jawaban_teks
* feedback_guru:
* type: string
* default: feedback_guru
* nilai:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Pengumpulan_tugas
* description: The Pengumpulan_tugas managing API
*/
/**
* @swagger
* /api/pengumpulan_tugas:
* post:
* security:
* - bearerAuth: []
* tags: [Pengumpulan_tugas]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Pengumpulan_tugas"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumpulan_tugas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Pengumpulan_tugasService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Pengumpulan_tugas]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Pengumpulan_tugas"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumpulan_tugas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Pengumpulan_tugasService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/pengumpulan_tugas/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Pengumpulan_tugas]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Pengumpulan_tugas"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumpulan_tugas"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await Pengumpulan_tugasService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/pengumpulan_tugas/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Pengumpulan_tugas]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumpulan_tugas"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await Pengumpulan_tugasService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/pengumpulan_tugas/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Pengumpulan_tugas]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumpulan_tugas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Pengumpulan_tugasService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/pengumpulan_tugas:
* get:
* security:
* - bearerAuth: []
* tags: [Pengumpulan_tugas]
* summary: Get all pengumpulan_tugas
* description: Get all pengumpulan_tugas
* responses:
* 200:
* description: Pengumpulan_tugas list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Pengumpulan_tugas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await Pengumpulan_tugasDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','jawaban_teks','feedback_guru',
'nilai',
'dikumpulkan_pada','dinilai_pada',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/pengumpulan_tugas/count:
* get:
* security:
* - bearerAuth: []
* tags: [Pengumpulan_tugas]
* summary: Count all pengumpulan_tugas
* description: Count all pengumpulan_tugas
* responses:
* 200:
* description: Pengumpulan_tugas count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Pengumpulan_tugas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Pengumpulan_tugasDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/pengumpulan_tugas/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Pengumpulan_tugas]
* summary: Find all pengumpulan_tugas that match search criteria
* description: Find all pengumpulan_tugas that match search criteria
* responses:
* 200:
* description: Pengumpulan_tugas list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Pengumpulan_tugas"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Pengumpulan_tugasDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/pengumpulan_tugas/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Pengumpulan_tugas]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumpulan_tugas"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await Pengumpulan_tugasDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,433 @@
const express = require('express');
const PengumumanService = require('../services/pengumuman');
const PengumumanDBApi = require('../db/api/pengumuman');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('pengumuman'));
/**
* @swagger
* components:
* schemas:
* Pengumuman:
* type: object
* properties:
* judul:
* type: string
* default: judul
* isi:
* type: string
* default: isi
*
*/
/**
* @swagger
* tags:
* name: Pengumuman
* description: The Pengumuman managing API
*/
/**
* @swagger
* /api/pengumuman:
* post:
* security:
* - bearerAuth: []
* tags: [Pengumuman]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Pengumuman"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumuman"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await PengumumanService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Pengumuman]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Pengumuman"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumuman"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await PengumumanService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/pengumuman/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Pengumuman]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Pengumuman"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumuman"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await PengumumanService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/pengumuman/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Pengumuman]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumuman"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await PengumumanService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/pengumuman/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Pengumuman]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumuman"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await PengumumanService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/pengumuman:
* get:
* security:
* - bearerAuth: []
* tags: [Pengumuman]
* summary: Get all pengumuman
* description: Get all pengumuman
* responses:
* 200:
* description: Pengumuman list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Pengumuman"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await PengumumanDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','judul','isi',
'published_at','expires_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/pengumuman/count:
* get:
* security:
* - bearerAuth: []
* tags: [Pengumuman]
* summary: Count all pengumuman
* description: Count all pengumuman
* responses:
* 200:
* description: Pengumuman count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Pengumuman"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await PengumumanDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/pengumuman/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Pengumuman]
* summary: Find all pengumuman that match search criteria
* description: Find all pengumuman that match search criteria
* responses:
* 200:
* description: Pengumuman list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Pengumuman"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await PengumumanDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/pengumuman/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Pengumuman]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Pengumuman"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await PengumumanDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,429 @@
const express = require('express');
const PermissionsService = require('../services/permissions');
const PermissionsDBApi = require('../db/api/permissions');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('permissions'));
/**
* @swagger
* components:
* schemas:
* Permissions:
* type: object
* properties:
* name:
* type: string
* default: name
*/
/**
* @swagger
* tags:
* name: Permissions
* description: The Permissions managing API
*/
/**
* @swagger
* /api/permissions:
* post:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Permissions"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Permissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await PermissionsService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Permissions"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Permissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await PermissionsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/permissions/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Permissions"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Permissions"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await PermissionsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/permissions/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Permissions"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await PermissionsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/permissions/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Permissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await PermissionsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/permissions:
* get:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Get all permissions
* description: Get all permissions
* responses:
* 200:
* description: Permissions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Permissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await PermissionsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/permissions/count:
* get:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Count all permissions
* description: Count all permissions
* responses:
* 200:
* description: Permissions count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Permissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await PermissionsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/permissions/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Find all permissions that match search criteria
* description: Find all permissions that match search criteria
* responses:
* 200:
* description: Permissions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Permissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await PermissionsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/permissions/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Permissions"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await PermissionsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,104 @@
const express = require('express');
const router = express.Router();
const { pexelsKey, pexelsQuery } = require('../config');
const fetch = require('node-fetch');
const KEY = pexelsKey;
router.get('/image', async (req, res) => {
const headers = {
Authorization: `${KEY}`,
};
const query = pexelsQuery || 'nature';
const orientation = 'portrait';
const perPage = 1;
const url = `https://api.pexels.com/v1/search?query=${query}&orientation=${orientation}&per_page=${perPage}&page=1`;
try {
const response = await fetch(url, { headers });
const data = await response.json();
res.status(200).json(data.photos[0]);
} catch (error) {
res.status(200).json({ error: 'Failed to fetch image' });
}
});
router.get('/video', async (req, res) => {
const headers = {
Authorization: `${KEY}`,
};
const query = pexelsQuery || 'nature';
const orientation = 'portrait';
const perPage = 1;
const url = `https://api.pexels.com/videos/search?query=${query}&orientation=${orientation}&per_page=${perPage}&page=1`;
try {
const response = await fetch(url, { headers });
const data = await response.json();
res.status(200).json(data.videos[0]);
} catch (error) {
res.status(200).json({ error: 'Failed to fetch video' });
}
});
router.get('/multiple-images', async (req, res) => {
const headers = {
Authorization: `${KEY}`,
};
const queries = req.query.queries
? req.query.queries.split(',')
: ['home', 'apple', 'pizza', 'mountains', 'cat'];
const orientation = 'square';
const perPage = 1;
const fallbackImage = {
src: 'https://images.pexels.com/photos/8199252/pexels-photo-8199252.jpeg',
photographer: 'Yan Krukau',
photographer_url: 'https://www.pexels.com/@yankrukov',
};
const fetchFallbackImage = async () => {
try {
const response = await fetch('https://picsum.photos/600');
return {
src: response.url,
photographer: 'Random Picsum',
photographer_url: 'https://picsum.photos/',
};
} catch (error) {
return fallbackImage;
}
};
const fetchImage = async (query) => {
const url = `https://api.pexels.com/v1/search?query=${query}&orientation=${orientation}&per_page=${perPage}&page=1`;
const response = await fetch(url, { headers });
const data = await response.json();
return data.photos[0] || null;
};
const imagePromises = queries.map((query) => fetchImage(query));
const imagesResults = await Promise.allSettled(imagePromises);
const formattedImages = await Promise.all(imagesResults.map(async (result) => {
if (result.status === 'fulfilled' && result.value) {
const image = result.value;
return {
src: image.src?.original || fallbackImage.src,
photographer: image.photographer || fallbackImage.photographer,
photographer_url: image.photographer_url || fallbackImage.photographer_url,
};
} else {
const fallback = await fetchFallbackImage();
return {
src: fallback.src || '',
photographer: fallback.photographer || 'Unknown',
photographer_url: fallback.photographer_url || '',
};
}
}));
res.json(formattedImages);
});
module.exports = router;

View File

@ -0,0 +1,449 @@
const express = require('express');
const Raport_descriptionsService = require('../services/raport_descriptions');
const Raport_descriptionsDBApi = require('../db/api/raport_descriptions');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('raport_descriptions'));
/**
* @swagger
* components:
* schemas:
* Raport_descriptions:
* type: object
* properties:
* tahun_ajaran:
* type: string
* default: tahun_ajaran
* deskripsi_kktp:
* type: string
* default: deskripsi_kktp
* ai_prompt:
* type: string
* default: ai_prompt
* ai_output:
* type: string
* default: ai_output
* ranking_kelas:
* type: integer
* format: int64
* nilai_akhir:
* type: integer
* format: int64
* rata_rata_kelas:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Raport_descriptions
* description: The Raport_descriptions managing API
*/
/**
* @swagger
* /api/raport_descriptions:
* post:
* security:
* - bearerAuth: []
* tags: [Raport_descriptions]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Raport_descriptions"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Raport_descriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Raport_descriptionsService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Raport_descriptions]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Raport_descriptions"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Raport_descriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Raport_descriptionsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/raport_descriptions/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Raport_descriptions]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Raport_descriptions"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Raport_descriptions"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await Raport_descriptionsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/raport_descriptions/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Raport_descriptions]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Raport_descriptions"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await Raport_descriptionsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/raport_descriptions/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Raport_descriptions]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Raport_descriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Raport_descriptionsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/raport_descriptions:
* get:
* security:
* - bearerAuth: []
* tags: [Raport_descriptions]
* summary: Get all raport_descriptions
* description: Get all raport_descriptions
* responses:
* 200:
* description: Raport_descriptions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Raport_descriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await Raport_descriptionsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','tahun_ajaran','deskripsi_kktp','ai_prompt','ai_output',
'ranking_kelas',
'nilai_akhir','rata_rata_kelas',
'generated_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/raport_descriptions/count:
* get:
* security:
* - bearerAuth: []
* tags: [Raport_descriptions]
* summary: Count all raport_descriptions
* description: Count all raport_descriptions
* responses:
* 200:
* description: Raport_descriptions count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Raport_descriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Raport_descriptionsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/raport_descriptions/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Raport_descriptions]
* summary: Find all raport_descriptions that match search criteria
* description: Find all raport_descriptions that match search criteria
* responses:
* 200:
* description: Raport_descriptions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Raport_descriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Raport_descriptionsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/raport_descriptions/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Raport_descriptions]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Raport_descriptions"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await Raport_descriptionsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

429
backend/src/routes/roles.js Normal file
View File

@ -0,0 +1,429 @@
const express = require('express');
const RolesService = require('../services/roles');
const RolesDBApi = require('../db/api/roles');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('roles'));
/**
* @swagger
* components:
* schemas:
* Roles:
* type: object
* properties:
* name:
* type: string
* default: name
*/
/**
* @swagger
* tags:
* name: Roles
* description: The Roles managing API
*/
/**
* @swagger
* /api/roles:
* post:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Roles"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Roles"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await RolesService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Roles"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Roles"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await RolesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/roles/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Roles"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Roles"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await RolesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/roles/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Roles"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await RolesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/roles/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Roles"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await RolesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/roles:
* get:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Get all roles
* description: Get all roles
* responses:
* 200:
* description: Roles list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Roles"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await RolesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/roles/count:
* get:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Count all roles
* description: Count all roles
* responses:
* 200:
* description: Roles count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Roles"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await RolesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/roles/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Find all roles that match search criteria
* description: Find all roles that match search criteria
* responses:
* 200:
* description: Roles list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Roles"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await RolesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/roles/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Roles"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await RolesDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

Some files were not shown because too many files have changed in this diff Show More