Initial version

This commit is contained in:
Flatlogic Bot 2026-02-12 05:35:14 +00:00
commit 540915c534
629 changed files with 196875 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>Sistem Sekolah Indonesia</h2>
<p>Sistem sekolah Indonesia untuk SPP, pendaftaran cicilan, absensi, jadwal, tugas, ujian, dan pengumuman multi-role.</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 @@
# Sistem Sekolah Indonesia
## 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_38373
DB_USER=app_38373
DB_PASS=dfa38d66-af0b-412f-abc2-79b8ededa8b8
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 @@
#Sistem Sekolah Indonesia - 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_sistem_sekolah_indonesia;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_sistem_sekolah_indonesia 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": "sistemsekolahindonesia",
"description": "Sistem Sekolah Indonesia - 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});
});
}

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

@ -0,0 +1,81 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "dfa38d66",
user_pass: "79b8ededa8b8",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'dfa38d66-af0b-412f-abc2-79b8ededa8b8',
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: 'Sistem Sekolah Indonesia <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: {
super_admin: 'Super Administrator',
admin: 'Administrator',
user: 'Orang Tua',
},
project_uuid: 'dfa38d66-af0b-412f-abc2-79b8ededa8b8',
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 = 'students walking to school';
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,529 @@
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 Academic_yearsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const academic_years = await db.academic_years.create(
{
id: data.id || undefined,
name: data.name
||
null
,
start_date: data.start_date
||
null
,
end_date: data.end_date
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await academic_years.setSchool( data.school || null, {
transaction,
});
return academic_years;
}
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 academic_yearsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
start_date: item.start_date
||
null
,
end_date: item.end_date
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const academic_years = await db.academic_years.bulkCreate(academic_yearsData, { transaction });
// For each item created, replace relation files
return academic_years;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const academic_years = await db.academic_years.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.start_date !== undefined) updatePayload.start_date = data.start_date;
if (data.end_date !== undefined) updatePayload.end_date = data.end_date;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await academic_years.update(updatePayload, {transaction});
if (data.school !== undefined) {
await academic_years.setSchool(
data.school,
{ transaction }
);
}
return academic_years;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const academic_years = await db.academic_years.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of academic_years) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of academic_years) {
await record.destroy({transaction});
}
});
return academic_years;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const academic_years = await db.academic_years.findByPk(id, options);
await academic_years.update({
deletedBy: currentUser.id
}, {
transaction,
});
await academic_years.destroy({
transaction
});
return academic_years;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const academic_years = await db.academic_years.findOne(
{ where },
{ transaction },
);
if (!academic_years) {
return academic_years;
}
const output = academic_years.get({plain: true});
output.classes_academic_year = await academic_years.getClasses_academic_year({
transaction
});
output.fee_definitions_academic_year = await academic_years.getFee_definitions_academic_year({
transaction
});
output.school = await academic_years.getSchool({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.schools,
as: 'school',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'academic_years',
'name',
filter.name,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_dateRange) {
const [start, end] = filter.start_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_date: {
...where.start_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_date: {
...where.start_date,
[Op.lte]: end,
},
};
}
}
if (filter.end_dateRange) {
const [start, end] = filter.end_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_date: {
...where.end_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_date: {
...where.end_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.school) {
const listItems = filter.school.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.academic_years.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'academic_years',
'name',
query,
),
],
};
}
const records = await db.academic_years.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,681 @@
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 AnnouncementsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const announcements = await db.announcements.create(
{
id: data.id || undefined,
title: data.title
||
null
,
content: data.content
||
null
,
audience: data.audience
||
null
,
publish_at: data.publish_at
||
null
,
expire_at: data.expire_at
||
null
,
pinned: data.pinned
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await announcements.setSchool( data.school || null, {
transaction,
});
await announcements.setTarget_class( data.target_class || null, {
transaction,
});
await announcements.setAuthor( data.author || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.announcements.getTableName(),
belongsToColumn: 'attachments',
belongsToId: announcements.id,
},
data.attachments,
options,
);
return announcements;
}
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 announcementsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
content: item.content
||
null
,
audience: item.audience
||
null
,
publish_at: item.publish_at
||
null
,
expire_at: item.expire_at
||
null
,
pinned: item.pinned
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const announcements = await db.announcements.bulkCreate(announcementsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < announcements.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.announcements.getTableName(),
belongsToColumn: 'attachments',
belongsToId: announcements[i].id,
},
data[i].attachments,
options,
);
}
return announcements;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const announcements = await db.announcements.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.audience !== undefined) updatePayload.audience = data.audience;
if (data.publish_at !== undefined) updatePayload.publish_at = data.publish_at;
if (data.expire_at !== undefined) updatePayload.expire_at = data.expire_at;
if (data.pinned !== undefined) updatePayload.pinned = data.pinned;
updatePayload.updatedById = currentUser.id;
await announcements.update(updatePayload, {transaction});
if (data.school !== undefined) {
await announcements.setSchool(
data.school,
{ transaction }
);
}
if (data.target_class !== undefined) {
await announcements.setTarget_class(
data.target_class,
{ transaction }
);
}
if (data.author !== undefined) {
await announcements.setAuthor(
data.author,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.announcements.getTableName(),
belongsToColumn: 'attachments',
belongsToId: announcements.id,
},
data.attachments,
options,
);
return announcements;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const announcements = await db.announcements.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of announcements) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of announcements) {
await record.destroy({transaction});
}
});
return announcements;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const announcements = await db.announcements.findByPk(id, options);
await announcements.update({
deletedBy: currentUser.id
}, {
transaction,
});
await announcements.destroy({
transaction
});
return announcements;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const announcements = await db.announcements.findOne(
{ where },
{ transaction },
);
if (!announcements) {
return announcements;
}
const output = announcements.get({plain: true});
output.school = await announcements.getSchool({
transaction
});
output.target_class = await announcements.getTarget_class({
transaction
});
output.author = await announcements.getAuthor({
transaction
});
output.attachments = await announcements.getAttachments({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.schools,
as: 'school',
},
{
model: db.classes,
as: 'target_class',
where: filter.target_class ? {
[Op.or]: [
{ id: { [Op.in]: filter.target_class.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.target_class.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.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'announcements',
'title',
filter.title,
),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'announcements',
'content',
filter.content,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
publish_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
expire_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.publish_atRange) {
const [start, end] = filter.publish_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
publish_at: {
...where.publish_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
publish_at: {
...where.publish_at,
[Op.lte]: end,
},
};
}
}
if (filter.expire_atRange) {
const [start, end] = filter.expire_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expire_at: {
...where.expire_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expire_at: {
...where.expire_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.audience) {
where = {
...where,
audience: filter.audience,
};
}
if (filter.pinned) {
where = {
...where,
pinned: filter.pinned,
};
}
if (filter.school) {
const listItems = filter.school.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.announcements.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'announcements',
'title',
query,
),
],
};
}
const records = await db.announcements.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,715 @@
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 Assignment_submissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assignment_submissions = await db.assignment_submissions.create(
{
id: data.id || undefined,
submitted_at: data.submitted_at
||
null
,
status: data.status
||
null
,
answer_text: data.answer_text
||
null
,
score: data.score
||
null
,
teacher_feedback: data.teacher_feedback
||
null
,
graded_at: data.graded_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await assignment_submissions.setAssignment( data.assignment || null, {
transaction,
});
await assignment_submissions.setStudent( data.student || null, {
transaction,
});
await assignment_submissions.setGraded_by( data.graded_by || null, {
transaction,
});
await assignment_submissions.setSchools( data.schools || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assignment_submissions.getTableName(),
belongsToColumn: 'answer_files',
belongsToId: assignment_submissions.id,
},
data.answer_files,
options,
);
return assignment_submissions;
}
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 assignment_submissionsData = data.map((item, index) => ({
id: item.id || undefined,
submitted_at: item.submitted_at
||
null
,
status: item.status
||
null
,
answer_text: item.answer_text
||
null
,
score: item.score
||
null
,
teacher_feedback: item.teacher_feedback
||
null
,
graded_at: item.graded_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const assignment_submissions = await db.assignment_submissions.bulkCreate(assignment_submissionsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < assignment_submissions.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assignment_submissions.getTableName(),
belongsToColumn: 'answer_files',
belongsToId: assignment_submissions[i].id,
},
data[i].answer_files,
options,
);
}
return assignment_submissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const assignment_submissions = await db.assignment_submissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.answer_text !== undefined) updatePayload.answer_text = data.answer_text;
if (data.score !== undefined) updatePayload.score = data.score;
if (data.teacher_feedback !== undefined) updatePayload.teacher_feedback = data.teacher_feedback;
if (data.graded_at !== undefined) updatePayload.graded_at = data.graded_at;
updatePayload.updatedById = currentUser.id;
await assignment_submissions.update(updatePayload, {transaction});
if (data.assignment !== undefined) {
await assignment_submissions.setAssignment(
data.assignment,
{ transaction }
);
}
if (data.student !== undefined) {
await assignment_submissions.setStudent(
data.student,
{ transaction }
);
}
if (data.graded_by !== undefined) {
await assignment_submissions.setGraded_by(
data.graded_by,
{ transaction }
);
}
if (data.schools !== undefined) {
await assignment_submissions.setSchools(
data.schools,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assignment_submissions.getTableName(),
belongsToColumn: 'answer_files',
belongsToId: assignment_submissions.id,
},
data.answer_files,
options,
);
return assignment_submissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assignment_submissions = await db.assignment_submissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of assignment_submissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of assignment_submissions) {
await record.destroy({transaction});
}
});
return assignment_submissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const assignment_submissions = await db.assignment_submissions.findByPk(id, options);
await assignment_submissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await assignment_submissions.destroy({
transaction
});
return assignment_submissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const assignment_submissions = await db.assignment_submissions.findOne(
{ where },
{ transaction },
);
if (!assignment_submissions) {
return assignment_submissions;
}
const output = assignment_submissions.get({plain: true});
output.assignment = await assignment_submissions.getAssignment({
transaction
});
output.student = await assignment_submissions.getStudent({
transaction
});
output.answer_files = await assignment_submissions.getAnswer_files({
transaction
});
output.graded_by = await assignment_submissions.getGraded_by({
transaction
});
output.schools = await assignment_submissions.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.assignments,
as: 'assignment',
where: filter.assignment ? {
[Op.or]: [
{ id: { [Op.in]: filter.assignment.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.assignment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.students,
as: 'student',
where: filter.student ? {
[Op.or]: [
{ id: { [Op.in]: filter.student.split('|').map(term => Utils.uuid(term)) } },
{
nis: {
[Op.or]: filter.student.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'graded_by',
where: filter.graded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.graded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.graded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
{
model: db.file,
as: 'answer_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.answer_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'assignment_submissions',
'answer_text',
filter.answer_text,
),
};
}
if (filter.teacher_feedback) {
where = {
...where,
[Op.and]: Utils.ilike(
'assignment_submissions',
'teacher_feedback',
filter.teacher_feedback,
),
};
}
if (filter.submitted_atRange) {
const [start, end] = filter.submitted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.lte]: end,
},
};
}
}
if (filter.scoreRange) {
const [start, end] = filter.scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score: {
...where.score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score: {
...where.score,
[Op.lte]: end,
},
};
}
}
if (filter.graded_atRange) {
const [start, end] = filter.graded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
graded_at: {
...where.graded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
graded_at: {
...where.graded_at,
[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.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.assignment_submissions.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'assignment_submissions',
'status',
query,
),
],
};
}
const records = await db.assignment_submissions.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,685 @@
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 AssignmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assignments = await db.assignments.create(
{
id: data.id || undefined,
title: data.title
||
null
,
description: data.description
||
null
,
assigned_at: data.assigned_at
||
null
,
due_at: data.due_at
||
null
,
submission_type: data.submission_type
||
null
,
published: data.published
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await assignments.setClass_subject( data.class_subject || null, {
transaction,
});
await assignments.setCreated_by( data.created_by || null, {
transaction,
});
await assignments.setSchools( data.schools || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assignments.getTableName(),
belongsToColumn: 'attachments',
belongsToId: assignments.id,
},
data.attachments,
options,
);
return assignments;
}
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 assignmentsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
description: item.description
||
null
,
assigned_at: item.assigned_at
||
null
,
due_at: item.due_at
||
null
,
submission_type: item.submission_type
||
null
,
published: item.published
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const assignments = await db.assignments.bulkCreate(assignmentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < assignments.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assignments.getTableName(),
belongsToColumn: 'attachments',
belongsToId: assignments[i].id,
},
data[i].attachments,
options,
);
}
return assignments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const assignments = await db.assignments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.submission_type !== undefined) updatePayload.submission_type = data.submission_type;
if (data.published !== undefined) updatePayload.published = data.published;
updatePayload.updatedById = currentUser.id;
await assignments.update(updatePayload, {transaction});
if (data.class_subject !== undefined) {
await assignments.setClass_subject(
data.class_subject,
{ transaction }
);
}
if (data.created_by !== undefined) {
await assignments.setCreated_by(
data.created_by,
{ transaction }
);
}
if (data.schools !== undefined) {
await assignments.setSchools(
data.schools,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assignments.getTableName(),
belongsToColumn: 'attachments',
belongsToId: assignments.id,
},
data.attachments,
options,
);
return assignments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assignments = await db.assignments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of assignments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of assignments) {
await record.destroy({transaction});
}
});
return assignments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const assignments = await db.assignments.findByPk(id, options);
await assignments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await assignments.destroy({
transaction
});
return assignments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const assignments = await db.assignments.findOne(
{ where },
{ transaction },
);
if (!assignments) {
return assignments;
}
const output = assignments.get({plain: true});
output.assignment_submissions_assignment = await assignments.getAssignment_submissions_assignment({
transaction
});
output.class_subject = await assignments.getClass_subject({
transaction
});
output.attachments = await assignments.getAttachments({
transaction
});
output.created_by = await assignments.getCreated_by({
transaction
});
output.schools = await assignments.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.class_subjects,
as: 'class_subject',
where: filter.class_subject ? {
[Op.or]: [
{ id: { [Op.in]: filter.class_subject.split('|').map(term => Utils.uuid(term)) } },
{
weekly_sessions: {
[Op.or]: filter.class_subject.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'created_by',
where: filter.created_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'assignments',
'title',
filter.title,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'assignments',
'description',
filter.description,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
assigned_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
due_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.assigned_atRange) {
const [start, end] = filter.assigned_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.lte]: end,
},
};
}
}
if (filter.due_atRange) {
const [start, end] = filter.due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.submission_type) {
where = {
...where,
submission_type: filter.submission_type,
};
}
if (filter.published) {
where = {
...where,
published: filter.published,
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.assignments.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'assignments',
'title',
query,
),
],
};
}
const records = await db.assignments.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,575 @@
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 Attendance_recordsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const attendance_records = await db.attendance_records.create(
{
id: data.id || undefined,
status: data.status
||
null
,
remarks: data.remarks
||
null
,
checked_at: data.checked_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await attendance_records.setAttendance_session( data.attendance_session || null, {
transaction,
});
await attendance_records.setStudent( data.student || null, {
transaction,
});
await attendance_records.setChecked_by( data.checked_by || null, {
transaction,
});
await attendance_records.setSchools( data.schools || null, {
transaction,
});
return attendance_records;
}
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 attendance_recordsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
remarks: item.remarks
||
null
,
checked_at: item.checked_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const attendance_records = await db.attendance_records.bulkCreate(attendance_recordsData, { transaction });
// For each item created, replace relation files
return attendance_records;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const attendance_records = await db.attendance_records.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.remarks !== undefined) updatePayload.remarks = data.remarks;
if (data.checked_at !== undefined) updatePayload.checked_at = data.checked_at;
updatePayload.updatedById = currentUser.id;
await attendance_records.update(updatePayload, {transaction});
if (data.attendance_session !== undefined) {
await attendance_records.setAttendance_session(
data.attendance_session,
{ transaction }
);
}
if (data.student !== undefined) {
await attendance_records.setStudent(
data.student,
{ transaction }
);
}
if (data.checked_by !== undefined) {
await attendance_records.setChecked_by(
data.checked_by,
{ transaction }
);
}
if (data.schools !== undefined) {
await attendance_records.setSchools(
data.schools,
{ transaction }
);
}
return attendance_records;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const attendance_records = await db.attendance_records.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of attendance_records) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of attendance_records) {
await record.destroy({transaction});
}
});
return attendance_records;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const attendance_records = await db.attendance_records.findByPk(id, options);
await attendance_records.update({
deletedBy: currentUser.id
}, {
transaction,
});
await attendance_records.destroy({
transaction
});
return attendance_records;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const attendance_records = await db.attendance_records.findOne(
{ where },
{ transaction },
);
if (!attendance_records) {
return attendance_records;
}
const output = attendance_records.get({plain: true});
output.attendance_session = await attendance_records.getAttendance_session({
transaction
});
output.student = await attendance_records.getStudent({
transaction
});
output.checked_by = await attendance_records.getChecked_by({
transaction
});
output.schools = await attendance_records.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.attendance_sessions,
as: 'attendance_session',
where: filter.attendance_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.attendance_session.split('|').map(term => Utils.uuid(term)) } },
{
notes: {
[Op.or]: filter.attendance_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.students,
as: 'student',
where: filter.student ? {
[Op.or]: [
{ id: { [Op.in]: filter.student.split('|').map(term => Utils.uuid(term)) } },
{
nis: {
[Op.or]: filter.student.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'checked_by',
where: filter.checked_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.checked_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.checked_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.remarks) {
where = {
...where,
[Op.and]: Utils.ilike(
'attendance_records',
'remarks',
filter.remarks,
),
};
}
if (filter.checked_atRange) {
const [start, end] = filter.checked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
checked_at: {
...where.checked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
checked_at: {
...where.checked_at,
[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.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.attendance_records.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'attendance_records',
'remarks',
query,
),
],
};
}
const records = await db.attendance_records.findAll({
attributes: [ 'id', 'remarks' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['remarks', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.remarks,
}));
}
};

View File

@ -0,0 +1,540 @@
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 Attendance_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const attendance_sessions = await db.attendance_sessions.create(
{
id: data.id || undefined,
attendance_date: data.attendance_date
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await attendance_sessions.setClass( data.class || null, {
transaction,
});
await attendance_sessions.setRecorded_by( data.recorded_by || null, {
transaction,
});
await attendance_sessions.setSchools( data.schools || null, {
transaction,
});
return attendance_sessions;
}
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 attendance_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
attendance_date: item.attendance_date
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const attendance_sessions = await db.attendance_sessions.bulkCreate(attendance_sessionsData, { transaction });
// For each item created, replace relation files
return attendance_sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const attendance_sessions = await db.attendance_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.attendance_date !== undefined) updatePayload.attendance_date = data.attendance_date;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await attendance_sessions.update(updatePayload, {transaction});
if (data.class !== undefined) {
await attendance_sessions.setClass(
data.class,
{ transaction }
);
}
if (data.recorded_by !== undefined) {
await attendance_sessions.setRecorded_by(
data.recorded_by,
{ transaction }
);
}
if (data.schools !== undefined) {
await attendance_sessions.setSchools(
data.schools,
{ transaction }
);
}
return attendance_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const attendance_sessions = await db.attendance_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of attendance_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of attendance_sessions) {
await record.destroy({transaction});
}
});
return attendance_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const attendance_sessions = await db.attendance_sessions.findByPk(id, options);
await attendance_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await attendance_sessions.destroy({
transaction
});
return attendance_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const attendance_sessions = await db.attendance_sessions.findOne(
{ where },
{ transaction },
);
if (!attendance_sessions) {
return attendance_sessions;
}
const output = attendance_sessions.get({plain: true});
output.attendance_records_attendance_session = await attendance_sessions.getAttendance_records_attendance_session({
transaction
});
output.class = await attendance_sessions.getClass({
transaction
});
output.recorded_by = await attendance_sessions.getRecorded_by({
transaction
});
output.schools = await attendance_sessions.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.classes,
as: 'class',
where: filter.class ? {
[Op.or]: [
{ id: { [Op.in]: filter.class.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.class.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'recorded_by',
where: filter.recorded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.recorded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recorded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'attendance_sessions',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
attendance_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
attendance_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.attendance_dateRange) {
const [start, end] = filter.attendance_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
attendance_date: {
...where.attendance_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
attendance_date: {
...where.attendance_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.attendance_sessions.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'attendance_sessions',
'notes',
query,
),
],
};
}
const records = await db.attendance_sessions.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};

View File

@ -0,0 +1,771 @@
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 Billing_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const billing_items = await db.billing_items.create(
{
id: data.id || undefined,
bill_number: data.bill_number
||
null
,
period_type: data.period_type
||
null
,
period_year: data.period_year
||
null
,
period_month: data.period_month
||
null
,
issued_at: data.issued_at
||
null
,
due_at: data.due_at
||
null
,
amount_total: data.amount_total
||
null
,
amount_paid: data.amount_paid
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await billing_items.setFee_definition( data.fee_definition || null, {
transaction,
});
await billing_items.setStudent( data.student || null, {
transaction,
});
await billing_items.setSchools( data.schools || null, {
transaction,
});
return billing_items;
}
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 billing_itemsData = data.map((item, index) => ({
id: item.id || undefined,
bill_number: item.bill_number
||
null
,
period_type: item.period_type
||
null
,
period_year: item.period_year
||
null
,
period_month: item.period_month
||
null
,
issued_at: item.issued_at
||
null
,
due_at: item.due_at
||
null
,
amount_total: item.amount_total
||
null
,
amount_paid: item.amount_paid
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const billing_items = await db.billing_items.bulkCreate(billing_itemsData, { transaction });
// For each item created, replace relation files
return billing_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const billing_items = await db.billing_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.bill_number !== undefined) updatePayload.bill_number = data.bill_number;
if (data.period_type !== undefined) updatePayload.period_type = data.period_type;
if (data.period_year !== undefined) updatePayload.period_year = data.period_year;
if (data.period_month !== undefined) updatePayload.period_month = data.period_month;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.amount_total !== undefined) updatePayload.amount_total = data.amount_total;
if (data.amount_paid !== undefined) updatePayload.amount_paid = data.amount_paid;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await billing_items.update(updatePayload, {transaction});
if (data.fee_definition !== undefined) {
await billing_items.setFee_definition(
data.fee_definition,
{ transaction }
);
}
if (data.student !== undefined) {
await billing_items.setStudent(
data.student,
{ transaction }
);
}
if (data.schools !== undefined) {
await billing_items.setSchools(
data.schools,
{ transaction }
);
}
return billing_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const billing_items = await db.billing_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of billing_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of billing_items) {
await record.destroy({transaction});
}
});
return billing_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const billing_items = await db.billing_items.findByPk(id, options);
await billing_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await billing_items.destroy({
transaction
});
return billing_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const billing_items = await db.billing_items.findOne(
{ where },
{ transaction },
);
if (!billing_items) {
return billing_items;
}
const output = billing_items.get({plain: true});
output.payments_billing_item = await billing_items.getPayments_billing_item({
transaction
});
output.fee_definition = await billing_items.getFee_definition({
transaction
});
output.student = await billing_items.getStudent({
transaction
});
output.schools = await billing_items.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.fee_definitions,
as: 'fee_definition',
where: filter.fee_definition ? {
[Op.or]: [
{ id: { [Op.in]: filter.fee_definition.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.fee_definition.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.students,
as: 'student',
where: filter.student ? {
[Op.or]: [
{ id: { [Op.in]: filter.student.split('|').map(term => Utils.uuid(term)) } },
{
nis: {
[Op.or]: filter.student.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.bill_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'billing_items',
'bill_number',
filter.bill_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'billing_items',
'notes',
filter.notes,
),
};
}
if (filter.period_yearRange) {
const [start, end] = filter.period_yearRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_year: {
...where.period_year,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_year: {
...where.period_year,
[Op.lte]: end,
},
};
}
}
if (filter.period_monthRange) {
const [start, end] = filter.period_monthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_month: {
...where.period_month,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_month: {
...where.period_month,
[Op.lte]: end,
},
};
}
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.lte]: end,
},
};
}
}
if (filter.due_atRange) {
const [start, end] = filter.due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.lte]: end,
},
};
}
}
if (filter.amount_totalRange) {
const [start, end] = filter.amount_totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount_total: {
...where.amount_total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount_total: {
...where.amount_total,
[Op.lte]: end,
},
};
}
}
if (filter.amount_paidRange) {
const [start, end] = filter.amount_paidRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount_paid: {
...where.amount_paid,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount_paid: {
...where.amount_paid,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.period_type) {
where = {
...where,
period_type: filter.period_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.billing_items.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'billing_items',
'bill_number',
query,
),
],
};
}
const records = await db.billing_items.findAll({
attributes: [ 'id', 'bill_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['bill_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.bill_number,
}));
}
};

View File

@ -0,0 +1,565 @@
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 Class_subjectsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const class_subjects = await db.class_subjects.create(
{
id: data.id || undefined,
weekly_sessions: data.weekly_sessions
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await class_subjects.setClass( data.class || null, {
transaction,
});
await class_subjects.setSubject( data.subject || null, {
transaction,
});
await class_subjects.setTeacher( data.teacher || null, {
transaction,
});
await class_subjects.setSchools( data.schools || null, {
transaction,
});
return class_subjects;
}
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 class_subjectsData = data.map((item, index) => ({
id: item.id || undefined,
weekly_sessions: item.weekly_sessions
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const class_subjects = await db.class_subjects.bulkCreate(class_subjectsData, { transaction });
// For each item created, replace relation files
return class_subjects;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const class_subjects = await db.class_subjects.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.weekly_sessions !== undefined) updatePayload.weekly_sessions = data.weekly_sessions;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await class_subjects.update(updatePayload, {transaction});
if (data.class !== undefined) {
await class_subjects.setClass(
data.class,
{ transaction }
);
}
if (data.subject !== undefined) {
await class_subjects.setSubject(
data.subject,
{ transaction }
);
}
if (data.teacher !== undefined) {
await class_subjects.setTeacher(
data.teacher,
{ transaction }
);
}
if (data.schools !== undefined) {
await class_subjects.setSchools(
data.schools,
{ transaction }
);
}
return class_subjects;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const class_subjects = await db.class_subjects.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of class_subjects) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of class_subjects) {
await record.destroy({transaction});
}
});
return class_subjects;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const class_subjects = await db.class_subjects.findByPk(id, options);
await class_subjects.update({
deletedBy: currentUser.id
}, {
transaction,
});
await class_subjects.destroy({
transaction
});
return class_subjects;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const class_subjects = await db.class_subjects.findOne(
{ where },
{ transaction },
);
if (!class_subjects) {
return class_subjects;
}
const output = class_subjects.get({plain: true});
output.timetable_entries_class_subject = await class_subjects.getTimetable_entries_class_subject({
transaction
});
output.assignments_class_subject = await class_subjects.getAssignments_class_subject({
transaction
});
output.exams_class_subject = await class_subjects.getExams_class_subject({
transaction
});
output.class = await class_subjects.getClass({
transaction
});
output.subject = await class_subjects.getSubject({
transaction
});
output.teacher = await class_subjects.getTeacher({
transaction
});
output.schools = await class_subjects.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.classes,
as: 'class',
where: filter.class ? {
[Op.or]: [
{ id: { [Op.in]: filter.class.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.class.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.subjects,
as: 'subject',
where: filter.subject ? {
[Op.or]: [
{ id: { [Op.in]: filter.subject.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.subject.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'teacher',
where: filter.teacher ? {
[Op.or]: [
{ id: { [Op.in]: filter.teacher.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.teacher.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.weekly_sessionsRange) {
const [start, end] = filter.weekly_sessionsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
weekly_sessions: {
...where.weekly_sessions,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
weekly_sessions: {
...where.weekly_sessions,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.class_subjects.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'class_subjects',
'weekly_sessions',
query,
),
],
};
}
const records = await db.class_subjects.findAll({
attributes: [ 'id', 'weekly_sessions' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['weekly_sessions', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.weekly_sessions,
}));
}
};

View File

@ -0,0 +1,625 @@
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 ClassesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const classes = await db.classes.create(
{
id: data.id || undefined,
name: data.name
||
null
,
grade: data.grade
||
null
,
homeroom_label: data.homeroom_label
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await classes.setSchool( data.school || null, {
transaction,
});
await classes.setAcademic_year( data.academic_year || null, {
transaction,
});
await classes.setEducation_level( data.education_level || null, {
transaction,
});
await classes.setHomeroom_teacher( data.homeroom_teacher || null, {
transaction,
});
return classes;
}
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 classesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
grade: item.grade
||
null
,
homeroom_label: item.homeroom_label
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const classes = await db.classes.bulkCreate(classesData, { transaction });
// For each item created, replace relation files
return classes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const classes = await db.classes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.grade !== undefined) updatePayload.grade = data.grade;
if (data.homeroom_label !== undefined) updatePayload.homeroom_label = data.homeroom_label;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await classes.update(updatePayload, {transaction});
if (data.school !== undefined) {
await classes.setSchool(
data.school,
{ transaction }
);
}
if (data.academic_year !== undefined) {
await classes.setAcademic_year(
data.academic_year,
{ transaction }
);
}
if (data.education_level !== undefined) {
await classes.setEducation_level(
data.education_level,
{ transaction }
);
}
if (data.homeroom_teacher !== undefined) {
await classes.setHomeroom_teacher(
data.homeroom_teacher,
{ transaction }
);
}
return classes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const classes = await db.classes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of classes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of classes) {
await record.destroy({transaction});
}
});
return classes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const classes = await db.classes.findByPk(id, options);
await classes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await classes.destroy({
transaction
});
return classes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const classes = await db.classes.findOne(
{ where },
{ transaction },
);
if (!classes) {
return classes;
}
const output = classes.get({plain: true});
output.students_current_class = await classes.getStudents_current_class({
transaction
});
output.class_subjects_class = await classes.getClass_subjects_class({
transaction
});
output.timetable_entries_class = await classes.getTimetable_entries_class({
transaction
});
output.attendance_sessions_class = await classes.getAttendance_sessions_class({
transaction
});
output.announcements_target_class = await classes.getAnnouncements_target_class({
transaction
});
output.fee_definitions_class = await classes.getFee_definitions_class({
transaction
});
output.school = await classes.getSchool({
transaction
});
output.academic_year = await classes.getAcademic_year({
transaction
});
output.education_level = await classes.getEducation_level({
transaction
});
output.homeroom_teacher = await classes.getHomeroom_teacher({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.schools,
as: 'school',
},
{
model: db.academic_years,
as: 'academic_year',
where: filter.academic_year ? {
[Op.or]: [
{ id: { [Op.in]: filter.academic_year.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.academic_year.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.education_levels,
as: 'education_level',
where: filter.education_level ? {
[Op.or]: [
{ id: { [Op.in]: filter.education_level.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.education_level.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'homeroom_teacher',
where: filter.homeroom_teacher ? {
[Op.or]: [
{ id: { [Op.in]: filter.homeroom_teacher.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.homeroom_teacher.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'classes',
'name',
filter.name,
),
};
}
if (filter.homeroom_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'classes',
'homeroom_label',
filter.homeroom_label,
),
};
}
if (filter.gradeRange) {
const [start, end] = filter.gradeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
grade: {
...where.grade,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
grade: {
...where.grade,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.school) {
const listItems = filter.school.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.classes.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'classes',
'name',
query,
),
],
};
}
const records = await db.classes.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,531 @@
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 Education_levelsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const education_levels = await db.education_levels.create(
{
id: data.id || undefined,
level: data.level
||
null
,
name: data.name
||
null
,
grade_start: data.grade_start
||
null
,
grade_end: data.grade_end
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await education_levels.setSchool( data.school || null, {
transaction,
});
return education_levels;
}
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 education_levelsData = data.map((item, index) => ({
id: item.id || undefined,
level: item.level
||
null
,
name: item.name
||
null
,
grade_start: item.grade_start
||
null
,
grade_end: item.grade_end
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const education_levels = await db.education_levels.bulkCreate(education_levelsData, { transaction });
// For each item created, replace relation files
return education_levels;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const education_levels = await db.education_levels.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.level !== undefined) updatePayload.level = data.level;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.grade_start !== undefined) updatePayload.grade_start = data.grade_start;
if (data.grade_end !== undefined) updatePayload.grade_end = data.grade_end;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await education_levels.update(updatePayload, {transaction});
if (data.school !== undefined) {
await education_levels.setSchool(
data.school,
{ transaction }
);
}
return education_levels;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const education_levels = await db.education_levels.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of education_levels) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of education_levels) {
await record.destroy({transaction});
}
});
return education_levels;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const education_levels = await db.education_levels.findByPk(id, options);
await education_levels.update({
deletedBy: currentUser.id
}, {
transaction,
});
await education_levels.destroy({
transaction
});
return education_levels;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const education_levels = await db.education_levels.findOne(
{ where },
{ transaction },
);
if (!education_levels) {
return education_levels;
}
const output = education_levels.get({plain: true});
output.classes_education_level = await education_levels.getClasses_education_level({
transaction
});
output.fee_definitions_education_level = await education_levels.getFee_definitions_education_level({
transaction
});
output.school = await education_levels.getSchool({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.schools,
as: 'school',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'education_levels',
'name',
filter.name,
),
};
}
if (filter.grade_startRange) {
const [start, end] = filter.grade_startRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
grade_start: {
...where.grade_start,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
grade_start: {
...where.grade_start,
[Op.lte]: end,
},
};
}
}
if (filter.grade_endRange) {
const [start, end] = filter.grade_endRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
grade_end: {
...where.grade_end,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
grade_end: {
...where.grade_end,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.level) {
where = {
...where,
level: filter.level,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.school) {
const listItems = filter.school.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.education_levels.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'education_levels',
'name',
query,
),
],
};
}
const records = await db.education_levels.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,629 @@
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 Exam_answersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exam_answers = await db.exam_answers.create(
{
id: data.id || undefined,
answer_text: data.answer_text
||
null
,
score: data.score
||
null
,
graded_at: data.graded_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await exam_answers.setExam_attempt( data.exam_attempt || null, {
transaction,
});
await exam_answers.setExam_question( data.exam_question || null, {
transaction,
});
await exam_answers.setSelected_choice( data.selected_choice || null, {
transaction,
});
await exam_answers.setGraded_by( data.graded_by || null, {
transaction,
});
await exam_answers.setSchools( data.schools || null, {
transaction,
});
return exam_answers;
}
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 exam_answersData = data.map((item, index) => ({
id: item.id || undefined,
answer_text: item.answer_text
||
null
,
score: item.score
||
null
,
graded_at: item.graded_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const exam_answers = await db.exam_answers.bulkCreate(exam_answersData, { transaction });
// For each item created, replace relation files
return exam_answers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const exam_answers = await db.exam_answers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.answer_text !== undefined) updatePayload.answer_text = data.answer_text;
if (data.score !== undefined) updatePayload.score = data.score;
if (data.graded_at !== undefined) updatePayload.graded_at = data.graded_at;
updatePayload.updatedById = currentUser.id;
await exam_answers.update(updatePayload, {transaction});
if (data.exam_attempt !== undefined) {
await exam_answers.setExam_attempt(
data.exam_attempt,
{ transaction }
);
}
if (data.exam_question !== undefined) {
await exam_answers.setExam_question(
data.exam_question,
{ transaction }
);
}
if (data.selected_choice !== undefined) {
await exam_answers.setSelected_choice(
data.selected_choice,
{ transaction }
);
}
if (data.graded_by !== undefined) {
await exam_answers.setGraded_by(
data.graded_by,
{ transaction }
);
}
if (data.schools !== undefined) {
await exam_answers.setSchools(
data.schools,
{ transaction }
);
}
return exam_answers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exam_answers = await db.exam_answers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of exam_answers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of exam_answers) {
await record.destroy({transaction});
}
});
return exam_answers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const exam_answers = await db.exam_answers.findByPk(id, options);
await exam_answers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await exam_answers.destroy({
transaction
});
return exam_answers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const exam_answers = await db.exam_answers.findOne(
{ where },
{ transaction },
);
if (!exam_answers) {
return exam_answers;
}
const output = exam_answers.get({plain: true});
output.exam_attempt = await exam_answers.getExam_attempt({
transaction
});
output.exam_question = await exam_answers.getExam_question({
transaction
});
output.selected_choice = await exam_answers.getSelected_choice({
transaction
});
output.graded_by = await exam_answers.getGraded_by({
transaction
});
output.schools = await exam_answers.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.exam_attempts,
as: 'exam_attempt',
where: filter.exam_attempt ? {
[Op.or]: [
{ id: { [Op.in]: filter.exam_attempt.split('|').map(term => Utils.uuid(term)) } },
{
status: {
[Op.or]: filter.exam_attempt.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.exam_questions,
as: 'exam_question',
where: filter.exam_question ? {
[Op.or]: [
{ id: { [Op.in]: filter.exam_question.split('|').map(term => Utils.uuid(term)) } },
{
question_text: {
[Op.or]: filter.exam_question.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.exam_question_choices,
as: 'selected_choice',
where: filter.selected_choice ? {
[Op.or]: [
{ id: { [Op.in]: filter.selected_choice.split('|').map(term => Utils.uuid(term)) } },
{
choice_label: {
[Op.or]: filter.selected_choice.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'graded_by',
where: filter.graded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.graded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.graded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.answer_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'exam_answers',
'answer_text',
filter.answer_text,
),
};
}
if (filter.scoreRange) {
const [start, end] = filter.scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score: {
...where.score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score: {
...where.score,
[Op.lte]: end,
},
};
}
}
if (filter.graded_atRange) {
const [start, end] = filter.graded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
graded_at: {
...where.graded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
graded_at: {
...where.graded_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.exam_answers.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'exam_answers',
'answer_text',
query,
),
],
};
}
const records = await db.exam_answers.findAll({
attributes: [ 'id', 'answer_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['answer_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.answer_text,
}));
}
};

View File

@ -0,0 +1,614 @@
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 Exam_attemptsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exam_attempts = await db.exam_attempts.create(
{
id: data.id || undefined,
started_at: data.started_at
||
null
,
submitted_at: data.submitted_at
||
null
,
status: data.status
||
null
,
score_total: data.score_total
||
null
,
passed: data.passed
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await exam_attempts.setExam( data.exam || null, {
transaction,
});
await exam_attempts.setStudent( data.student || null, {
transaction,
});
await exam_attempts.setSchools( data.schools || null, {
transaction,
});
return exam_attempts;
}
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 exam_attemptsData = data.map((item, index) => ({
id: item.id || undefined,
started_at: item.started_at
||
null
,
submitted_at: item.submitted_at
||
null
,
status: item.status
||
null
,
score_total: item.score_total
||
null
,
passed: item.passed
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const exam_attempts = await db.exam_attempts.bulkCreate(exam_attemptsData, { transaction });
// For each item created, replace relation files
return exam_attempts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const exam_attempts = await db.exam_attempts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.score_total !== undefined) updatePayload.score_total = data.score_total;
if (data.passed !== undefined) updatePayload.passed = data.passed;
updatePayload.updatedById = currentUser.id;
await exam_attempts.update(updatePayload, {transaction});
if (data.exam !== undefined) {
await exam_attempts.setExam(
data.exam,
{ transaction }
);
}
if (data.student !== undefined) {
await exam_attempts.setStudent(
data.student,
{ transaction }
);
}
if (data.schools !== undefined) {
await exam_attempts.setSchools(
data.schools,
{ transaction }
);
}
return exam_attempts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exam_attempts = await db.exam_attempts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of exam_attempts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of exam_attempts) {
await record.destroy({transaction});
}
});
return exam_attempts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const exam_attempts = await db.exam_attempts.findByPk(id, options);
await exam_attempts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await exam_attempts.destroy({
transaction
});
return exam_attempts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const exam_attempts = await db.exam_attempts.findOne(
{ where },
{ transaction },
);
if (!exam_attempts) {
return exam_attempts;
}
const output = exam_attempts.get({plain: true});
output.exam_answers_exam_attempt = await exam_attempts.getExam_answers_exam_attempt({
transaction
});
output.exam = await exam_attempts.getExam({
transaction
});
output.student = await exam_attempts.getStudent({
transaction
});
output.schools = await exam_attempts.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.exams,
as: 'exam',
where: filter.exam ? {
[Op.or]: [
{ id: { [Op.in]: filter.exam.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.exam.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.students,
as: 'student',
where: filter.student ? {
[Op.or]: [
{ id: { [Op.in]: filter.student.split('|').map(term => Utils.uuid(term)) } },
{
nis: {
[Op.or]: filter.student.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
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.submitted_atRange) {
const [start, end] = filter.submitted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.lte]: end,
},
};
}
}
if (filter.score_totalRange) {
const [start, end] = filter.score_totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score_total: {
...where.score_total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score_total: {
...where.score_total,
[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.passed) {
where = {
...where,
passed: filter.passed,
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.exam_attempts.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'exam_attempts',
'status',
query,
),
],
};
}
const records = await db.exam_attempts.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,453 @@
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 Exam_categoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exam_categories = await db.exam_categories.create(
{
id: data.id || undefined,
name: data.name
||
null
,
type: data.type
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await exam_categories.setSchool( data.school || null, {
transaction,
});
return exam_categories;
}
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 exam_categoriesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
type: item.type
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const exam_categories = await db.exam_categories.bulkCreate(exam_categoriesData, { transaction });
// For each item created, replace relation files
return exam_categories;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const exam_categories = await db.exam_categories.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.type !== undefined) updatePayload.type = data.type;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await exam_categories.update(updatePayload, {transaction});
if (data.school !== undefined) {
await exam_categories.setSchool(
data.school,
{ transaction }
);
}
return exam_categories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exam_categories = await db.exam_categories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of exam_categories) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of exam_categories) {
await record.destroy({transaction});
}
});
return exam_categories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const exam_categories = await db.exam_categories.findByPk(id, options);
await exam_categories.update({
deletedBy: currentUser.id
}, {
transaction,
});
await exam_categories.destroy({
transaction
});
return exam_categories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const exam_categories = await db.exam_categories.findOne(
{ where },
{ transaction },
);
if (!exam_categories) {
return exam_categories;
}
const output = exam_categories.get({plain: true});
output.exams_category = await exam_categories.getExams_category({
transaction
});
output.school = await exam_categories.getSchool({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.schools,
as: 'school',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'exam_categories',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.type) {
where = {
...where,
type: filter.type,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.school) {
const listItems = filter.school.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.exam_categories.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'exam_categories',
'name',
query,
),
],
};
}
const records = await db.exam_categories.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,531 @@
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 Exam_question_choicesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exam_question_choices = await db.exam_question_choices.create(
{
id: data.id || undefined,
choice_label: data.choice_label
||
null
,
choice_text: data.choice_text
||
null
,
is_correct: data.is_correct
||
false
,
order_number: data.order_number
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await exam_question_choices.setExam_question( data.exam_question || null, {
transaction,
});
await exam_question_choices.setSchools( data.schools || null, {
transaction,
});
return exam_question_choices;
}
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 exam_question_choicesData = data.map((item, index) => ({
id: item.id || undefined,
choice_label: item.choice_label
||
null
,
choice_text: item.choice_text
||
null
,
is_correct: item.is_correct
||
false
,
order_number: item.order_number
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const exam_question_choices = await db.exam_question_choices.bulkCreate(exam_question_choicesData, { transaction });
// For each item created, replace relation files
return exam_question_choices;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const exam_question_choices = await db.exam_question_choices.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.choice_label !== undefined) updatePayload.choice_label = data.choice_label;
if (data.choice_text !== undefined) updatePayload.choice_text = data.choice_text;
if (data.is_correct !== undefined) updatePayload.is_correct = data.is_correct;
if (data.order_number !== undefined) updatePayload.order_number = data.order_number;
updatePayload.updatedById = currentUser.id;
await exam_question_choices.update(updatePayload, {transaction});
if (data.exam_question !== undefined) {
await exam_question_choices.setExam_question(
data.exam_question,
{ transaction }
);
}
if (data.schools !== undefined) {
await exam_question_choices.setSchools(
data.schools,
{ transaction }
);
}
return exam_question_choices;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exam_question_choices = await db.exam_question_choices.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of exam_question_choices) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of exam_question_choices) {
await record.destroy({transaction});
}
});
return exam_question_choices;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const exam_question_choices = await db.exam_question_choices.findByPk(id, options);
await exam_question_choices.update({
deletedBy: currentUser.id
}, {
transaction,
});
await exam_question_choices.destroy({
transaction
});
return exam_question_choices;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const exam_question_choices = await db.exam_question_choices.findOne(
{ where },
{ transaction },
);
if (!exam_question_choices) {
return exam_question_choices;
}
const output = exam_question_choices.get({plain: true});
output.exam_answers_selected_choice = await exam_question_choices.getExam_answers_selected_choice({
transaction
});
output.exam_question = await exam_question_choices.getExam_question({
transaction
});
output.schools = await exam_question_choices.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.exam_questions,
as: 'exam_question',
where: filter.exam_question ? {
[Op.or]: [
{ id: { [Op.in]: filter.exam_question.split('|').map(term => Utils.uuid(term)) } },
{
question_text: {
[Op.or]: filter.exam_question.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.choice_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'exam_question_choices',
'choice_label',
filter.choice_label,
),
};
}
if (filter.choice_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'exam_question_choices',
'choice_text',
filter.choice_text,
),
};
}
if (filter.order_numberRange) {
const [start, end] = filter.order_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
order_number: {
...where.order_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
order_number: {
...where.order_number,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_correct) {
where = {
...where,
is_correct: filter.is_correct,
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.exam_question_choices.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'exam_question_choices',
'choice_label',
query,
),
],
};
}
const records = await db.exam_question_choices.findAll({
attributes: [ 'id', 'choice_label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['choice_label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.choice_label,
}));
}
};

View File

@ -0,0 +1,610 @@
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 Exam_questionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exam_questions = await db.exam_questions.create(
{
id: data.id || undefined,
question_type: data.question_type
||
null
,
question_text: data.question_text
||
null
,
points: data.points
||
null
,
order_number: data.order_number
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await exam_questions.setExam( data.exam || null, {
transaction,
});
await exam_questions.setSchools( data.schools || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.exam_questions.getTableName(),
belongsToColumn: 'question_media',
belongsToId: exam_questions.id,
},
data.question_media,
options,
);
return exam_questions;
}
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 exam_questionsData = data.map((item, index) => ({
id: item.id || undefined,
question_type: item.question_type
||
null
,
question_text: item.question_text
||
null
,
points: item.points
||
null
,
order_number: item.order_number
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const exam_questions = await db.exam_questions.bulkCreate(exam_questionsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < exam_questions.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.exam_questions.getTableName(),
belongsToColumn: 'question_media',
belongsToId: exam_questions[i].id,
},
data[i].question_media,
options,
);
}
return exam_questions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const exam_questions = await db.exam_questions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.question_type !== undefined) updatePayload.question_type = data.question_type;
if (data.question_text !== undefined) updatePayload.question_text = data.question_text;
if (data.points !== undefined) updatePayload.points = data.points;
if (data.order_number !== undefined) updatePayload.order_number = data.order_number;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await exam_questions.update(updatePayload, {transaction});
if (data.exam !== undefined) {
await exam_questions.setExam(
data.exam,
{ transaction }
);
}
if (data.schools !== undefined) {
await exam_questions.setSchools(
data.schools,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.exam_questions.getTableName(),
belongsToColumn: 'question_media',
belongsToId: exam_questions.id,
},
data.question_media,
options,
);
return exam_questions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exam_questions = await db.exam_questions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of exam_questions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of exam_questions) {
await record.destroy({transaction});
}
});
return exam_questions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const exam_questions = await db.exam_questions.findByPk(id, options);
await exam_questions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await exam_questions.destroy({
transaction
});
return exam_questions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const exam_questions = await db.exam_questions.findOne(
{ where },
{ transaction },
);
if (!exam_questions) {
return exam_questions;
}
const output = exam_questions.get({plain: true});
output.exam_question_choices_exam_question = await exam_questions.getExam_question_choices_exam_question({
transaction
});
output.exam_answers_exam_question = await exam_questions.getExam_answers_exam_question({
transaction
});
output.exam = await exam_questions.getExam({
transaction
});
output.question_media = await exam_questions.getQuestion_media({
transaction
});
output.schools = await exam_questions.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.exams,
as: 'exam',
where: filter.exam ? {
[Op.or]: [
{ id: { [Op.in]: filter.exam.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.exam.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
{
model: db.file,
as: 'question_media',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.question_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'exam_questions',
'question_text',
filter.question_text,
),
};
}
if (filter.pointsRange) {
const [start, end] = filter.pointsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
points: {
...where.points,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
points: {
...where.points,
[Op.lte]: end,
},
};
}
}
if (filter.order_numberRange) {
const [start, end] = filter.order_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
order_number: {
...where.order_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
order_number: {
...where.order_number,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.question_type) {
where = {
...where,
question_type: filter.question_type,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.exam_questions.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'exam_questions',
'question_text',
query,
),
],
};
}
const records = await db.exam_questions.findAll({
attributes: [ 'id', 'question_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['question_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.question_text,
}));
}
};

756
backend/src/db/api/exams.js Normal file
View File

@ -0,0 +1,756 @@
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 ExamsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exams = await db.exams.create(
{
id: data.id || undefined,
title: data.title
||
null
,
mode: data.mode
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
duration_minutes: data.duration_minutes
||
null
,
randomize_questions: data.randomize_questions
||
false
,
passing_score: data.passing_score
||
null
,
published: data.published
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await exams.setClass_subject( data.class_subject || null, {
transaction,
});
await exams.setCategory( data.category || null, {
transaction,
});
await exams.setCreated_by( data.created_by || null, {
transaction,
});
await exams.setSchools( data.schools || null, {
transaction,
});
return exams;
}
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 examsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
mode: item.mode
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
duration_minutes: item.duration_minutes
||
null
,
randomize_questions: item.randomize_questions
||
false
,
passing_score: item.passing_score
||
null
,
published: item.published
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const exams = await db.exams.bulkCreate(examsData, { transaction });
// For each item created, replace relation files
return exams;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const exams = await db.exams.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.mode !== undefined) updatePayload.mode = data.mode;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.duration_minutes !== undefined) updatePayload.duration_minutes = data.duration_minutes;
if (data.randomize_questions !== undefined) updatePayload.randomize_questions = data.randomize_questions;
if (data.passing_score !== undefined) updatePayload.passing_score = data.passing_score;
if (data.published !== undefined) updatePayload.published = data.published;
updatePayload.updatedById = currentUser.id;
await exams.update(updatePayload, {transaction});
if (data.class_subject !== undefined) {
await exams.setClass_subject(
data.class_subject,
{ transaction }
);
}
if (data.category !== undefined) {
await exams.setCategory(
data.category,
{ transaction }
);
}
if (data.created_by !== undefined) {
await exams.setCreated_by(
data.created_by,
{ transaction }
);
}
if (data.schools !== undefined) {
await exams.setSchools(
data.schools,
{ transaction }
);
}
return exams;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exams = await db.exams.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of exams) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of exams) {
await record.destroy({transaction});
}
});
return exams;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const exams = await db.exams.findByPk(id, options);
await exams.update({
deletedBy: currentUser.id
}, {
transaction,
});
await exams.destroy({
transaction
});
return exams;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const exams = await db.exams.findOne(
{ where },
{ transaction },
);
if (!exams) {
return exams;
}
const output = exams.get({plain: true});
output.exam_questions_exam = await exams.getExam_questions_exam({
transaction
});
output.exam_attempts_exam = await exams.getExam_attempts_exam({
transaction
});
output.class_subject = await exams.getClass_subject({
transaction
});
output.category = await exams.getCategory({
transaction
});
output.created_by = await exams.getCreated_by({
transaction
});
output.schools = await exams.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.class_subjects,
as: 'class_subject',
where: filter.class_subject ? {
[Op.or]: [
{ id: { [Op.in]: filter.class_subject.split('|').map(term => Utils.uuid(term)) } },
{
weekly_sessions: {
[Op.or]: filter.class_subject.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.exam_categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'created_by',
where: filter.created_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'exams',
'title',
filter.title,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_atRange) {
const [start, end] = filter.start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.lte]: end,
},
};
}
}
if (filter.end_atRange) {
const [start, end] = filter.end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.lte]: end,
},
};
}
}
if (filter.duration_minutesRange) {
const [start, end] = filter.duration_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_minutes: {
...where.duration_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_minutes: {
...where.duration_minutes,
[Op.lte]: end,
},
};
}
}
if (filter.passing_scoreRange) {
const [start, end] = filter.passing_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
passing_score: {
...where.passing_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
passing_score: {
...where.passing_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.mode) {
where = {
...where,
mode: filter.mode,
};
}
if (filter.randomize_questions) {
where = {
...where,
randomize_questions: filter.randomize_questions,
};
}
if (filter.published) {
where = {
...where,
published: filter.published,
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.exams.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'exams',
'title',
query,
),
],
};
}
const records = await db.exams.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,734 @@
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 Fee_definitionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const fee_definitions = await db.fee_definitions.create(
{
id: data.id || undefined,
fee_type: data.fee_type
||
null
,
name: data.name
||
null
,
amount: data.amount
||
null
,
allow_installments: data.allow_installments
||
false
,
minimum_down_payment: data.minimum_down_payment
||
null
,
max_installments: data.max_installments
||
null
,
installment_deadline: data.installment_deadline
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await fee_definitions.setSchool( data.school || null, {
transaction,
});
await fee_definitions.setAcademic_year( data.academic_year || null, {
transaction,
});
await fee_definitions.setEducation_level( data.education_level || null, {
transaction,
});
await fee_definitions.setClass( data.class || null, {
transaction,
});
return fee_definitions;
}
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 fee_definitionsData = data.map((item, index) => ({
id: item.id || undefined,
fee_type: item.fee_type
||
null
,
name: item.name
||
null
,
amount: item.amount
||
null
,
allow_installments: item.allow_installments
||
false
,
minimum_down_payment: item.minimum_down_payment
||
null
,
max_installments: item.max_installments
||
null
,
installment_deadline: item.installment_deadline
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const fee_definitions = await db.fee_definitions.bulkCreate(fee_definitionsData, { transaction });
// For each item created, replace relation files
return fee_definitions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const fee_definitions = await db.fee_definitions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.fee_type !== undefined) updatePayload.fee_type = data.fee_type;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.allow_installments !== undefined) updatePayload.allow_installments = data.allow_installments;
if (data.minimum_down_payment !== undefined) updatePayload.minimum_down_payment = data.minimum_down_payment;
if (data.max_installments !== undefined) updatePayload.max_installments = data.max_installments;
if (data.installment_deadline !== undefined) updatePayload.installment_deadline = data.installment_deadline;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await fee_definitions.update(updatePayload, {transaction});
if (data.school !== undefined) {
await fee_definitions.setSchool(
data.school,
{ transaction }
);
}
if (data.academic_year !== undefined) {
await fee_definitions.setAcademic_year(
data.academic_year,
{ transaction }
);
}
if (data.education_level !== undefined) {
await fee_definitions.setEducation_level(
data.education_level,
{ transaction }
);
}
if (data.class !== undefined) {
await fee_definitions.setClass(
data.class,
{ transaction }
);
}
return fee_definitions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const fee_definitions = await db.fee_definitions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of fee_definitions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of fee_definitions) {
await record.destroy({transaction});
}
});
return fee_definitions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const fee_definitions = await db.fee_definitions.findByPk(id, options);
await fee_definitions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await fee_definitions.destroy({
transaction
});
return fee_definitions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const fee_definitions = await db.fee_definitions.findOne(
{ where },
{ transaction },
);
if (!fee_definitions) {
return fee_definitions;
}
const output = fee_definitions.get({plain: true});
output.billing_items_fee_definition = await fee_definitions.getBilling_items_fee_definition({
transaction
});
output.school = await fee_definitions.getSchool({
transaction
});
output.academic_year = await fee_definitions.getAcademic_year({
transaction
});
output.education_level = await fee_definitions.getEducation_level({
transaction
});
output.class = await fee_definitions.getClass({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.schools,
as: 'school',
},
{
model: db.academic_years,
as: 'academic_year',
where: filter.academic_year ? {
[Op.or]: [
{ id: { [Op.in]: filter.academic_year.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.academic_year.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.education_levels,
as: 'education_level',
where: filter.education_level ? {
[Op.or]: [
{ id: { [Op.in]: filter.education_level.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.education_level.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.classes,
as: 'class',
where: filter.class ? {
[Op.or]: [
{ id: { [Op.in]: filter.class.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.class.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'fee_definitions',
'name',
filter.name,
),
};
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.minimum_down_paymentRange) {
const [start, end] = filter.minimum_down_paymentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
minimum_down_payment: {
...where.minimum_down_payment,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
minimum_down_payment: {
...where.minimum_down_payment,
[Op.lte]: end,
},
};
}
}
if (filter.max_installmentsRange) {
const [start, end] = filter.max_installmentsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_installments: {
...where.max_installments,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_installments: {
...where.max_installments,
[Op.lte]: end,
},
};
}
}
if (filter.installment_deadlineRange) {
const [start, end] = filter.installment_deadlineRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
installment_deadline: {
...where.installment_deadline,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
installment_deadline: {
...where.installment_deadline,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.fee_type) {
where = {
...where,
fee_type: filter.fee_type,
};
}
if (filter.allow_installments) {
where = {
...where,
allow_installments: filter.allow_installments,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.school) {
const listItems = filter.school.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.fee_definitions.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'fee_definitions',
'name',
query,
),
],
};
}
const records = await db.fee_definitions.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,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,
});
}
}
};

View File

@ -0,0 +1,565 @@
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 Notification_logsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notification_logs = await db.notification_logs.create(
{
id: data.id || undefined,
channel: data.channel
||
null
,
category: data.category
||
null
,
title: data.title
||
null
,
message: data.message
||
null
,
sent_at: data.sent_at
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notification_logs.setSchool( data.school || null, {
transaction,
});
await notification_logs.setRecipient_user( data.recipient_user || null, {
transaction,
});
return notification_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 notification_logsData = data.map((item, index) => ({
id: item.id || undefined,
channel: item.channel
||
null
,
category: item.category
||
null
,
title: item.title
||
null
,
message: item.message
||
null
,
sent_at: item.sent_at
||
null
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const notification_logs = await db.notification_logs.bulkCreate(notification_logsData, { transaction });
// For each item created, replace relation files
return notification_logs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const notification_logs = await db.notification_logs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.message !== undefined) updatePayload.message = data.message;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await notification_logs.update(updatePayload, {transaction});
if (data.school !== undefined) {
await notification_logs.setSchool(
data.school,
{ transaction }
);
}
if (data.recipient_user !== undefined) {
await notification_logs.setRecipient_user(
data.recipient_user,
{ transaction }
);
}
return notification_logs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notification_logs = await db.notification_logs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notification_logs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notification_logs) {
await record.destroy({transaction});
}
});
return notification_logs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notification_logs = await db.notification_logs.findByPk(id, options);
await notification_logs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notification_logs.destroy({
transaction
});
return notification_logs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notification_logs = await db.notification_logs.findOne(
{ where },
{ transaction },
);
if (!notification_logs) {
return notification_logs;
}
const output = notification_logs.get({plain: true});
output.school = await notification_logs.getSchool({
transaction
});
output.recipient_user = await notification_logs.getRecipient_user({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.schools,
as: 'school',
},
{
model: db.users,
as: 'recipient_user',
where: filter.recipient_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.recipient_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recipient_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'notification_logs',
'title',
filter.title,
),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'notification_logs',
'message',
filter.message,
),
};
}
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.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.school) {
const listItems = filter.school.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.notification_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'notification_logs',
'title',
query,
),
],
};
}
const records = await db.notification_logs.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,499 @@
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 Parent_student_linksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const parent_student_links = await db.parent_student_links.create(
{
id: data.id || undefined,
relationship: data.relationship
||
null
,
is_primary: data.is_primary
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await parent_student_links.setParent_user( data.parent_user || null, {
transaction,
});
await parent_student_links.setStudent( data.student || null, {
transaction,
});
await parent_student_links.setSchools( data.schools || null, {
transaction,
});
return parent_student_links;
}
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 parent_student_linksData = data.map((item, index) => ({
id: item.id || undefined,
relationship: item.relationship
||
null
,
is_primary: item.is_primary
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const parent_student_links = await db.parent_student_links.bulkCreate(parent_student_linksData, { transaction });
// For each item created, replace relation files
return parent_student_links;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const parent_student_links = await db.parent_student_links.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.relationship !== undefined) updatePayload.relationship = data.relationship;
if (data.is_primary !== undefined) updatePayload.is_primary = data.is_primary;
updatePayload.updatedById = currentUser.id;
await parent_student_links.update(updatePayload, {transaction});
if (data.parent_user !== undefined) {
await parent_student_links.setParent_user(
data.parent_user,
{ transaction }
);
}
if (data.student !== undefined) {
await parent_student_links.setStudent(
data.student,
{ transaction }
);
}
if (data.schools !== undefined) {
await parent_student_links.setSchools(
data.schools,
{ transaction }
);
}
return parent_student_links;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const parent_student_links = await db.parent_student_links.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of parent_student_links) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of parent_student_links) {
await record.destroy({transaction});
}
});
return parent_student_links;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const parent_student_links = await db.parent_student_links.findByPk(id, options);
await parent_student_links.update({
deletedBy: currentUser.id
}, {
transaction,
});
await parent_student_links.destroy({
transaction
});
return parent_student_links;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const parent_student_links = await db.parent_student_links.findOne(
{ where },
{ transaction },
);
if (!parent_student_links) {
return parent_student_links;
}
const output = parent_student_links.get({plain: true});
output.parent_user = await parent_student_links.getParent_user({
transaction
});
output.student = await parent_student_links.getStudent({
transaction
});
output.schools = await parent_student_links.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'parent_user',
where: filter.parent_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.parent_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.parent_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.students,
as: 'student',
where: filter.student ? {
[Op.or]: [
{ id: { [Op.in]: filter.student.split('|').map(term => Utils.uuid(term)) } },
{
nis: {
[Op.or]: filter.student.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.relationship) {
where = {
...where,
relationship: filter.relationship,
};
}
if (filter.is_primary) {
where = {
...where,
is_primary: filter.is_primary,
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.parent_student_links.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'parent_student_links',
'relationship',
query,
),
],
};
}
const records = await db.parent_student_links.findAll({
attributes: [ 'id', 'relationship' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['relationship', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.relationship,
}));
}
};

View File

@ -0,0 +1,661 @@
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 PaymentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.create(
{
id: data.id || undefined,
paid_at: data.paid_at
||
null
,
amount: data.amount
||
null
,
method: data.method
||
null
,
reference_number: data.reference_number
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payments.setBilling_item( data.billing_item || null, {
transaction,
});
await payments.setPaid_by_user( data.paid_by_user || null, {
transaction,
});
await payments.setSchools( data.schools || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'proof',
belongsToId: payments.id,
},
data.proof,
options,
);
return payments;
}
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 paymentsData = data.map((item, index) => ({
id: item.id || undefined,
paid_at: item.paid_at
||
null
,
amount: item.amount
||
null
,
method: item.method
||
null
,
reference_number: item.reference_number
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payments = await db.payments.bulkCreate(paymentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < payments.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'proof',
belongsToId: payments[i].id,
},
data[i].proof,
options,
);
}
return payments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const payments = await db.payments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.method !== undefined) updatePayload.method = data.method;
if (data.reference_number !== undefined) updatePayload.reference_number = data.reference_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await payments.update(updatePayload, {transaction});
if (data.billing_item !== undefined) {
await payments.setBilling_item(
data.billing_item,
{ transaction }
);
}
if (data.paid_by_user !== undefined) {
await payments.setPaid_by_user(
data.paid_by_user,
{ transaction }
);
}
if (data.schools !== undefined) {
await payments.setSchools(
data.schools,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'proof',
belongsToId: payments.id,
},
data.proof,
options,
);
return payments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payments) {
await record.destroy({transaction});
}
});
return payments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findByPk(id, options);
await payments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payments.destroy({
transaction
});
return payments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findOne(
{ where },
{ transaction },
);
if (!payments) {
return payments;
}
const output = payments.get({plain: true});
output.billing_item = await payments.getBilling_item({
transaction
});
output.paid_by_user = await payments.getPaid_by_user({
transaction
});
output.proof = await payments.getProof({
transaction
});
output.schools = await payments.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.billing_items,
as: 'billing_item',
where: filter.billing_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.billing_item.split('|').map(term => Utils.uuid(term)) } },
{
bill_number: {
[Op.or]: filter.billing_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'paid_by_user',
where: filter.paid_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.paid_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.paid_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
{
model: db.file,
as: 'proof',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reference_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'reference_number',
filter.reference_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'notes',
filter.notes,
),
};
}
if (filter.paid_atRange) {
const [start, end] = filter.paid_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.lte]: end,
},
};
}
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.method) {
where = {
...where,
method: filter.method,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.payments.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'payments',
'reference_number',
query,
),
],
};
}
const records = await db.payments.findAll({
attributes: [ 'id', 'reference_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reference_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reference_number,
}));
}
};

View File

@ -0,0 +1,356 @@
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 globalAccess = currentUser.app_role?.globalAccess;
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;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
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,
}));
}
};

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

@ -0,0 +1,458 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const config = require('../../config');
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
,
globalAccess: data.globalAccess
||
false
,
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
,
globalAccess: item.globalAccess
||
false
,
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 globalAccess = currentUser.app_role?.globalAccess;
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;
if (data.globalAccess !== undefined) updatePayload.globalAccess = data.globalAccess;
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,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
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.globalAccess) {
where = {
...where,
globalAccess: filter.globalAccess,
};
}
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,
},
};
}
}
}
if (!globalAccess) {
where = { name: { [Op.ne]: config.roles.super_admin } };
}
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, globalAccess,) {
let where = {};
if (!globalAccess) {
where = { name: { [Op.ne]: config.roles.super_admin } };
}
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,
}));
}
};

View File

@ -0,0 +1,466 @@
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 SchoolsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const schools = await db.schools.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return schools;
}
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 schoolsData = 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 schools = await db.schools.bulkCreate(schoolsData, { transaction });
// For each item created, replace relation files
return schools;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const schools = await db.schools.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await schools.update(updatePayload, {transaction});
return schools;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const schools = await db.schools.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of schools) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of schools) {
await record.destroy({transaction});
}
});
return schools;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const schools = await db.schools.findByPk(id, options);
await schools.update({
deletedBy: currentUser.id
}, {
transaction,
});
await schools.destroy({
transaction
});
return schools;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const schools = await db.schools.findOne(
{ where },
{ transaction },
);
if (!schools) {
return schools;
}
const output = schools.get({plain: true});
output.users_schools = await schools.getUsers_schools({
transaction
});
output.academic_years_school = await schools.getAcademic_years_school({
transaction
});
output.education_levels_school = await schools.getEducation_levels_school({
transaction
});
output.classes_school = await schools.getClasses_school({
transaction
});
output.students_school = await schools.getStudents_school({
transaction
});
output.parent_student_links_schools = await schools.getParent_student_links_schools({
transaction
});
output.subjects_school = await schools.getSubjects_school({
transaction
});
output.class_subjects_schools = await schools.getClass_subjects_schools({
transaction
});
output.timetable_entries_schools = await schools.getTimetable_entries_schools({
transaction
});
output.attendance_sessions_schools = await schools.getAttendance_sessions_schools({
transaction
});
output.attendance_records_schools = await schools.getAttendance_records_schools({
transaction
});
output.announcements_school = await schools.getAnnouncements_school({
transaction
});
output.assignments_schools = await schools.getAssignments_schools({
transaction
});
output.assignment_submissions_schools = await schools.getAssignment_submissions_schools({
transaction
});
output.exam_categories_school = await schools.getExam_categories_school({
transaction
});
output.exams_schools = await schools.getExams_schools({
transaction
});
output.exam_questions_schools = await schools.getExam_questions_schools({
transaction
});
output.exam_question_choices_schools = await schools.getExam_question_choices_schools({
transaction
});
output.exam_attempts_schools = await schools.getExam_attempts_schools({
transaction
});
output.exam_answers_schools = await schools.getExam_answers_schools({
transaction
});
output.fee_definitions_school = await schools.getFee_definitions_school({
transaction
});
output.billing_items_schools = await schools.getBilling_items_schools({
transaction
});
output.payments_schools = await schools.getPayments_schools({
transaction
});
output.notification_logs_school = await schools.getNotification_logs_school({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
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(
'schools',
'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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.schools.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'schools',
'name',
query,
),
],
};
}
const records = await db.schools.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,687 @@
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 StudentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const students = await db.students.create(
{
id: data.id || undefined,
nis: data.nis
||
null
,
nisn: data.nisn
||
null
,
birth_place: data.birth_place
||
null
,
birth_date: data.birth_date
||
null
,
gender: data.gender
||
null
,
address: data.address
||
null
,
enrollment_date: data.enrollment_date
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await students.setSchool( data.school || null, {
transaction,
});
await students.setUser( data.user || null, {
transaction,
});
await students.setCurrent_class( data.current_class || null, {
transaction,
});
return students;
}
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 studentsData = data.map((item, index) => ({
id: item.id || undefined,
nis: item.nis
||
null
,
nisn: item.nisn
||
null
,
birth_place: item.birth_place
||
null
,
birth_date: item.birth_date
||
null
,
gender: item.gender
||
null
,
address: item.address
||
null
,
enrollment_date: item.enrollment_date
||
null
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const students = await db.students.bulkCreate(studentsData, { transaction });
// For each item created, replace relation files
return students;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const students = await db.students.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.nis !== undefined) updatePayload.nis = data.nis;
if (data.nisn !== undefined) updatePayload.nisn = data.nisn;
if (data.birth_place !== undefined) updatePayload.birth_place = data.birth_place;
if (data.birth_date !== undefined) updatePayload.birth_date = data.birth_date;
if (data.gender !== undefined) updatePayload.gender = data.gender;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.enrollment_date !== undefined) updatePayload.enrollment_date = data.enrollment_date;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await students.update(updatePayload, {transaction});
if (data.school !== undefined) {
await students.setSchool(
data.school,
{ transaction }
);
}
if (data.user !== undefined) {
await students.setUser(
data.user,
{ transaction }
);
}
if (data.current_class !== undefined) {
await students.setCurrent_class(
data.current_class,
{ transaction }
);
}
return students;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const students = await db.students.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of students) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of students) {
await record.destroy({transaction});
}
});
return students;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const students = await db.students.findByPk(id, options);
await students.update({
deletedBy: currentUser.id
}, {
transaction,
});
await students.destroy({
transaction
});
return students;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const students = await db.students.findOne(
{ where },
{ transaction },
);
if (!students) {
return students;
}
const output = students.get({plain: true});
output.parent_student_links_student = await students.getParent_student_links_student({
transaction
});
output.attendance_records_student = await students.getAttendance_records_student({
transaction
});
output.assignment_submissions_student = await students.getAssignment_submissions_student({
transaction
});
output.exam_attempts_student = await students.getExam_attempts_student({
transaction
});
output.billing_items_student = await students.getBilling_items_student({
transaction
});
output.school = await students.getSchool({
transaction
});
output.user = await students.getUser({
transaction
});
output.current_class = await students.getCurrent_class({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.schools,
as: 'school',
},
{
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.classes,
as: 'current_class',
where: filter.current_class ? {
[Op.or]: [
{ id: { [Op.in]: filter.current_class.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.current_class.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.nis) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'nis',
filter.nis,
),
};
}
if (filter.nisn) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'nisn',
filter.nisn,
),
};
}
if (filter.birth_place) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'birth_place',
filter.birth_place,
),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'students',
'address',
filter.address,
),
};
}
if (filter.birth_dateRange) {
const [start, end] = filter.birth_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
birth_date: {
...where.birth_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
birth_date: {
...where.birth_date,
[Op.lte]: end,
},
};
}
}
if (filter.enrollment_dateRange) {
const [start, end] = filter.enrollment_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
enrollment_date: {
...where.enrollment_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
enrollment_date: {
...where.enrollment_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.gender) {
where = {
...where,
gender: filter.gender,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.school) {
const listItems = filter.school.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.students.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'students',
'nis',
query,
),
],
};
}
const records = await db.students.findAll({
attributes: [ 'id', 'nis' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['nis', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.nis,
}));
}
};

View File

@ -0,0 +1,457 @@
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 SubjectsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subjects = await db.subjects.create(
{
id: data.id || undefined,
name: data.name
||
null
,
code: data.code
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await subjects.setSchool( data.school || null, {
transaction,
});
return subjects;
}
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 subjectsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
code: item.code
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const subjects = await db.subjects.bulkCreate(subjectsData, { transaction });
// For each item created, replace relation files
return subjects;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const subjects = await db.subjects.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await subjects.update(updatePayload, {transaction});
if (data.school !== undefined) {
await subjects.setSchool(
data.school,
{ transaction }
);
}
return subjects;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subjects = await db.subjects.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of subjects) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of subjects) {
await record.destroy({transaction});
}
});
return subjects;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const subjects = await db.subjects.findByPk(id, options);
await subjects.update({
deletedBy: currentUser.id
}, {
transaction,
});
await subjects.destroy({
transaction
});
return subjects;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const subjects = await db.subjects.findOne(
{ where },
{ transaction },
);
if (!subjects) {
return subjects;
}
const output = subjects.get({plain: true});
output.class_subjects_subject = await subjects.getClass_subjects_subject({
transaction
});
output.school = await subjects.getSchool({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.schools,
as: 'school',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'subjects',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'subjects',
'code',
filter.code,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.school) {
const listItems = filter.school.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.subjects.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'subjects',
'name',
query,
),
],
};
}
const records = await db.subjects.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,608 @@
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 Timetable_entriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const timetable_entries = await db.timetable_entries.create(
{
id: data.id || undefined,
day_of_week: data.day_of_week
||
null
,
period_number: data.period_number
||
null
,
start_time: data.start_time
||
null
,
end_time: data.end_time
||
null
,
room: data.room
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await timetable_entries.setClass( data.class || null, {
transaction,
});
await timetable_entries.setClass_subject( data.class_subject || null, {
transaction,
});
await timetable_entries.setSchools( data.schools || null, {
transaction,
});
return timetable_entries;
}
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 timetable_entriesData = data.map((item, index) => ({
id: item.id || undefined,
day_of_week: item.day_of_week
||
null
,
period_number: item.period_number
||
null
,
start_time: item.start_time
||
null
,
end_time: item.end_time
||
null
,
room: item.room
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const timetable_entries = await db.timetable_entries.bulkCreate(timetable_entriesData, { transaction });
// For each item created, replace relation files
return timetable_entries;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const timetable_entries = await db.timetable_entries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.day_of_week !== undefined) updatePayload.day_of_week = data.day_of_week;
if (data.period_number !== undefined) updatePayload.period_number = data.period_number;
if (data.start_time !== undefined) updatePayload.start_time = data.start_time;
if (data.end_time !== undefined) updatePayload.end_time = data.end_time;
if (data.room !== undefined) updatePayload.room = data.room;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await timetable_entries.update(updatePayload, {transaction});
if (data.class !== undefined) {
await timetable_entries.setClass(
data.class,
{ transaction }
);
}
if (data.class_subject !== undefined) {
await timetable_entries.setClass_subject(
data.class_subject,
{ transaction }
);
}
if (data.schools !== undefined) {
await timetable_entries.setSchools(
data.schools,
{ transaction }
);
}
return timetable_entries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const timetable_entries = await db.timetable_entries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of timetable_entries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of timetable_entries) {
await record.destroy({transaction});
}
});
return timetable_entries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const timetable_entries = await db.timetable_entries.findByPk(id, options);
await timetable_entries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await timetable_entries.destroy({
transaction
});
return timetable_entries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const timetable_entries = await db.timetable_entries.findOne(
{ where },
{ transaction },
);
if (!timetable_entries) {
return timetable_entries;
}
const output = timetable_entries.get({plain: true});
output.class = await timetable_entries.getClass({
transaction
});
output.class_subject = await timetable_entries.getClass_subject({
transaction
});
output.schools = await timetable_entries.getSchools({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSchools = (user && user.schools?.id) || null;
if (userSchools) {
if (options?.currentUser?.schoolsId) {
where.schoolsId = options.currentUser.schoolsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.classes,
as: 'class',
where: filter.class ? {
[Op.or]: [
{ id: { [Op.in]: filter.class.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.class.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.class_subjects,
as: 'class_subject',
where: filter.class_subject ? {
[Op.or]: [
{ id: { [Op.in]: filter.class_subject.split('|').map(term => Utils.uuid(term)) } },
{
weekly_sessions: {
[Op.or]: filter.class_subject.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.schools,
as: 'schools',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.start_time) {
where = {
...where,
[Op.and]: Utils.ilike(
'timetable_entries',
'start_time',
filter.start_time,
),
};
}
if (filter.end_time) {
where = {
...where,
[Op.and]: Utils.ilike(
'timetable_entries',
'end_time',
filter.end_time,
),
};
}
if (filter.room) {
where = {
...where,
[Op.and]: Utils.ilike(
'timetable_entries',
'room',
filter.room,
),
};
}
if (filter.period_numberRange) {
const [start, end] = filter.period_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_number: {
...where.period_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_number: {
...where.period_number,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.day_of_week) {
where = {
...where,
day_of_week: filter.day_of_week,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.schools) {
const listItems = filter.schools.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
schoolsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.schoolsId;
}
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.timetable_entries.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'timetable_entries',
'room',
query,
),
],
};
}
const records = await db.timetable_entries.findAll({
attributes: [ 'id', 'room' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['room', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.room,
}));
}
};

1062
backend/src/db/api/users.js Normal file

File diff suppressed because it is too large Load Diff

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_sistem_sekolah_indonesia',
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,140 @@
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 academic_years = sequelize.define(
'academic_years',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
start_date: {
type: DataTypes.DATE,
},
end_date: {
type: DataTypes.DATE,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
academic_years.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.academic_years.hasMany(db.classes, {
as: 'classes_academic_year',
foreignKey: {
name: 'academic_yearId',
},
constraints: false,
});
db.academic_years.hasMany(db.fee_definitions, {
as: 'fee_definitions_academic_year',
foreignKey: {
name: 'academic_yearId',
},
constraints: false,
});
//end loop
db.academic_years.belongsTo(db.schools, {
as: 'school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.academic_years.belongsTo(db.users, {
as: 'createdBy',
});
db.academic_years.belongsTo(db.users, {
as: 'updatedBy',
});
};
return academic_years;
};

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 announcements = sequelize.define(
'announcements',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
content: {
type: DataTypes.TEXT,
},
audience: {
type: DataTypes.ENUM,
values: [
"semua",
"guru",
"siswa",
"orang_tua",
"kelas_tertentu"
],
},
publish_at: {
type: DataTypes.DATE,
},
expire_at: {
type: DataTypes.DATE,
},
pinned: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
announcements.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.announcements.belongsTo(db.schools, {
as: 'school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.announcements.belongsTo(db.classes, {
as: 'target_class',
foreignKey: {
name: 'target_classId',
},
constraints: false,
});
db.announcements.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.announcements.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.announcements.getTableName(),
belongsToColumn: 'attachments',
},
});
db.announcements.belongsTo(db.users, {
as: 'createdBy',
});
db.announcements.belongsTo(db.users, {
as: 'updatedBy',
});
};
return announcements;
};

View File

@ -0,0 +1,181 @@
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 assignment_submissions = sequelize.define(
'assignment_submissions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
submitted_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"belum",
"sudah",
"terlambat"
],
},
answer_text: {
type: DataTypes.TEXT,
},
score: {
type: DataTypes.DECIMAL,
},
teacher_feedback: {
type: DataTypes.TEXT,
},
graded_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
assignment_submissions.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.assignment_submissions.belongsTo(db.assignments, {
as: 'assignment',
foreignKey: {
name: 'assignmentId',
},
constraints: false,
});
db.assignment_submissions.belongsTo(db.students, {
as: 'student',
foreignKey: {
name: 'studentId',
},
constraints: false,
});
db.assignment_submissions.belongsTo(db.users, {
as: 'graded_by',
foreignKey: {
name: 'graded_byId',
},
constraints: false,
});
db.assignment_submissions.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.assignment_submissions.hasMany(db.file, {
as: 'answer_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.assignment_submissions.getTableName(),
belongsToColumn: 'answer_files',
},
});
db.assignment_submissions.belongsTo(db.users, {
as: 'createdBy',
});
db.assignment_submissions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return assignment_submissions;
};

View File

@ -0,0 +1,181 @@
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 assignments = sequelize.define(
'assignments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
assigned_at: {
type: DataTypes.DATE,
},
due_at: {
type: DataTypes.DATE,
},
submission_type: {
type: DataTypes.ENUM,
values: [
"offline",
"online"
],
},
published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
assignments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.assignments.hasMany(db.assignment_submissions, {
as: 'assignment_submissions_assignment',
foreignKey: {
name: 'assignmentId',
},
constraints: false,
});
//end loop
db.assignments.belongsTo(db.class_subjects, {
as: 'class_subject',
foreignKey: {
name: 'class_subjectId',
},
constraints: false,
});
db.assignments.belongsTo(db.users, {
as: 'created_by',
foreignKey: {
name: 'created_byId',
},
constraints: false,
});
db.assignments.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.assignments.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.assignments.getTableName(),
belongsToColumn: 'attachments',
},
});
db.assignments.belongsTo(db.users, {
as: 'createdBy',
});
db.assignments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return assignments;
};

View File

@ -0,0 +1,153 @@
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 attendance_records = sequelize.define(
'attendance_records',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"hadir",
"sakit",
"izin",
"alpha"
],
},
remarks: {
type: DataTypes.TEXT,
},
checked_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
attendance_records.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.attendance_records.belongsTo(db.attendance_sessions, {
as: 'attendance_session',
foreignKey: {
name: 'attendance_sessionId',
},
constraints: false,
});
db.attendance_records.belongsTo(db.students, {
as: 'student',
foreignKey: {
name: 'studentId',
},
constraints: false,
});
db.attendance_records.belongsTo(db.users, {
as: 'checked_by',
foreignKey: {
name: 'checked_byId',
},
constraints: false,
});
db.attendance_records.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.attendance_records.belongsTo(db.users, {
as: 'createdBy',
});
db.attendance_records.belongsTo(db.users, {
as: 'updatedBy',
});
};
return attendance_records;
};

View File

@ -0,0 +1,131 @@
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 attendance_sessions = sequelize.define(
'attendance_sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
attendance_date: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
attendance_sessions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.attendance_sessions.hasMany(db.attendance_records, {
as: 'attendance_records_attendance_session',
foreignKey: {
name: 'attendance_sessionId',
},
constraints: false,
});
//end loop
db.attendance_sessions.belongsTo(db.classes, {
as: 'class',
foreignKey: {
name: 'classId',
},
constraints: false,
});
db.attendance_sessions.belongsTo(db.users, {
as: 'recorded_by',
foreignKey: {
name: 'recorded_byId',
},
constraints: false,
});
db.attendance_sessions.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.attendance_sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.attendance_sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return attendance_sessions;
};

View File

@ -0,0 +1,214 @@
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 billing_items = sequelize.define(
'billing_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
bill_number: {
type: DataTypes.TEXT,
},
period_type: {
type: DataTypes.ENUM,
values: [
"bulanan",
"sekali"
],
},
period_year: {
type: DataTypes.INTEGER,
},
period_month: {
type: DataTypes.INTEGER,
},
issued_at: {
type: DataTypes.DATE,
},
due_at: {
type: DataTypes.DATE,
},
amount_total: {
type: DataTypes.DECIMAL,
},
amount_paid: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"belum_bayar",
"cicilan",
"lunas",
"jatuh_tempo",
"dibatalkan"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
billing_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.billing_items.hasMany(db.payments, {
as: 'payments_billing_item',
foreignKey: {
name: 'billing_itemId',
},
constraints: false,
});
//end loop
db.billing_items.belongsTo(db.fee_definitions, {
as: 'fee_definition',
foreignKey: {
name: 'fee_definitionId',
},
constraints: false,
});
db.billing_items.belongsTo(db.students, {
as: 'student',
foreignKey: {
name: 'studentId',
},
constraints: false,
});
db.billing_items.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.billing_items.belongsTo(db.users, {
as: 'createdBy',
});
db.billing_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return billing_items;
};

View File

@ -0,0 +1,158 @@
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 class_subjects = sequelize.define(
'class_subjects',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
weekly_sessions: {
type: DataTypes.INTEGER,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
class_subjects.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.class_subjects.hasMany(db.timetable_entries, {
as: 'timetable_entries_class_subject',
foreignKey: {
name: 'class_subjectId',
},
constraints: false,
});
db.class_subjects.hasMany(db.assignments, {
as: 'assignments_class_subject',
foreignKey: {
name: 'class_subjectId',
},
constraints: false,
});
db.class_subjects.hasMany(db.exams, {
as: 'exams_class_subject',
foreignKey: {
name: 'class_subjectId',
},
constraints: false,
});
//end loop
db.class_subjects.belongsTo(db.classes, {
as: 'class',
foreignKey: {
name: 'classId',
},
constraints: false,
});
db.class_subjects.belongsTo(db.subjects, {
as: 'subject',
foreignKey: {
name: 'subjectId',
},
constraints: false,
});
db.class_subjects.belongsTo(db.users, {
as: 'teacher',
foreignKey: {
name: 'teacherId',
},
constraints: false,
});
db.class_subjects.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.class_subjects.belongsTo(db.users, {
as: 'createdBy',
});
db.class_subjects.belongsTo(db.users, {
as: 'updatedBy',
});
};
return class_subjects;
};

View File

@ -0,0 +1,196 @@
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 classes = sequelize.define(
'classes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
grade: {
type: DataTypes.INTEGER,
},
homeroom_label: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
classes.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.classes.hasMany(db.students, {
as: 'students_current_class',
foreignKey: {
name: 'current_classId',
},
constraints: false,
});
db.classes.hasMany(db.class_subjects, {
as: 'class_subjects_class',
foreignKey: {
name: 'classId',
},
constraints: false,
});
db.classes.hasMany(db.timetable_entries, {
as: 'timetable_entries_class',
foreignKey: {
name: 'classId',
},
constraints: false,
});
db.classes.hasMany(db.attendance_sessions, {
as: 'attendance_sessions_class',
foreignKey: {
name: 'classId',
},
constraints: false,
});
db.classes.hasMany(db.announcements, {
as: 'announcements_target_class',
foreignKey: {
name: 'target_classId',
},
constraints: false,
});
db.classes.hasMany(db.fee_definitions, {
as: 'fee_definitions_class',
foreignKey: {
name: 'classId',
},
constraints: false,
});
//end loop
db.classes.belongsTo(db.schools, {
as: 'school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.classes.belongsTo(db.academic_years, {
as: 'academic_year',
foreignKey: {
name: 'academic_yearId',
},
constraints: false,
});
db.classes.belongsTo(db.education_levels, {
as: 'education_level',
foreignKey: {
name: 'education_levelId',
},
constraints: false,
});
db.classes.belongsTo(db.users, {
as: 'homeroom_teacher',
foreignKey: {
name: 'homeroom_teacherId',
},
constraints: false,
});
db.classes.belongsTo(db.users, {
as: 'createdBy',
});
db.classes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return classes;
};

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 education_levels = sequelize.define(
'education_levels',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
level: {
type: DataTypes.ENUM,
values: [
"sd",
"smp",
"sma",
"smk"
],
},
name: {
type: DataTypes.TEXT,
},
grade_start: {
type: DataTypes.INTEGER,
},
grade_end: {
type: DataTypes.INTEGER,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
education_levels.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.education_levels.hasMany(db.classes, {
as: 'classes_education_level',
foreignKey: {
name: 'education_levelId',
},
constraints: false,
});
db.education_levels.hasMany(db.fee_definitions, {
as: 'fee_definitions_education_level',
foreignKey: {
name: 'education_levelId',
},
constraints: false,
});
//end loop
db.education_levels.belongsTo(db.schools, {
as: 'school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.education_levels.belongsTo(db.users, {
as: 'createdBy',
});
db.education_levels.belongsTo(db.users, {
as: 'updatedBy',
});
};
return education_levels;
};

View File

@ -0,0 +1,146 @@
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 exam_answers = sequelize.define(
'exam_answers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
answer_text: {
type: DataTypes.TEXT,
},
score: {
type: DataTypes.DECIMAL,
},
graded_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
exam_answers.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.exam_answers.belongsTo(db.exam_attempts, {
as: 'exam_attempt',
foreignKey: {
name: 'exam_attemptId',
},
constraints: false,
});
db.exam_answers.belongsTo(db.exam_questions, {
as: 'exam_question',
foreignKey: {
name: 'exam_questionId',
},
constraints: false,
});
db.exam_answers.belongsTo(db.exam_question_choices, {
as: 'selected_choice',
foreignKey: {
name: 'selected_choiceId',
},
constraints: false,
});
db.exam_answers.belongsTo(db.users, {
as: 'graded_by',
foreignKey: {
name: 'graded_byId',
},
constraints: false,
});
db.exam_answers.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.exam_answers.belongsTo(db.users, {
as: 'createdBy',
});
db.exam_answers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return exam_answers;
};

View File

@ -0,0 +1,170 @@
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 exam_attempts = sequelize.define(
'exam_attempts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
started_at: {
type: DataTypes.DATE,
},
submitted_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"belum_mulai",
"sedang",
"selesai",
"dibatalkan"
],
},
score_total: {
type: DataTypes.DECIMAL,
},
passed: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
exam_attempts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.exam_attempts.hasMany(db.exam_answers, {
as: 'exam_answers_exam_attempt',
foreignKey: {
name: 'exam_attemptId',
},
constraints: false,
});
//end loop
db.exam_attempts.belongsTo(db.exams, {
as: 'exam',
foreignKey: {
name: 'examId',
},
constraints: false,
});
db.exam_attempts.belongsTo(db.students, {
as: 'student',
foreignKey: {
name: 'studentId',
},
constraints: false,
});
db.exam_attempts.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.exam_attempts.belongsTo(db.users, {
as: 'createdBy',
});
db.exam_attempts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return exam_attempts;
};

View File

@ -0,0 +1,143 @@
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 exam_categories = sequelize.define(
'exam_categories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
type: {
type: DataTypes.ENUM,
values: [
"ulangan_harian",
"uts",
"uas",
"kenaikan_kelas",
"lainnya"
],
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
exam_categories.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.exam_categories.hasMany(db.exams, {
as: 'exams_category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
//end loop
db.exam_categories.belongsTo(db.schools, {
as: 'school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.exam_categories.belongsTo(db.users, {
as: 'createdBy',
});
db.exam_categories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return exam_categories;
};

View File

@ -0,0 +1,140 @@
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 exam_question_choices = sequelize.define(
'exam_question_choices',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
choice_label: {
type: DataTypes.TEXT,
},
choice_text: {
type: DataTypes.TEXT,
},
is_correct: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
order_number: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
exam_question_choices.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.exam_question_choices.hasMany(db.exam_answers, {
as: 'exam_answers_selected_choice',
foreignKey: {
name: 'selected_choiceId',
},
constraints: false,
});
//end loop
db.exam_question_choices.belongsTo(db.exam_questions, {
as: 'exam_question',
foreignKey: {
name: 'exam_questionId',
},
constraints: false,
});
db.exam_question_choices.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.exam_question_choices.belongsTo(db.users, {
as: 'createdBy',
});
db.exam_question_choices.belongsTo(db.users, {
as: 'updatedBy',
});
};
return exam_question_choices;
};

View File

@ -0,0 +1,174 @@
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 exam_questions = sequelize.define(
'exam_questions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
question_type: {
type: DataTypes.ENUM,
values: [
"pilihan_ganda",
"essay"
],
},
question_text: {
type: DataTypes.TEXT,
},
points: {
type: DataTypes.DECIMAL,
},
order_number: {
type: DataTypes.INTEGER,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
exam_questions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.exam_questions.hasMany(db.exam_question_choices, {
as: 'exam_question_choices_exam_question',
foreignKey: {
name: 'exam_questionId',
},
constraints: false,
});
db.exam_questions.hasMany(db.exam_answers, {
as: 'exam_answers_exam_question',
foreignKey: {
name: 'exam_questionId',
},
constraints: false,
});
//end loop
db.exam_questions.belongsTo(db.exams, {
as: 'exam',
foreignKey: {
name: 'examId',
},
constraints: false,
});
db.exam_questions.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.exam_questions.hasMany(db.file, {
as: 'question_media',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.exam_questions.getTableName(),
belongsToColumn: 'question_media',
},
});
db.exam_questions.belongsTo(db.users, {
as: 'createdBy',
});
db.exam_questions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return exam_questions;
};

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 exams = sequelize.define(
'exams',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
mode: {
type: DataTypes.ENUM,
values: [
"paper",
"cbt"
],
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
duration_minutes: {
type: DataTypes.INTEGER,
},
randomize_questions: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
passing_score: {
type: DataTypes.DECIMAL,
},
published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
exams.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.exams.hasMany(db.exam_questions, {
as: 'exam_questions_exam',
foreignKey: {
name: 'examId',
},
constraints: false,
});
db.exams.hasMany(db.exam_attempts, {
as: 'exam_attempts_exam',
foreignKey: {
name: 'examId',
},
constraints: false,
});
//end loop
db.exams.belongsTo(db.class_subjects, {
as: 'class_subject',
foreignKey: {
name: 'class_subjectId',
},
constraints: false,
});
db.exams.belongsTo(db.exam_categories, {
as: 'category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
db.exams.belongsTo(db.users, {
as: 'created_by',
foreignKey: {
name: 'created_byId',
},
constraints: false,
});
db.exams.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.exams.belongsTo(db.users, {
as: 'createdBy',
});
db.exams.belongsTo(db.users, {
as: 'updatedBy',
});
};
return exams;
};

View File

@ -0,0 +1,196 @@
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 fee_definitions = sequelize.define(
'fee_definitions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
fee_type: {
type: DataTypes.ENUM,
values: [
"spp_bulanan",
"pendaftaran"
],
},
name: {
type: DataTypes.TEXT,
},
amount: {
type: DataTypes.DECIMAL,
},
allow_installments: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
minimum_down_payment: {
type: DataTypes.DECIMAL,
},
max_installments: {
type: DataTypes.INTEGER,
},
installment_deadline: {
type: DataTypes.DATE,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
fee_definitions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.fee_definitions.hasMany(db.billing_items, {
as: 'billing_items_fee_definition',
foreignKey: {
name: 'fee_definitionId',
},
constraints: false,
});
//end loop
db.fee_definitions.belongsTo(db.schools, {
as: 'school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.fee_definitions.belongsTo(db.academic_years, {
as: 'academic_year',
foreignKey: {
name: 'academic_yearId',
},
constraints: false,
});
db.fee_definitions.belongsTo(db.education_levels, {
as: 'education_level',
foreignKey: {
name: 'education_levelId',
},
constraints: false,
});
db.fee_definitions.belongsTo(db.classes, {
as: 'class',
foreignKey: {
name: 'classId',
},
constraints: false,
});
db.fee_definitions.belongsTo(db.users, {
as: 'createdBy',
});
db.fee_definitions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return fee_definitions;
};

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,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,194 @@
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 notification_logs = sequelize.define(
'notification_logs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
channel: {
type: DataTypes.ENUM,
values: [
"in_app",
"email",
"sms",
"whatsapp"
],
},
category: {
type: DataTypes.ENUM,
values: [
"absensi",
"tagihan",
"pengumuman",
"tugas",
"ujian",
"lainnya"
],
},
title: {
type: DataTypes.TEXT,
},
message: {
type: DataTypes.TEXT,
},
sent_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"sent",
"failed",
"read"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notification_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.notification_logs.belongsTo(db.schools, {
as: 'school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.notification_logs.belongsTo(db.users, {
as: 'recipient_user',
foreignKey: {
name: 'recipient_userId',
},
constraints: false,
});
db.notification_logs.belongsTo(db.users, {
as: 'createdBy',
});
db.notification_logs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notification_logs;
};

View File

@ -0,0 +1,138 @@
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 parent_student_links = sequelize.define(
'parent_student_links',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
relationship: {
type: DataTypes.ENUM,
values: [
"ayah",
"ibu",
"wali"
],
},
is_primary: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
parent_student_links.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.parent_student_links.belongsTo(db.users, {
as: 'parent_user',
foreignKey: {
name: 'parent_userId',
},
constraints: false,
});
db.parent_student_links.belongsTo(db.students, {
as: 'student',
foreignKey: {
name: 'studentId',
},
constraints: false,
});
db.parent_student_links.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.parent_student_links.belongsTo(db.users, {
as: 'createdBy',
});
db.parent_student_links.belongsTo(db.users, {
as: 'updatedBy',
});
};
return parent_student_links;
};

View File

@ -0,0 +1,194 @@
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 payments = sequelize.define(
'payments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
paid_at: {
type: DataTypes.DATE,
},
amount: {
type: DataTypes.DECIMAL,
},
method: {
type: DataTypes.ENUM,
values: [
"cash",
"transfer",
"va",
"qris",
"lainnya"
],
},
reference_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"success",
"failed",
"refunded"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payments.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.payments.belongsTo(db.billing_items, {
as: 'billing_item',
foreignKey: {
name: 'billing_itemId',
},
constraints: false,
});
db.payments.belongsTo(db.users, {
as: 'paid_by_user',
foreignKey: {
name: 'paid_by_userId',
},
constraints: false,
});
db.payments.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.payments.hasMany(db.file, {
as: 'proof',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.payments.getTableName(),
belongsToColumn: 'proof',
},
});
db.payments.belongsTo(db.users, {
as: 'createdBy',
});
db.payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payments;
};

View File

@ -0,0 +1,92 @@
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,135 @@
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,
},
globalAccess: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
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,284 @@
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 schools = sequelize.define(
'schools',
{
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,
},
);
schools.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.schools.hasMany(db.users, {
as: 'users_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.academic_years, {
as: 'academic_years_school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.schools.hasMany(db.education_levels, {
as: 'education_levels_school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.schools.hasMany(db.classes, {
as: 'classes_school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.schools.hasMany(db.students, {
as: 'students_school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.schools.hasMany(db.parent_student_links, {
as: 'parent_student_links_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.subjects, {
as: 'subjects_school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.schools.hasMany(db.class_subjects, {
as: 'class_subjects_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.timetable_entries, {
as: 'timetable_entries_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.attendance_sessions, {
as: 'attendance_sessions_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.attendance_records, {
as: 'attendance_records_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.announcements, {
as: 'announcements_school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.schools.hasMany(db.assignments, {
as: 'assignments_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.assignment_submissions, {
as: 'assignment_submissions_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.exam_categories, {
as: 'exam_categories_school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.schools.hasMany(db.exams, {
as: 'exams_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.exam_questions, {
as: 'exam_questions_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.exam_question_choices, {
as: 'exam_question_choices_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.exam_attempts, {
as: 'exam_attempts_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.exam_answers, {
as: 'exam_answers_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.fee_definitions, {
as: 'fee_definitions_school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.schools.hasMany(db.billing_items, {
as: 'billing_items_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.payments, {
as: 'payments_schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.schools.hasMany(db.notification_logs, {
as: 'notification_logs_school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
//end loop
db.schools.belongsTo(db.users, {
as: 'createdBy',
});
db.schools.belongsTo(db.users, {
as: 'updatedBy',
});
};
return schools;
};

View File

@ -0,0 +1,229 @@
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 students = sequelize.define(
'students',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
nis: {
type: DataTypes.TEXT,
},
nisn: {
type: DataTypes.TEXT,
},
birth_place: {
type: DataTypes.TEXT,
},
birth_date: {
type: DataTypes.DATE,
},
gender: {
type: DataTypes.ENUM,
values: [
"laki_laki",
"perempuan"
],
},
address: {
type: DataTypes.TEXT,
},
enrollment_date: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"aktif",
"nonaktif",
"lulus",
"pindah"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
students.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.students.hasMany(db.parent_student_links, {
as: 'parent_student_links_student',
foreignKey: {
name: 'studentId',
},
constraints: false,
});
db.students.hasMany(db.attendance_records, {
as: 'attendance_records_student',
foreignKey: {
name: 'studentId',
},
constraints: false,
});
db.students.hasMany(db.assignment_submissions, {
as: 'assignment_submissions_student',
foreignKey: {
name: 'studentId',
},
constraints: false,
});
db.students.hasMany(db.exam_attempts, {
as: 'exam_attempts_student',
foreignKey: {
name: 'studentId',
},
constraints: false,
});
db.students.hasMany(db.billing_items, {
as: 'billing_items_student',
foreignKey: {
name: 'studentId',
},
constraints: false,
});
//end loop
db.students.belongsTo(db.schools, {
as: 'school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.students.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.students.belongsTo(db.classes, {
as: 'current_class',
foreignKey: {
name: 'current_classId',
},
constraints: false,
});
db.students.belongsTo(db.users, {
as: 'createdBy',
});
db.students.belongsTo(db.users, {
as: 'updatedBy',
});
};
return students;
};

View File

@ -0,0 +1,125 @@
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 subjects = sequelize.define(
'subjects',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
subjects.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.subjects.hasMany(db.class_subjects, {
as: 'class_subjects_subject',
foreignKey: {
name: 'subjectId',
},
constraints: false,
});
//end loop
db.subjects.belongsTo(db.schools, {
as: 'school',
foreignKey: {
name: 'schoolId',
},
constraints: false,
});
db.subjects.belongsTo(db.users, {
as: 'createdBy',
});
db.subjects.belongsTo(db.users, {
as: 'updatedBy',
});
};
return subjects;
};

View File

@ -0,0 +1,175 @@
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 timetable_entries = sequelize.define(
'timetable_entries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
day_of_week: {
type: DataTypes.ENUM,
values: [
"senin",
"selasa",
"rabu",
"kamis",
"jumat",
"sabtu"
],
},
period_number: {
type: DataTypes.INTEGER,
},
start_time: {
type: DataTypes.TEXT,
},
end_time: {
type: DataTypes.TEXT,
},
room: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
timetable_entries.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.timetable_entries.belongsTo(db.classes, {
as: 'class',
foreignKey: {
name: 'classId',
},
constraints: false,
});
db.timetable_entries.belongsTo(db.class_subjects, {
as: 'class_subject',
foreignKey: {
name: 'class_subjectId',
},
constraints: false,
});
db.timetable_entries.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
constraints: false,
});
db.timetable_entries.belongsTo(db.users, {
as: 'createdBy',
});
db.timetable_entries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return timetable_entries;
};

View File

@ -0,0 +1,362 @@
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.classes, {
as: 'classes_homeroom_teacher',
foreignKey: {
name: 'homeroom_teacherId',
},
constraints: false,
});
db.users.hasMany(db.students, {
as: 'students_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.parent_student_links, {
as: 'parent_student_links_parent_user',
foreignKey: {
name: 'parent_userId',
},
constraints: false,
});
db.users.hasMany(db.class_subjects, {
as: 'class_subjects_teacher',
foreignKey: {
name: 'teacherId',
},
constraints: false,
});
db.users.hasMany(db.attendance_sessions, {
as: 'attendance_sessions_recorded_by',
foreignKey: {
name: 'recorded_byId',
},
constraints: false,
});
db.users.hasMany(db.attendance_records, {
as: 'attendance_records_checked_by',
foreignKey: {
name: 'checked_byId',
},
constraints: false,
});
db.users.hasMany(db.announcements, {
as: 'announcements_author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.users.hasMany(db.assignments, {
as: 'assignments_created_by',
foreignKey: {
name: 'created_byId',
},
constraints: false,
});
db.users.hasMany(db.assignment_submissions, {
as: 'assignment_submissions_graded_by',
foreignKey: {
name: 'graded_byId',
},
constraints: false,
});
db.users.hasMany(db.exams, {
as: 'exams_created_by',
foreignKey: {
name: 'created_byId',
},
constraints: false,
});
db.users.hasMany(db.exam_answers, {
as: 'exam_answers_graded_by',
foreignKey: {
name: 'graded_byId',
},
constraints: false,
});
db.users.hasMany(db.payments, {
as: 'payments_paid_by_user',
foreignKey: {
name: 'paid_by_userId',
},
constraints: false,
});
db.users.hasMany(db.notification_logs, {
as: 'notification_logs_recipient_user',
foreignKey: {
name: 'recipient_userId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.belongsTo(db.schools, {
as: 'schools',
foreignKey: {
name: 'schoolsId',
},
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,77 @@
'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',
'ab4cf9bf-4eef-4107-b73d-9d0274cf69bc',
]
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()
},
{
id: ids[3],
firstName: 'Super Admin',
email: 'super_admin@flatlogic.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: admin_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'});
};
};

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

@ -0,0 +1,241 @@
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 organizationForAuthRoutes = require('./routes/organizationLogin');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const schoolsRoutes = require('./routes/schools');
const academic_yearsRoutes = require('./routes/academic_years');
const education_levelsRoutes = require('./routes/education_levels');
const classesRoutes = require('./routes/classes');
const studentsRoutes = require('./routes/students');
const parent_student_linksRoutes = require('./routes/parent_student_links');
const subjectsRoutes = require('./routes/subjects');
const class_subjectsRoutes = require('./routes/class_subjects');
const timetable_entriesRoutes = require('./routes/timetable_entries');
const attendance_sessionsRoutes = require('./routes/attendance_sessions');
const attendance_recordsRoutes = require('./routes/attendance_records');
const announcementsRoutes = require('./routes/announcements');
const assignmentsRoutes = require('./routes/assignments');
const assignment_submissionsRoutes = require('./routes/assignment_submissions');
const exam_categoriesRoutes = require('./routes/exam_categories');
const examsRoutes = require('./routes/exams');
const exam_questionsRoutes = require('./routes/exam_questions');
const exam_question_choicesRoutes = require('./routes/exam_question_choices');
const exam_attemptsRoutes = require('./routes/exam_attempts');
const exam_answersRoutes = require('./routes/exam_answers');
const fee_definitionsRoutes = require('./routes/fee_definitions');
const billing_itemsRoutes = require('./routes/billing_items');
const paymentsRoutes = require('./routes/payments');
const notification_logsRoutes = require('./routes/notification_logs');
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: "Sistem Sekolah Indonesia",
description: "Sistem Sekolah Indonesia 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/schools', passport.authenticate('jwt', {session: false}), schoolsRoutes);
app.use('/api/academic_years', passport.authenticate('jwt', {session: false}), academic_yearsRoutes);
app.use('/api/education_levels', passport.authenticate('jwt', {session: false}), education_levelsRoutes);
app.use('/api/classes', passport.authenticate('jwt', {session: false}), classesRoutes);
app.use('/api/students', passport.authenticate('jwt', {session: false}), studentsRoutes);
app.use('/api/parent_student_links', passport.authenticate('jwt', {session: false}), parent_student_linksRoutes);
app.use('/api/subjects', passport.authenticate('jwt', {session: false}), subjectsRoutes);
app.use('/api/class_subjects', passport.authenticate('jwt', {session: false}), class_subjectsRoutes);
app.use('/api/timetable_entries', passport.authenticate('jwt', {session: false}), timetable_entriesRoutes);
app.use('/api/attendance_sessions', passport.authenticate('jwt', {session: false}), attendance_sessionsRoutes);
app.use('/api/attendance_records', passport.authenticate('jwt', {session: false}), attendance_recordsRoutes);
app.use('/api/announcements', passport.authenticate('jwt', {session: false}), announcementsRoutes);
app.use('/api/assignments', passport.authenticate('jwt', {session: false}), assignmentsRoutes);
app.use('/api/assignment_submissions', passport.authenticate('jwt', {session: false}), assignment_submissionsRoutes);
app.use('/api/exam_categories', passport.authenticate('jwt', {session: false}), exam_categoriesRoutes);
app.use('/api/exams', passport.authenticate('jwt', {session: false}), examsRoutes);
app.use('/api/exam_questions', passport.authenticate('jwt', {session: false}), exam_questionsRoutes);
app.use('/api/exam_question_choices', passport.authenticate('jwt', {session: false}), exam_question_choicesRoutes);
app.use('/api/exam_attempts', passport.authenticate('jwt', {session: false}), exam_attemptsRoutes);
app.use('/api/exam_answers', passport.authenticate('jwt', {session: false}), exam_answersRoutes);
app.use('/api/fee_definitions', passport.authenticate('jwt', {session: false}), fee_definitionsRoutes);
app.use('/api/billing_items', passport.authenticate('jwt', {session: false}), billing_itemsRoutes);
app.use('/api/payments', passport.authenticate('jwt', {session: false}), paymentsRoutes);
app.use('/api/notification_logs', passport.authenticate('jwt', {session: false}), notification_logsRoutes);
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);
app.use(
'/api/org-for-auth',
organizationForAuthRoutes,
);
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;
db.sequelize.sync().then(function () {
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,440 @@
const express = require('express');
const Academic_yearsService = require('../services/academic_years');
const Academic_yearsDBApi = require('../db/api/academic_years');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('academic_years'));
/**
* @swagger
* components:
* schemas:
* Academic_years:
* type: object
* properties:
* name:
* type: string
* default: name
*/
/**
* @swagger
* tags:
* name: Academic_years
* description: The Academic_years managing API
*/
/**
* @swagger
* /api/academic_years:
* post:
* security:
* - bearerAuth: []
* tags: [Academic_years]
* 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/Academic_years"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Academic_years"
* 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 Academic_yearsService.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: [Academic_years]
* 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/Academic_years"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Academic_years"
* 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 Academic_yearsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/academic_years/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Academic_years]
* 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/Academic_years"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Academic_years"
* 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 Academic_yearsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/academic_years/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Academic_years]
* 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/Academic_years"
* 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 Academic_yearsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/academic_years/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Academic_years]
* 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/Academic_years"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Academic_yearsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/academic_years:
* get:
* security:
* - bearerAuth: []
* tags: [Academic_years]
* summary: Get all academic_years
* description: Get all academic_years
* responses:
* 200:
* description: Academic_years list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Academic_years"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Academic_yearsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name',
'start_date','end_date',
];
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/academic_years/count:
* get:
* security:
* - bearerAuth: []
* tags: [Academic_years]
* summary: Count all academic_years
* description: Count all academic_years
* responses:
* 200:
* description: Academic_years count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Academic_years"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Academic_yearsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/academic_years/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Academic_years]
* summary: Find all academic_years that match search criteria
* description: Find all academic_years that match search criteria
* responses:
* 200:
* description: Academic_years list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Academic_years"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await Academic_yearsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/academic_years/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Academic_years]
* 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/Academic_years"
* 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 Academic_yearsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,444 @@
const express = require('express');
const AnnouncementsService = require('../services/announcements');
const AnnouncementsDBApi = require('../db/api/announcements');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('announcements'));
/**
* @swagger
* components:
* schemas:
* Announcements:
* type: object
* properties:
* title:
* type: string
* default: title
* content:
* type: string
* default: content
*
*/
/**
* @swagger
* tags:
* name: Announcements
* description: The Announcements managing API
*/
/**
* @swagger
* /api/announcements:
* post:
* security:
* - bearerAuth: []
* tags: [Announcements]
* 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/Announcements"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Announcements"
* 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 AnnouncementsService.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: [Announcements]
* 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/Announcements"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Announcements"
* 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 AnnouncementsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/announcements/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Announcements]
* 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/Announcements"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Announcements"
* 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 AnnouncementsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/announcements/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Announcements]
* 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/Announcements"
* 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 AnnouncementsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/announcements/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Announcements]
* 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/Announcements"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await AnnouncementsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/announcements:
* get:
* security:
* - bearerAuth: []
* tags: [Announcements]
* summary: Get all announcements
* description: Get all announcements
* responses:
* 200:
* description: Announcements list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Announcements"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await AnnouncementsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','title','content',
'publish_at','expire_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/announcements/count:
* get:
* security:
* - bearerAuth: []
* tags: [Announcements]
* summary: Count all announcements
* description: Count all announcements
* responses:
* 200:
* description: Announcements count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Announcements"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await AnnouncementsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/announcements/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Announcements]
* summary: Find all announcements that match search criteria
* description: Find all announcements that match search criteria
* responses:
* 200:
* description: Announcements list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Announcements"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await AnnouncementsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/announcements/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Announcements]
* 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/Announcements"
* 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 AnnouncementsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,447 @@
const express = require('express');
const Assignment_submissionsService = require('../services/assignment_submissions');
const Assignment_submissionsDBApi = require('../db/api/assignment_submissions');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('assignment_submissions'));
/**
* @swagger
* components:
* schemas:
* Assignment_submissions:
* type: object
* properties:
* answer_text:
* type: string
* default: answer_text
* teacher_feedback:
* type: string
* default: teacher_feedback
* score:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Assignment_submissions
* description: The Assignment_submissions managing API
*/
/**
* @swagger
* /api/assignment_submissions:
* post:
* security:
* - bearerAuth: []
* tags: [Assignment_submissions]
* 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/Assignment_submissions"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Assignment_submissions"
* 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 Assignment_submissionsService.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: [Assignment_submissions]
* 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/Assignment_submissions"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Assignment_submissions"
* 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 Assignment_submissionsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assignment_submissions/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Assignment_submissions]
* 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/Assignment_submissions"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Assignment_submissions"
* 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 Assignment_submissionsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assignment_submissions/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Assignment_submissions]
* 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/Assignment_submissions"
* 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 Assignment_submissionsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assignment_submissions/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Assignment_submissions]
* 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/Assignment_submissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Assignment_submissionsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assignment_submissions:
* get:
* security:
* - bearerAuth: []
* tags: [Assignment_submissions]
* summary: Get all assignment_submissions
* description: Get all assignment_submissions
* responses:
* 200:
* description: Assignment_submissions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Assignment_submissions"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Assignment_submissionsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','answer_text','teacher_feedback',
'score',
'submitted_at','graded_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/assignment_submissions/count:
* get:
* security:
* - bearerAuth: []
* tags: [Assignment_submissions]
* summary: Count all assignment_submissions
* description: Count all assignment_submissions
* responses:
* 200:
* description: Assignment_submissions count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Assignment_submissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Assignment_submissionsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assignment_submissions/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Assignment_submissions]
* summary: Find all assignment_submissions that match search criteria
* description: Find all assignment_submissions that match search criteria
* responses:
* 200:
* description: Assignment_submissions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Assignment_submissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await Assignment_submissionsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/assignment_submissions/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Assignment_submissions]
* 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/Assignment_submissions"
* 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 Assignment_submissionsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,444 @@
const express = require('express');
const AssignmentsService = require('../services/assignments');
const AssignmentsDBApi = require('../db/api/assignments');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('assignments'));
/**
* @swagger
* components:
* schemas:
* Assignments:
* type: object
* properties:
* title:
* type: string
* default: title
* description:
* type: string
* default: description
*
*/
/**
* @swagger
* tags:
* name: Assignments
* description: The Assignments managing API
*/
/**
* @swagger
* /api/assignments:
* post:
* security:
* - bearerAuth: []
* tags: [Assignments]
* 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/Assignments"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Assignments"
* 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 AssignmentsService.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: [Assignments]
* 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/Assignments"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Assignments"
* 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 AssignmentsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assignments/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Assignments]
* 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/Assignments"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Assignments"
* 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 AssignmentsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assignments/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Assignments]
* 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/Assignments"
* 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 AssignmentsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assignments/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Assignments]
* 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/Assignments"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await AssignmentsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assignments:
* get:
* security:
* - bearerAuth: []
* tags: [Assignments]
* summary: Get all assignments
* description: Get all assignments
* responses:
* 200:
* description: Assignments list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Assignments"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await AssignmentsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','title','description',
'assigned_at','due_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/assignments/count:
* get:
* security:
* - bearerAuth: []
* tags: [Assignments]
* summary: Count all assignments
* description: Count all assignments
* responses:
* 200:
* description: Assignments count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Assignments"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await AssignmentsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assignments/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Assignments]
* summary: Find all assignments that match search criteria
* description: Find all assignments that match search criteria
* responses:
* 200:
* description: Assignments list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Assignments"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await AssignmentsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/assignments/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Assignments]
* 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/Assignments"
* 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 AssignmentsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,441 @@
const express = require('express');
const Attendance_recordsService = require('../services/attendance_records');
const Attendance_recordsDBApi = require('../db/api/attendance_records');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('attendance_records'));
/**
* @swagger
* components:
* schemas:
* Attendance_records:
* type: object
* properties:
* remarks:
* type: string
* default: remarks
*
*/
/**
* @swagger
* tags:
* name: Attendance_records
* description: The Attendance_records managing API
*/
/**
* @swagger
* /api/attendance_records:
* post:
* security:
* - bearerAuth: []
* tags: [Attendance_records]
* 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/Attendance_records"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Attendance_records"
* 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 Attendance_recordsService.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: [Attendance_records]
* 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/Attendance_records"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Attendance_records"
* 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 Attendance_recordsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/attendance_records/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Attendance_records]
* 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/Attendance_records"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Attendance_records"
* 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 Attendance_recordsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/attendance_records/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Attendance_records]
* 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/Attendance_records"
* 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 Attendance_recordsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/attendance_records/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Attendance_records]
* 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/Attendance_records"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Attendance_recordsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/attendance_records:
* get:
* security:
* - bearerAuth: []
* tags: [Attendance_records]
* summary: Get all attendance_records
* description: Get all attendance_records
* responses:
* 200:
* description: Attendance_records list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Attendance_records"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Attendance_recordsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','remarks',
'checked_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/attendance_records/count:
* get:
* security:
* - bearerAuth: []
* tags: [Attendance_records]
* summary: Count all attendance_records
* description: Count all attendance_records
* responses:
* 200:
* description: Attendance_records count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Attendance_records"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Attendance_recordsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/attendance_records/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Attendance_records]
* summary: Find all attendance_records that match search criteria
* description: Find all attendance_records that match search criteria
* responses:
* 200:
* description: Attendance_records list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Attendance_records"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await Attendance_recordsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/attendance_records/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Attendance_records]
* 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/Attendance_records"
* 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 Attendance_recordsDBApi.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 Attendance_sessionsService = require('../services/attendance_sessions');
const Attendance_sessionsDBApi = require('../db/api/attendance_sessions');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('attendance_sessions'));
/**
* @swagger
* components:
* schemas:
* Attendance_sessions:
* type: object
* properties:
* notes:
* type: string
* default: notes
*/
/**
* @swagger
* tags:
* name: Attendance_sessions
* description: The Attendance_sessions managing API
*/
/**
* @swagger
* /api/attendance_sessions:
* post:
* security:
* - bearerAuth: []
* tags: [Attendance_sessions]
* 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/Attendance_sessions"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Attendance_sessions"
* 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 Attendance_sessionsService.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: [Attendance_sessions]
* 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/Attendance_sessions"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Attendance_sessions"
* 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 Attendance_sessionsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/attendance_sessions/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Attendance_sessions]
* 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/Attendance_sessions"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Attendance_sessions"
* 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 Attendance_sessionsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/attendance_sessions/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Attendance_sessions]
* 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/Attendance_sessions"
* 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 Attendance_sessionsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/attendance_sessions/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Attendance_sessions]
* 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/Attendance_sessions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Attendance_sessionsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/attendance_sessions:
* get:
* security:
* - bearerAuth: []
* tags: [Attendance_sessions]
* summary: Get all attendance_sessions
* description: Get all attendance_sessions
* responses:
* 200:
* description: Attendance_sessions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Attendance_sessions"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Attendance_sessionsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','notes',
'attendance_date',
];
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/attendance_sessions/count:
* get:
* security:
* - bearerAuth: []
* tags: [Attendance_sessions]
* summary: Count all attendance_sessions
* description: Count all attendance_sessions
* responses:
* 200:
* description: Attendance_sessions count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Attendance_sessions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Attendance_sessionsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/attendance_sessions/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Attendance_sessions]
* summary: Find all attendance_sessions that match search criteria
* description: Find all attendance_sessions that match search criteria
* responses:
* 200:
* description: Attendance_sessions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Attendance_sessions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await Attendance_sessionsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/attendance_sessions/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Attendance_sessions]
* 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/Attendance_sessions"
* 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 Attendance_sessionsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

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

@ -0,0 +1,209 @@
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.body.organizationId,
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

@ -0,0 +1,457 @@
const express = require('express');
const Billing_itemsService = require('../services/billing_items');
const Billing_itemsDBApi = require('../db/api/billing_items');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('billing_items'));
/**
* @swagger
* components:
* schemas:
* Billing_items:
* type: object
* properties:
* bill_number:
* type: string
* default: bill_number
* notes:
* type: string
* default: notes
* period_year:
* type: integer
* format: int64
* period_month:
* type: integer
* format: int64
* amount_total:
* type: integer
* format: int64
* amount_paid:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Billing_items
* description: The Billing_items managing API
*/
/**
* @swagger
* /api/billing_items:
* post:
* security:
* - bearerAuth: []
* tags: [Billing_items]
* 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/Billing_items"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Billing_items"
* 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 Billing_itemsService.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: [Billing_items]
* 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/Billing_items"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Billing_items"
* 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 Billing_itemsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/billing_items/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Billing_items]
* 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/Billing_items"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Billing_items"
* 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 Billing_itemsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/billing_items/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Billing_items]
* 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/Billing_items"
* 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 Billing_itemsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/billing_items/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Billing_items]
* 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/Billing_items"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Billing_itemsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/billing_items:
* get:
* security:
* - bearerAuth: []
* tags: [Billing_items]
* summary: Get all billing_items
* description: Get all billing_items
* responses:
* 200:
* description: Billing_items list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Billing_items"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Billing_itemsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','bill_number','notes',
'period_year','period_month',
'amount_total','amount_paid',
'issued_at','due_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/billing_items/count:
* get:
* security:
* - bearerAuth: []
* tags: [Billing_items]
* summary: Count all billing_items
* description: Count all billing_items
* responses:
* 200:
* description: Billing_items count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Billing_items"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Billing_itemsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/billing_items/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Billing_items]
* summary: Find all billing_items that match search criteria
* description: Find all billing_items that match search criteria
* responses:
* 200:
* description: Billing_items list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Billing_items"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await Billing_itemsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/billing_items/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Billing_items]
* 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/Billing_items"
* 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 Billing_itemsDBApi.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 Class_subjectsService = require('../services/class_subjects');
const Class_subjectsDBApi = require('../db/api/class_subjects');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('class_subjects'));
/**
* @swagger
* components:
* schemas:
* Class_subjects:
* type: object
* properties:
* weekly_sessions:
* type: integer
* format: int64
*/
/**
* @swagger
* tags:
* name: Class_subjects
* description: The Class_subjects managing API
*/
/**
* @swagger
* /api/class_subjects:
* post:
* security:
* - bearerAuth: []
* tags: [Class_subjects]
* 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/Class_subjects"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Class_subjects"
* 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 Class_subjectsService.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: [Class_subjects]
* 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/Class_subjects"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Class_subjects"
* 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 Class_subjectsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/class_subjects/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Class_subjects]
* 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/Class_subjects"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Class_subjects"
* 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 Class_subjectsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/class_subjects/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Class_subjects]
* 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/Class_subjects"
* 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 Class_subjectsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/class_subjects/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Class_subjects]
* 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/Class_subjects"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Class_subjectsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/class_subjects:
* get:
* security:
* - bearerAuth: []
* tags: [Class_subjects]
* summary: Get all class_subjects
* description: Get all class_subjects
* responses:
* 200:
* description: Class_subjects list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Class_subjects"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Class_subjectsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id',
'weekly_sessions',
];
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/class_subjects/count:
* get:
* security:
* - bearerAuth: []
* tags: [Class_subjects]
* summary: Count all class_subjects
* description: Count all class_subjects
* responses:
* 200:
* description: Class_subjects count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Class_subjects"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Class_subjectsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/class_subjects/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Class_subjects]
* summary: Find all class_subjects that match search criteria
* description: Find all class_subjects that match search criteria
* responses:
* 200:
* description: Class_subjects list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Class_subjects"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await Class_subjectsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/class_subjects/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Class_subjects]
* 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/Class_subjects"
* 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 Class_subjectsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,446 @@
const express = require('express');
const ClassesService = require('../services/classes');
const ClassesDBApi = require('../db/api/classes');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('classes'));
/**
* @swagger
* components:
* schemas:
* Classes:
* type: object
* properties:
* name:
* type: string
* default: name
* homeroom_label:
* type: string
* default: homeroom_label
* grade:
* type: integer
* format: int64
*/
/**
* @swagger
* tags:
* name: Classes
* description: The Classes managing API
*/
/**
* @swagger
* /api/classes:
* post:
* security:
* - bearerAuth: []
* tags: [Classes]
* 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/Classes"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Classes"
* 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 ClassesService.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: [Classes]
* 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/Classes"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Classes"
* 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 ClassesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/classes/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Classes]
* 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/Classes"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Classes"
* 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 ClassesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/classes/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Classes]
* 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/Classes"
* 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 ClassesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/classes/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Classes]
* 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/Classes"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await ClassesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/classes:
* get:
* security:
* - bearerAuth: []
* tags: [Classes]
* summary: Get all classes
* description: Get all classes
* responses:
* 200:
* description: Classes list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Classes"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await ClassesDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','homeroom_label',
'grade',
];
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/classes/count:
* get:
* security:
* - bearerAuth: []
* tags: [Classes]
* summary: Count all classes
* description: Count all classes
* responses:
* 200:
* description: Classes count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Classes"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await ClassesDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/classes/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Classes]
* summary: Find all classes that match search criteria
* description: Find all classes that match search criteria
* responses:
* 200:
* description: Classes list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Classes"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await ClassesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/classes/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Classes]
* 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/Classes"
* 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 ClassesDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

View File

@ -0,0 +1,447 @@
const express = require('express');
const Education_levelsService = require('../services/education_levels');
const Education_levelsDBApi = require('../db/api/education_levels');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('education_levels'));
/**
* @swagger
* components:
* schemas:
* Education_levels:
* type: object
* properties:
* name:
* type: string
* default: name
* grade_start:
* type: integer
* format: int64
* grade_end:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Education_levels
* description: The Education_levels managing API
*/
/**
* @swagger
* /api/education_levels:
* post:
* security:
* - bearerAuth: []
* tags: [Education_levels]
* 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/Education_levels"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Education_levels"
* 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 Education_levelsService.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: [Education_levels]
* 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/Education_levels"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Education_levels"
* 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 Education_levelsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/education_levels/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Education_levels]
* 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/Education_levels"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Education_levels"
* 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 Education_levelsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/education_levels/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Education_levels]
* 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/Education_levels"
* 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 Education_levelsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/education_levels/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Education_levels]
* 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/Education_levels"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Education_levelsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/education_levels:
* get:
* security:
* - bearerAuth: []
* tags: [Education_levels]
* summary: Get all education_levels
* description: Get all education_levels
* responses:
* 200:
* description: Education_levels list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Education_levels"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Education_levelsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name',
'grade_start','grade_end',
];
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/education_levels/count:
* get:
* security:
* - bearerAuth: []
* tags: [Education_levels]
* summary: Count all education_levels
* description: Count all education_levels
* responses:
* 200:
* description: Education_levels count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Education_levels"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Education_levelsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/education_levels/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Education_levels]
* summary: Find all education_levels that match search criteria
* description: Find all education_levels that match search criteria
* responses:
* 200:
* description: Education_levels list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Education_levels"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await Education_levelsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/education_levels/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Education_levels]
* 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/Education_levels"
* 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 Education_levelsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,443 @@
const express = require('express');
const Exam_answersService = require('../services/exam_answers');
const Exam_answersDBApi = require('../db/api/exam_answers');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('exam_answers'));
/**
* @swagger
* components:
* schemas:
* Exam_answers:
* type: object
* properties:
* answer_text:
* type: string
* default: answer_text
* score:
* type: integer
* format: int64
*/
/**
* @swagger
* tags:
* name: Exam_answers
* description: The Exam_answers managing API
*/
/**
* @swagger
* /api/exam_answers:
* post:
* security:
* - bearerAuth: []
* tags: [Exam_answers]
* 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/Exam_answers"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Exam_answers"
* 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 Exam_answersService.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: [Exam_answers]
* 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/Exam_answers"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Exam_answers"
* 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 Exam_answersService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/exam_answers/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Exam_answers]
* 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/Exam_answers"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Exam_answers"
* 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 Exam_answersService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/exam_answers/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Exam_answers]
* 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/Exam_answers"
* 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 Exam_answersService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/exam_answers/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Exam_answers]
* 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/Exam_answers"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Exam_answersService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/exam_answers:
* get:
* security:
* - bearerAuth: []
* tags: [Exam_answers]
* summary: Get all exam_answers
* description: Get all exam_answers
* responses:
* 200:
* description: Exam_answers list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Exam_answers"
* 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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Exam_answersDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','answer_text',
'score',
'graded_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/exam_answers/count:
* get:
* security:
* - bearerAuth: []
* tags: [Exam_answers]
* summary: Count all exam_answers
* description: Count all exam_answers
* responses:
* 200:
* description: Exam_answers count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Exam_answers"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Exam_answersDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/exam_answers/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Exam_answers]
* summary: Find all exam_answers that match search criteria
* description: Find all exam_answers that match search criteria
* responses:
* 200:
* description: Exam_answers list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Exam_answers"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await Exam_answersDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/exam_answers/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Exam_answers]
* 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/Exam_answers"
* 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 Exam_answersDBApi.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