Initial version

This commit is contained in:
Flatlogic Bot 2026-02-24 13:48:31 +00:00
commit 13c343270d
599 changed files with 166845 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>Relentless Generation Camp App</h2>
<p>Church summer camp app for registration, payments, schedules, rosters, and field trip management.</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 @@
# Relentless Generation Camp App
## 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_38737
DB_USER=app_38737
DB_PASS=276e8af3-04b9-4ac0-8e13-5539221080b6
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 @@
#Relentless Generation Camp App - 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_relentless_generation_camp_app;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_relentless_generation_camp_app 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": "relentlessgenerationcampapp",
"description": "Relentless Generation Camp App - template backend",
"scripts": {
"start": "npm run db:migrate && npm run db:seed && npm run watch",
"lint": "eslint . --ext .js",
"db:migrate": "sequelize-cli db:migrate",
"db:seed": "sequelize-cli db:seed:all",
"db:drop": "sequelize-cli db:drop",
"db:create": "sequelize-cli db:create",
"watch": "node watcher.js"
},
"dependencies": {
"@google-cloud/storage": "^5.18.2",
"axios": "^1.6.7",
"bcrypt": "5.1.1",
"chokidar": "^4.0.3",
"cors": "2.8.5",
"csv-parser": "^3.0.0",
"express": "4.18.2",
"formidable": "1.2.2",
"helmet": "4.1.1",
"json2csv": "^5.0.7",
"jsonwebtoken": "8.5.1",
"lodash": "4.17.21",
"moment": "2.30.1",
"multer": "^1.4.4",
"mysql2": "2.2.5",
"nodemailer": "6.9.9",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
"passport-jwt": "^4.0.1",
"passport-microsoft": "^0.1.0",
"pg": "8.4.1",
"pg-hstore": "2.3.4",
"sequelize": "6.35.2",
"sequelize-json-schema": "^2.1.1",
"sqlite": "4.0.15",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0",
"tedious": "^18.2.4"
},
"engines": {
"node": ">=18"
},
"private": true,
"devDependencies": {
"cross-env": "7.0.3",
"eslint": "^8.23.1",
"eslint-plugin-import": "^2.29.1",
"mocha": "8.1.3",
"node-mocks-http": "1.9.0",
"nodemon": "2.0.5",
"sequelize-cli": "6.6.2"
}
}

View File

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

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

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

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

@ -0,0 +1,79 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "276e8af3",
user_pass: "5539221080b6",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '276e8af3-04b9-4ac0-8e13-5539221080b6',
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: 'Relentless Generation Camp App <app@flatlogic.app>',
host: 'email-smtp.us-east-1.amazonaws.com',
port: 587,
auth: {
user: process.env.EMAIL_USER || '',
pass: process.env.EMAIL_PASS,
},
tls: {
rejectUnauthorized: false
}
},
roles: {
admin: 'Administrator',
user: 'Parent Guardian',
},
project_uuid: '276e8af3-04b9-4ac0-8e13-5539221080b6',
flHost: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'dev_stage' ? 'https://flatlogic.com/projects' : 'http://localhost:3000/projects',
gpt_key: process.env.GPT_KEY || '',
};
config.pexelsKey = process.env.PEXELS_KEY || '';
config.pexelsQuery = 'Sunrise over winding forest trail';
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,581 @@
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 Activity_blocksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const activity_blocks = await db.activity_blocks.create(
{
id: data.id || undefined,
name: data.name
||
null
,
program_shift: data.program_shift
||
null
,
block_start_datetime: data.block_start_datetime
||
null
,
block_end_datetime: data.block_end_datetime
||
null
,
block_type: data.block_type
||
null
,
details: data.details
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await activity_blocks.setAge_group( data.age_group || null, {
transaction,
});
await activity_blocks.setCamp_session( data.camp_session || null, {
transaction,
});
return activity_blocks;
}
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 activity_blocksData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
program_shift: item.program_shift
||
null
,
block_start_datetime: item.block_start_datetime
||
null
,
block_end_datetime: item.block_end_datetime
||
null
,
block_type: item.block_type
||
null
,
details: item.details
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const activity_blocks = await db.activity_blocks.bulkCreate(activity_blocksData, { transaction });
// For each item created, replace relation files
return activity_blocks;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const activity_blocks = await db.activity_blocks.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.program_shift !== undefined) updatePayload.program_shift = data.program_shift;
if (data.block_start_datetime !== undefined) updatePayload.block_start_datetime = data.block_start_datetime;
if (data.block_end_datetime !== undefined) updatePayload.block_end_datetime = data.block_end_datetime;
if (data.block_type !== undefined) updatePayload.block_type = data.block_type;
if (data.details !== undefined) updatePayload.details = data.details;
updatePayload.updatedById = currentUser.id;
await activity_blocks.update(updatePayload, {transaction});
if (data.age_group !== undefined) {
await activity_blocks.setAge_group(
data.age_group,
{ transaction }
);
}
if (data.camp_session !== undefined) {
await activity_blocks.setCamp_session(
data.camp_session,
{ transaction }
);
}
return activity_blocks;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const activity_blocks = await db.activity_blocks.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of activity_blocks) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of activity_blocks) {
await record.destroy({transaction});
}
});
return activity_blocks;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const activity_blocks = await db.activity_blocks.findByPk(id, options);
await activity_blocks.update({
deletedBy: currentUser.id
}, {
transaction,
});
await activity_blocks.destroy({
transaction
});
return activity_blocks;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const activity_blocks = await db.activity_blocks.findOne(
{ where },
{ transaction },
);
if (!activity_blocks) {
return activity_blocks;
}
const output = activity_blocks.get({plain: true});
output.age_group = await activity_blocks.getAge_group({
transaction
});
output.camp_session = await activity_blocks.getCamp_session({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.age_groups,
as: 'age_group',
where: filter.age_group ? {
[Op.or]: [
{ id: { [Op.in]: filter.age_group.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.age_group.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.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(
'activity_blocks',
'name',
filter.name,
),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'activity_blocks',
'details',
filter.details,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
block_start_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
block_end_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.block_start_datetimeRange) {
const [start, end] = filter.block_start_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
block_start_datetime: {
...where.block_start_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
block_start_datetime: {
...where.block_start_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.block_end_datetimeRange) {
const [start, end] = filter.block_end_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
block_end_datetime: {
...where.block_end_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
block_end_datetime: {
...where.block_end_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.program_shift) {
where = {
...where,
program_shift: filter.program_shift,
};
}
if (filter.block_type) {
where = {
...where,
block_type: filter.block_type,
};
}
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.activity_blocks.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(
'activity_blocks',
'name',
query,
),
],
};
}
const records = await db.activity_blocks.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,513 @@
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 Age_groupsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const age_groups = await db.age_groups.create(
{
id: data.id || undefined,
name: data.name
||
null
,
min_grade: data.min_grade
||
null
,
max_grade: data.max_grade
||
null
,
theme_scripture_reference: data.theme_scripture_reference
||
null
,
theme_scripture_text: data.theme_scripture_text
||
null
,
focus_summary: data.focus_summary
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return age_groups;
}
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 age_groupsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
min_grade: item.min_grade
||
null
,
max_grade: item.max_grade
||
null
,
theme_scripture_reference: item.theme_scripture_reference
||
null
,
theme_scripture_text: item.theme_scripture_text
||
null
,
focus_summary: item.focus_summary
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const age_groups = await db.age_groups.bulkCreate(age_groupsData, { transaction });
// For each item created, replace relation files
return age_groups;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const age_groups = await db.age_groups.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.min_grade !== undefined) updatePayload.min_grade = data.min_grade;
if (data.max_grade !== undefined) updatePayload.max_grade = data.max_grade;
if (data.theme_scripture_reference !== undefined) updatePayload.theme_scripture_reference = data.theme_scripture_reference;
if (data.theme_scripture_text !== undefined) updatePayload.theme_scripture_text = data.theme_scripture_text;
if (data.focus_summary !== undefined) updatePayload.focus_summary = data.focus_summary;
updatePayload.updatedById = currentUser.id;
await age_groups.update(updatePayload, {transaction});
return age_groups;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const age_groups = await db.age_groups.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of age_groups) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of age_groups) {
await record.destroy({transaction});
}
});
return age_groups;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const age_groups = await db.age_groups.findByPk(id, options);
await age_groups.update({
deletedBy: currentUser.id
}, {
transaction,
});
await age_groups.destroy({
transaction
});
return age_groups;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const age_groups = await db.age_groups.findOne(
{ where },
{ transaction },
);
if (!age_groups) {
return age_groups;
}
const output = age_groups.get({plain: true});
output.enrollments_age_group = await age_groups.getEnrollments_age_group({
transaction
});
output.field_trip_events_age_group = await age_groups.getField_trip_events_age_group({
transaction
});
output.activity_blocks_age_group = await age_groups.getActivity_blocks_age_group({
transaction
});
output.staff_assignments_age_group = await age_groups.getStaff_assignments_age_group({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'age_groups',
'name',
filter.name,
),
};
}
if (filter.theme_scripture_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'age_groups',
'theme_scripture_reference',
filter.theme_scripture_reference,
),
};
}
if (filter.theme_scripture_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'age_groups',
'theme_scripture_text',
filter.theme_scripture_text,
),
};
}
if (filter.focus_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'age_groups',
'focus_summary',
filter.focus_summary,
),
};
}
if (filter.min_gradeRange) {
const [start, end] = filter.min_gradeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_grade: {
...where.min_grade,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_grade: {
...where.min_grade,
[Op.lte]: end,
},
};
}
}
if (filter.max_gradeRange) {
const [start, end] = filter.max_gradeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_grade: {
...where.max_grade,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_grade: {
...where.max_grade,
[Op.lte]: end,
},
};
}
}
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.age_groups.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(
'age_groups',
'name',
query,
),
],
};
}
const records = await db.age_groups.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,546 @@
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
,
message: data.message
||
null
,
audience: data.audience
||
null
,
publish_datetime: data.publish_datetime
||
null
,
expire_datetime: data.expire_datetime
||
null
,
is_published: data.is_published
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await announcements.setCamp_session( data.camp_session || null, {
transaction,
});
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
,
message: item.message
||
null
,
audience: item.audience
||
null
,
publish_datetime: item.publish_datetime
||
null
,
expire_datetime: item.expire_datetime
||
null
,
is_published: item.is_published
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const announcements = await db.announcements.bulkCreate(announcementsData, { transaction });
// For each item created, replace relation files
return announcements;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const announcements = await db.announcements.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.message !== undefined) updatePayload.message = data.message;
if (data.audience !== undefined) updatePayload.audience = data.audience;
if (data.publish_datetime !== undefined) updatePayload.publish_datetime = data.publish_datetime;
if (data.expire_datetime !== undefined) updatePayload.expire_datetime = data.expire_datetime;
if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
updatePayload.updatedById = currentUser.id;
await announcements.update(updatePayload, {transaction});
if (data.camp_session !== undefined) {
await announcements.setCamp_session(
data.camp_session,
{ transaction }
);
}
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.camp_session = await announcements.getCamp_session({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.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(
'announcements',
'title',
filter.title,
),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'announcements',
'message',
filter.message,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
publish_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
expire_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.publish_datetimeRange) {
const [start, end] = filter.publish_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
publish_datetime: {
...where.publish_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
publish_datetime: {
...where.publish_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.expire_datetimeRange) {
const [start, end] = filter.expire_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expire_datetime: {
...where.expire_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expire_datetime: {
...where.expire_datetime,
[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.is_published) {
where = {
...where,
is_published: filter.is_published,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, ) {
let where = {};
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,690 @@
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 Camp_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const camp_sessions = await db.camp_sessions.create(
{
id: data.id || undefined,
name: data.name
||
null
,
theme_title: data.theme_title
||
null
,
theme_summary: data.theme_summary
||
null
,
theme_scripture_reference: data.theme_scripture_reference
||
null
,
theme_scripture_text: data.theme_scripture_text
||
null
,
start_datetime: data.start_datetime
||
null
,
end_datetime: data.end_datetime
||
null
,
day_camp_hours: data.day_camp_hours
||
null
,
third_shift_hours: data.third_shift_hours
||
null
,
is_published: data.is_published
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await camp_sessions.setCampus( data.campus || null, {
transaction,
});
return camp_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 camp_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
theme_title: item.theme_title
||
null
,
theme_summary: item.theme_summary
||
null
,
theme_scripture_reference: item.theme_scripture_reference
||
null
,
theme_scripture_text: item.theme_scripture_text
||
null
,
start_datetime: item.start_datetime
||
null
,
end_datetime: item.end_datetime
||
null
,
day_camp_hours: item.day_camp_hours
||
null
,
third_shift_hours: item.third_shift_hours
||
null
,
is_published: item.is_published
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const camp_sessions = await db.camp_sessions.bulkCreate(camp_sessionsData, { transaction });
// For each item created, replace relation files
return camp_sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const camp_sessions = await db.camp_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.theme_title !== undefined) updatePayload.theme_title = data.theme_title;
if (data.theme_summary !== undefined) updatePayload.theme_summary = data.theme_summary;
if (data.theme_scripture_reference !== undefined) updatePayload.theme_scripture_reference = data.theme_scripture_reference;
if (data.theme_scripture_text !== undefined) updatePayload.theme_scripture_text = data.theme_scripture_text;
if (data.start_datetime !== undefined) updatePayload.start_datetime = data.start_datetime;
if (data.end_datetime !== undefined) updatePayload.end_datetime = data.end_datetime;
if (data.day_camp_hours !== undefined) updatePayload.day_camp_hours = data.day_camp_hours;
if (data.third_shift_hours !== undefined) updatePayload.third_shift_hours = data.third_shift_hours;
if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
updatePayload.updatedById = currentUser.id;
await camp_sessions.update(updatePayload, {transaction});
if (data.campus !== undefined) {
await camp_sessions.setCampus(
data.campus,
{ transaction }
);
}
return camp_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const camp_sessions = await db.camp_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of camp_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of camp_sessions) {
await record.destroy({transaction});
}
});
return camp_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const camp_sessions = await db.camp_sessions.findByPk(id, options);
await camp_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await camp_sessions.destroy({
transaction
});
return camp_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const camp_sessions = await db.camp_sessions.findOne(
{ where },
{ transaction },
);
if (!camp_sessions) {
return camp_sessions;
}
const output = camp_sessions.get({plain: true});
output.weekly_themes_camp_session = await camp_sessions.getWeekly_themes_camp_session({
transaction
});
output.pricing_plans_camp_session = await camp_sessions.getPricing_plans_camp_session({
transaction
});
output.fee_rules_camp_session = await camp_sessions.getFee_rules_camp_session({
transaction
});
output.enrollments_camp_session = await camp_sessions.getEnrollments_camp_session({
transaction
});
output.waiver_documents_camp_session = await camp_sessions.getWaiver_documents_camp_session({
transaction
});
output.field_trip_events_camp_session = await camp_sessions.getField_trip_events_camp_session({
transaction
});
output.special_trips_camp_session = await camp_sessions.getSpecial_trips_camp_session({
transaction
});
output.end_of_summer_trip_options_camp_session = await camp_sessions.getEnd_of_summer_trip_options_camp_session({
transaction
});
output.activity_blocks_camp_session = await camp_sessions.getActivity_blocks_camp_session({
transaction
});
output.staff_assignments_camp_session = await camp_sessions.getStaff_assignments_camp_session({
transaction
});
output.announcements_camp_session = await camp_sessions.getAnnouncements_camp_session({
transaction
});
output.campus = await camp_sessions.getCampus({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.campuses,
as: 'campus',
where: filter.campus ? {
[Op.or]: [
{ id: { [Op.in]: filter.campus.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.campus.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(
'camp_sessions',
'name',
filter.name,
),
};
}
if (filter.theme_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'camp_sessions',
'theme_title',
filter.theme_title,
),
};
}
if (filter.theme_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'camp_sessions',
'theme_summary',
filter.theme_summary,
),
};
}
if (filter.theme_scripture_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'camp_sessions',
'theme_scripture_reference',
filter.theme_scripture_reference,
),
};
}
if (filter.theme_scripture_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'camp_sessions',
'theme_scripture_text',
filter.theme_scripture_text,
),
};
}
if (filter.day_camp_hours) {
where = {
...where,
[Op.and]: Utils.ilike(
'camp_sessions',
'day_camp_hours',
filter.day_camp_hours,
),
};
}
if (filter.third_shift_hours) {
where = {
...where,
[Op.and]: Utils.ilike(
'camp_sessions',
'third_shift_hours',
filter.third_shift_hours,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_datetimeRange) {
const [start, end] = filter.start_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_datetime: {
...where.start_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_datetime: {
...where.start_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.end_datetimeRange) {
const [start, end] = filter.end_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_datetime: {
...where.end_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_datetime: {
...where.end_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_published) {
where = {
...where,
is_published: filter.is_published,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.camp_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'camp_sessions',
'name',
query,
),
],
};
}
const records = await db.camp_sessions.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,624 @@
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 CampersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const campers = await db.campers.create(
{
id: data.id || undefined,
first_name: data.first_name
||
null
,
last_name: data.last_name
||
null
,
date_of_birth: data.date_of_birth
||
null
,
grade_level: data.grade_level
||
null
,
gender: data.gender
||
null
,
allergies: data.allergies
||
null
,
medical_notes: data.medical_notes
||
null
,
special_needs_notes: data.special_needs_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await campers.setPrimary_guardian( data.primary_guardian || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.campers.getTableName(),
belongsToColumn: 'profile_photo',
belongsToId: campers.id,
},
data.profile_photo,
options,
);
return campers;
}
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 campersData = data.map((item, index) => ({
id: item.id || undefined,
first_name: item.first_name
||
null
,
last_name: item.last_name
||
null
,
date_of_birth: item.date_of_birth
||
null
,
grade_level: item.grade_level
||
null
,
gender: item.gender
||
null
,
allergies: item.allergies
||
null
,
medical_notes: item.medical_notes
||
null
,
special_needs_notes: item.special_needs_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const campers = await db.campers.bulkCreate(campersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < campers.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.campers.getTableName(),
belongsToColumn: 'profile_photo',
belongsToId: campers[i].id,
},
data[i].profile_photo,
options,
);
}
return campers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const campers = await db.campers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.first_name !== undefined) updatePayload.first_name = data.first_name;
if (data.last_name !== undefined) updatePayload.last_name = data.last_name;
if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
if (data.grade_level !== undefined) updatePayload.grade_level = data.grade_level;
if (data.gender !== undefined) updatePayload.gender = data.gender;
if (data.allergies !== undefined) updatePayload.allergies = data.allergies;
if (data.medical_notes !== undefined) updatePayload.medical_notes = data.medical_notes;
if (data.special_needs_notes !== undefined) updatePayload.special_needs_notes = data.special_needs_notes;
updatePayload.updatedById = currentUser.id;
await campers.update(updatePayload, {transaction});
if (data.primary_guardian !== undefined) {
await campers.setPrimary_guardian(
data.primary_guardian,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.campers.getTableName(),
belongsToColumn: 'profile_photo',
belongsToId: campers.id,
},
data.profile_photo,
options,
);
return campers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const campers = await db.campers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of campers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of campers) {
await record.destroy({transaction});
}
});
return campers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const campers = await db.campers.findByPk(id, options);
await campers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await campers.destroy({
transaction
});
return campers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const campers = await db.campers.findOne(
{ where },
{ transaction },
);
if (!campers) {
return campers;
}
const output = campers.get({plain: true});
output.enrollments_camper = await campers.getEnrollments_camper({
transaction
});
output.primary_guardian = await campers.getPrimary_guardian({
transaction
});
output.profile_photo = await campers.getProfile_photo({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.guardians,
as: 'primary_guardian',
where: filter.primary_guardian ? {
[Op.or]: [
{ id: { [Op.in]: filter.primary_guardian.split('|').map(term => Utils.uuid(term)) } },
{
primary_phone: {
[Op.or]: filter.primary_guardian.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'profile_photo',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.first_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'campers',
'first_name',
filter.first_name,
),
};
}
if (filter.last_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'campers',
'last_name',
filter.last_name,
),
};
}
if (filter.allergies) {
where = {
...where,
[Op.and]: Utils.ilike(
'campers',
'allergies',
filter.allergies,
),
};
}
if (filter.medical_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'campers',
'medical_notes',
filter.medical_notes,
),
};
}
if (filter.special_needs_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'campers',
'special_needs_notes',
filter.special_needs_notes,
),
};
}
if (filter.date_of_birthRange) {
const [start, end] = filter.date_of_birthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.lte]: end,
},
};
}
}
if (filter.grade_levelRange) {
const [start, end] = filter.grade_levelRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
grade_level: {
...where.grade_level,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
grade_level: {
...where.grade_level,
[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.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.campers.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(
'campers',
'first_name',
query,
),
],
};
}
const records = await db.campers.findAll({
attributes: [ 'id', 'first_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['first_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.first_name,
}));
}
};

View File

@ -0,0 +1,451 @@
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 CampusesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const campuses = await db.campuses.create(
{
id: data.id || undefined,
name: data.name
||
null
,
address_line1: data.address_line1
||
null
,
city: data.city
||
null
,
state: data.state
||
null
,
postal_code: data.postal_code
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return campuses;
}
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 campusesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
address_line1: item.address_line1
||
null
,
city: item.city
||
null
,
state: item.state
||
null
,
postal_code: item.postal_code
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const campuses = await db.campuses.bulkCreate(campusesData, { transaction });
// For each item created, replace relation files
return campuses;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const campuses = await db.campuses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state !== undefined) updatePayload.state = data.state;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
updatePayload.updatedById = currentUser.id;
await campuses.update(updatePayload, {transaction});
return campuses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const campuses = await db.campuses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of campuses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of campuses) {
await record.destroy({transaction});
}
});
return campuses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const campuses = await db.campuses.findByPk(id, options);
await campuses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await campuses.destroy({
transaction
});
return campuses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const campuses = await db.campuses.findOne(
{ where },
{ transaction },
);
if (!campuses) {
return campuses;
}
const output = campuses.get({plain: true});
output.camp_sessions_campus = await campuses.getCamp_sessions_campus({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'campuses',
'name',
filter.name,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'campuses',
'address_line1',
filter.address_line1,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'campuses',
'city',
filter.city,
),
};
}
if (filter.state) {
where = {
...where,
[Op.and]: Utils.ilike(
'campuses',
'state',
filter.state,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'campuses',
'postal_code',
filter.postal_code,
),
};
}
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.campuses.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(
'campuses',
'name',
query,
),
],
};
}
const records = await db.campuses.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,421 @@
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 Curriculum_subjectsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const curriculum_subjects = await db.curriculum_subjects.create(
{
id: data.id || undefined,
name: data.name
||
null
,
subject_type: data.subject_type
||
null
,
description: data.description
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return curriculum_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 curriculum_subjectsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
subject_type: item.subject_type
||
null
,
description: item.description
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const curriculum_subjects = await db.curriculum_subjects.bulkCreate(curriculum_subjectsData, { transaction });
// For each item created, replace relation files
return curriculum_subjects;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const curriculum_subjects = await db.curriculum_subjects.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.subject_type !== undefined) updatePayload.subject_type = data.subject_type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await curriculum_subjects.update(updatePayload, {transaction});
return curriculum_subjects;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const curriculum_subjects = await db.curriculum_subjects.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of curriculum_subjects) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of curriculum_subjects) {
await record.destroy({transaction});
}
});
return curriculum_subjects;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const curriculum_subjects = await db.curriculum_subjects.findByPk(id, options);
await curriculum_subjects.update({
deletedBy: currentUser.id
}, {
transaction,
});
await curriculum_subjects.destroy({
transaction
});
return curriculum_subjects;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const curriculum_subjects = await db.curriculum_subjects.findOne(
{ where },
{ transaction },
);
if (!curriculum_subjects) {
return curriculum_subjects;
}
const output = curriculum_subjects.get({plain: true});
output.staff_assignments_subject = await curriculum_subjects.getStaff_assignments_subject({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'curriculum_subjects',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'curriculum_subjects',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.subject_type) {
where = {
...where,
subject_type: filter.subject_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.curriculum_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'curriculum_subjects',
'name',
query,
),
],
};
}
const records = await db.curriculum_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,519 @@
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 Document_signaturesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_signatures = await db.document_signatures.create(
{
id: data.id || undefined,
status: data.status
||
null
,
signed_datetime: data.signed_datetime
||
null
,
signature_name: data.signature_name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await document_signatures.setWaiver_document( data.waiver_document || null, {
transaction,
});
await document_signatures.setEnrollment( data.enrollment || null, {
transaction,
});
await document_signatures.setGuardian( data.guardian || null, {
transaction,
});
return document_signatures;
}
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 document_signaturesData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
signed_datetime: item.signed_datetime
||
null
,
signature_name: item.signature_name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const document_signatures = await db.document_signatures.bulkCreate(document_signaturesData, { transaction });
// For each item created, replace relation files
return document_signatures;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_signatures = await db.document_signatures.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.signed_datetime !== undefined) updatePayload.signed_datetime = data.signed_datetime;
if (data.signature_name !== undefined) updatePayload.signature_name = data.signature_name;
updatePayload.updatedById = currentUser.id;
await document_signatures.update(updatePayload, {transaction});
if (data.waiver_document !== undefined) {
await document_signatures.setWaiver_document(
data.waiver_document,
{ transaction }
);
}
if (data.enrollment !== undefined) {
await document_signatures.setEnrollment(
data.enrollment,
{ transaction }
);
}
if (data.guardian !== undefined) {
await document_signatures.setGuardian(
data.guardian,
{ transaction }
);
}
return document_signatures;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_signatures = await db.document_signatures.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of document_signatures) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of document_signatures) {
await record.destroy({transaction});
}
});
return document_signatures;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_signatures = await db.document_signatures.findByPk(id, options);
await document_signatures.update({
deletedBy: currentUser.id
}, {
transaction,
});
await document_signatures.destroy({
transaction
});
return document_signatures;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const document_signatures = await db.document_signatures.findOne(
{ where },
{ transaction },
);
if (!document_signatures) {
return document_signatures;
}
const output = document_signatures.get({plain: true});
output.waiver_document = await document_signatures.getWaiver_document({
transaction
});
output.enrollment = await document_signatures.getEnrollment({
transaction
});
output.guardian = await document_signatures.getGuardian({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.waiver_documents,
as: 'waiver_document',
where: filter.waiver_document ? {
[Op.or]: [
{ id: { [Op.in]: filter.waiver_document.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.waiver_document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.enrollments,
as: 'enrollment',
where: filter.enrollment ? {
[Op.or]: [
{ id: { [Op.in]: filter.enrollment.split('|').map(term => Utils.uuid(term)) } },
{
notes: {
[Op.or]: filter.enrollment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.guardians,
as: 'guardian',
where: filter.guardian ? {
[Op.or]: [
{ id: { [Op.in]: filter.guardian.split('|').map(term => Utils.uuid(term)) } },
{
primary_phone: {
[Op.or]: filter.guardian.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.signature_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_signatures',
'signature_name',
filter.signature_name,
),
};
}
if (filter.signed_datetimeRange) {
const [start, end] = filter.signed_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
signed_datetime: {
...where.signed_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
signed_datetime: {
...where.signed_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.document_signatures.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(
'document_signatures',
'signature_name',
query,
),
],
};
}
const records = await db.document_signatures.findAll({
attributes: [ 'id', 'signature_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['signature_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.signature_name,
}));
}
};

View File

@ -0,0 +1,495 @@
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 End_of_summer_trip_optionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const end_of_summer_trip_options = await db.end_of_summer_trip_options.create(
{
id: data.id || undefined,
name: data.name
||
null
,
option_type: data.option_type
||
null
,
destination: data.destination
||
null
,
estimated_price: data.estimated_price
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await end_of_summer_trip_options.setCamp_session( data.camp_session || null, {
transaction,
});
return end_of_summer_trip_options;
}
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 end_of_summer_trip_optionsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
option_type: item.option_type
||
null
,
destination: item.destination
||
null
,
estimated_price: item.estimated_price
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const end_of_summer_trip_options = await db.end_of_summer_trip_options.bulkCreate(end_of_summer_trip_optionsData, { transaction });
// For each item created, replace relation files
return end_of_summer_trip_options;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const end_of_summer_trip_options = await db.end_of_summer_trip_options.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.option_type !== undefined) updatePayload.option_type = data.option_type;
if (data.destination !== undefined) updatePayload.destination = data.destination;
if (data.estimated_price !== undefined) updatePayload.estimated_price = data.estimated_price;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await end_of_summer_trip_options.update(updatePayload, {transaction});
if (data.camp_session !== undefined) {
await end_of_summer_trip_options.setCamp_session(
data.camp_session,
{ transaction }
);
}
return end_of_summer_trip_options;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const end_of_summer_trip_options = await db.end_of_summer_trip_options.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of end_of_summer_trip_options) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of end_of_summer_trip_options) {
await record.destroy({transaction});
}
});
return end_of_summer_trip_options;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const end_of_summer_trip_options = await db.end_of_summer_trip_options.findByPk(id, options);
await end_of_summer_trip_options.update({
deletedBy: currentUser.id
}, {
transaction,
});
await end_of_summer_trip_options.destroy({
transaction
});
return end_of_summer_trip_options;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const end_of_summer_trip_options = await db.end_of_summer_trip_options.findOne(
{ where },
{ transaction },
);
if (!end_of_summer_trip_options) {
return end_of_summer_trip_options;
}
const output = end_of_summer_trip_options.get({plain: true});
output.end_of_summer_trip_selections_trip_option = await end_of_summer_trip_options.getEnd_of_summer_trip_selections_trip_option({
transaction
});
output.camp_session = await end_of_summer_trip_options.getCamp_session({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.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(
'end_of_summer_trip_options',
'name',
filter.name,
),
};
}
if (filter.destination) {
where = {
...where,
[Op.and]: Utils.ilike(
'end_of_summer_trip_options',
'destination',
filter.destination,
),
};
}
if (filter.estimated_priceRange) {
const [start, end] = filter.estimated_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_price: {
...where.estimated_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_price: {
...where.estimated_price,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.option_type) {
where = {
...where,
option_type: filter.option_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.end_of_summer_trip_options.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(
'end_of_summer_trip_options',
'name',
query,
),
],
};
}
const records = await db.end_of_summer_trip_options.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,458 @@
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 End_of_summer_trip_selectionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const end_of_summer_trip_selections = await db.end_of_summer_trip_selections.create(
{
id: data.id || undefined,
status: data.status
||
null
,
selected_datetime: data.selected_datetime
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await end_of_summer_trip_selections.setEnrollment( data.enrollment || null, {
transaction,
});
await end_of_summer_trip_selections.setTrip_option( data.trip_option || null, {
transaction,
});
return end_of_summer_trip_selections;
}
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 end_of_summer_trip_selectionsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
selected_datetime: item.selected_datetime
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const end_of_summer_trip_selections = await db.end_of_summer_trip_selections.bulkCreate(end_of_summer_trip_selectionsData, { transaction });
// For each item created, replace relation files
return end_of_summer_trip_selections;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const end_of_summer_trip_selections = await db.end_of_summer_trip_selections.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.selected_datetime !== undefined) updatePayload.selected_datetime = data.selected_datetime;
updatePayload.updatedById = currentUser.id;
await end_of_summer_trip_selections.update(updatePayload, {transaction});
if (data.enrollment !== undefined) {
await end_of_summer_trip_selections.setEnrollment(
data.enrollment,
{ transaction }
);
}
if (data.trip_option !== undefined) {
await end_of_summer_trip_selections.setTrip_option(
data.trip_option,
{ transaction }
);
}
return end_of_summer_trip_selections;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const end_of_summer_trip_selections = await db.end_of_summer_trip_selections.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of end_of_summer_trip_selections) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of end_of_summer_trip_selections) {
await record.destroy({transaction});
}
});
return end_of_summer_trip_selections;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const end_of_summer_trip_selections = await db.end_of_summer_trip_selections.findByPk(id, options);
await end_of_summer_trip_selections.update({
deletedBy: currentUser.id
}, {
transaction,
});
await end_of_summer_trip_selections.destroy({
transaction
});
return end_of_summer_trip_selections;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const end_of_summer_trip_selections = await db.end_of_summer_trip_selections.findOne(
{ where },
{ transaction },
);
if (!end_of_summer_trip_selections) {
return end_of_summer_trip_selections;
}
const output = end_of_summer_trip_selections.get({plain: true});
output.enrollment = await end_of_summer_trip_selections.getEnrollment({
transaction
});
output.trip_option = await end_of_summer_trip_selections.getTrip_option({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.enrollments,
as: 'enrollment',
where: filter.enrollment ? {
[Op.or]: [
{ id: { [Op.in]: filter.enrollment.split('|').map(term => Utils.uuid(term)) } },
{
notes: {
[Op.or]: filter.enrollment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.end_of_summer_trip_options,
as: 'trip_option',
where: filter.trip_option ? {
[Op.or]: [
{ id: { [Op.in]: filter.trip_option.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.trip_option.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.selected_datetimeRange) {
const [start, end] = filter.selected_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
selected_datetime: {
...where.selected_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
selected_datetime: {
...where.selected_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.end_of_summer_trip_selections.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(
'end_of_summer_trip_selections',
'status',
query,
),
],
};
}
const records = await db.end_of_summer_trip_selections.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,594 @@
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 EnrollmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const enrollments = await db.enrollments.create(
{
id: data.id || undefined,
submitted_datetime: data.submitted_datetime
||
null
,
status: data.status
||
null
,
application_fee_waived: data.application_fee_waived
||
false
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await enrollments.setCamper( data.camper || null, {
transaction,
});
await enrollments.setCamp_session( data.camp_session || null, {
transaction,
});
await enrollments.setPricing_plan( data.pricing_plan || null, {
transaction,
});
await enrollments.setAge_group( data.age_group || null, {
transaction,
});
return enrollments;
}
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 enrollmentsData = data.map((item, index) => ({
id: item.id || undefined,
submitted_datetime: item.submitted_datetime
||
null
,
status: item.status
||
null
,
application_fee_waived: item.application_fee_waived
||
false
,
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 enrollments = await db.enrollments.bulkCreate(enrollmentsData, { transaction });
// For each item created, replace relation files
return enrollments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const enrollments = await db.enrollments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.submitted_datetime !== undefined) updatePayload.submitted_datetime = data.submitted_datetime;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.application_fee_waived !== undefined) updatePayload.application_fee_waived = data.application_fee_waived;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await enrollments.update(updatePayload, {transaction});
if (data.camper !== undefined) {
await enrollments.setCamper(
data.camper,
{ transaction }
);
}
if (data.camp_session !== undefined) {
await enrollments.setCamp_session(
data.camp_session,
{ transaction }
);
}
if (data.pricing_plan !== undefined) {
await enrollments.setPricing_plan(
data.pricing_plan,
{ transaction }
);
}
if (data.age_group !== undefined) {
await enrollments.setAge_group(
data.age_group,
{ transaction }
);
}
return enrollments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const enrollments = await db.enrollments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of enrollments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of enrollments) {
await record.destroy({transaction});
}
});
return enrollments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const enrollments = await db.enrollments.findByPk(id, options);
await enrollments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await enrollments.destroy({
transaction
});
return enrollments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const enrollments = await db.enrollments.findOne(
{ where },
{ transaction },
);
if (!enrollments) {
return enrollments;
}
const output = enrollments.get({plain: true});
output.payments_enrollment = await enrollments.getPayments_enrollment({
transaction
});
output.document_signatures_enrollment = await enrollments.getDocument_signatures_enrollment({
transaction
});
output.trip_registrations_enrollment = await enrollments.getTrip_registrations_enrollment({
transaction
});
output.end_of_summer_trip_selections_enrollment = await enrollments.getEnd_of_summer_trip_selections_enrollment({
transaction
});
output.camper = await enrollments.getCamper({
transaction
});
output.camp_session = await enrollments.getCamp_session({
transaction
});
output.pricing_plan = await enrollments.getPricing_plan({
transaction
});
output.age_group = await enrollments.getAge_group({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.campers,
as: 'camper',
where: filter.camper ? {
[Op.or]: [
{ id: { [Op.in]: filter.camper.split('|').map(term => Utils.uuid(term)) } },
{
first_name: {
[Op.or]: filter.camper.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.pricing_plans,
as: 'pricing_plan',
where: filter.pricing_plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.pricing_plan.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.pricing_plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.age_groups,
as: 'age_group',
where: filter.age_group ? {
[Op.or]: [
{ id: { [Op.in]: filter.age_group.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.age_group.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'enrollments',
'notes',
filter.notes,
),
};
}
if (filter.submitted_datetimeRange) {
const [start, end] = filter.submitted_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submitted_datetime: {
...where.submitted_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submitted_datetime: {
...where.submitted_datetime,
[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.application_fee_waived) {
where = {
...where,
application_fee_waived: filter.application_fee_waived,
};
}
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.enrollments.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(
'enrollments',
'notes',
query,
),
],
};
}
const records = await db.enrollments.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,504 @@
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_rulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const fee_rules = await db.fee_rules.create(
{
id: data.id || undefined,
name: data.name
||
null
,
fee_kind: data.fee_kind
||
null
,
amount: data.amount
||
null
,
waiver_first_n: data.waiver_first_n
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await fee_rules.setCamp_session( data.camp_session || null, {
transaction,
});
return fee_rules;
}
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_rulesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
fee_kind: item.fee_kind
||
null
,
amount: item.amount
||
null
,
waiver_first_n: item.waiver_first_n
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const fee_rules = await db.fee_rules.bulkCreate(fee_rulesData, { transaction });
// For each item created, replace relation files
return fee_rules;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const fee_rules = await db.fee_rules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.fee_kind !== undefined) updatePayload.fee_kind = data.fee_kind;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.waiver_first_n !== undefined) updatePayload.waiver_first_n = data.waiver_first_n;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await fee_rules.update(updatePayload, {transaction});
if (data.camp_session !== undefined) {
await fee_rules.setCamp_session(
data.camp_session,
{ transaction }
);
}
return fee_rules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const fee_rules = await db.fee_rules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of fee_rules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of fee_rules) {
await record.destroy({transaction});
}
});
return fee_rules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const fee_rules = await db.fee_rules.findByPk(id, options);
await fee_rules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await fee_rules.destroy({
transaction
});
return fee_rules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const fee_rules = await db.fee_rules.findOne(
{ where },
{ transaction },
);
if (!fee_rules) {
return fee_rules;
}
const output = fee_rules.get({plain: true});
output.camp_session = await fee_rules.getCamp_session({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.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_rules',
'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.waiver_first_nRange) {
const [start, end] = filter.waiver_first_nRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
waiver_first_n: {
...where.waiver_first_n,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
waiver_first_n: {
...where.waiver_first_n,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.fee_kind) {
where = {
...where,
fee_kind: filter.fee_kind,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.fee_rules.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(
'fee_rules',
'name',
query,
),
],
};
}
const records = await db.fee_rules.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,543 @@
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 Field_trip_catalogDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const field_trip_catalog = await db.field_trip_catalog.create(
{
id: data.id || undefined,
name: data.name
||
null
,
category: data.category
||
null
,
location_name: data.location_name
||
null
,
grade_range: data.grade_range
||
null
,
typical_min_rate: data.typical_min_rate
||
null
,
typical_max_rate: data.typical_max_rate
||
null
,
separate_payment_required: data.separate_payment_required
||
false
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return field_trip_catalog;
}
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 field_trip_catalogData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
category: item.category
||
null
,
location_name: item.location_name
||
null
,
grade_range: item.grade_range
||
null
,
typical_min_rate: item.typical_min_rate
||
null
,
typical_max_rate: item.typical_max_rate
||
null
,
separate_payment_required: item.separate_payment_required
||
false
,
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 field_trip_catalog = await db.field_trip_catalog.bulkCreate(field_trip_catalogData, { transaction });
// For each item created, replace relation files
return field_trip_catalog;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const field_trip_catalog = await db.field_trip_catalog.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.location_name !== undefined) updatePayload.location_name = data.location_name;
if (data.grade_range !== undefined) updatePayload.grade_range = data.grade_range;
if (data.typical_min_rate !== undefined) updatePayload.typical_min_rate = data.typical_min_rate;
if (data.typical_max_rate !== undefined) updatePayload.typical_max_rate = data.typical_max_rate;
if (data.separate_payment_required !== undefined) updatePayload.separate_payment_required = data.separate_payment_required;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await field_trip_catalog.update(updatePayload, {transaction});
return field_trip_catalog;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const field_trip_catalog = await db.field_trip_catalog.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of field_trip_catalog) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of field_trip_catalog) {
await record.destroy({transaction});
}
});
return field_trip_catalog;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const field_trip_catalog = await db.field_trip_catalog.findByPk(id, options);
await field_trip_catalog.update({
deletedBy: currentUser.id
}, {
transaction,
});
await field_trip_catalog.destroy({
transaction
});
return field_trip_catalog;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const field_trip_catalog = await db.field_trip_catalog.findOne(
{ where },
{ transaction },
);
if (!field_trip_catalog) {
return field_trip_catalog;
}
const output = field_trip_catalog.get({plain: true});
output.field_trip_events_field_trip = await field_trip_catalog.getField_trip_events_field_trip({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'field_trip_catalog',
'name',
filter.name,
),
};
}
if (filter.location_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'field_trip_catalog',
'location_name',
filter.location_name,
),
};
}
if (filter.grade_range) {
where = {
...where,
[Op.and]: Utils.ilike(
'field_trip_catalog',
'grade_range',
filter.grade_range,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'field_trip_catalog',
'notes',
filter.notes,
),
};
}
if (filter.typical_min_rateRange) {
const [start, end] = filter.typical_min_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
typical_min_rate: {
...where.typical_min_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
typical_min_rate: {
...where.typical_min_rate,
[Op.lte]: end,
},
};
}
}
if (filter.typical_max_rateRange) {
const [start, end] = filter.typical_max_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
typical_max_rate: {
...where.typical_max_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
typical_max_rate: {
...where.typical_max_rate,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.separate_payment_required) {
where = {
...where,
separate_payment_required: filter.separate_payment_required,
};
}
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.field_trip_catalog.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(
'field_trip_catalog',
'name',
query,
),
],
};
}
const records = await db.field_trip_catalog.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,628 @@
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 Field_trip_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const field_trip_events = await db.field_trip_events.create(
{
id: data.id || undefined,
depart_datetime: data.depart_datetime
||
null
,
return_datetime: data.return_datetime
||
null
,
price_per_student: data.price_per_student
||
null
,
capacity: data.capacity
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await field_trip_events.setCamp_session( data.camp_session || null, {
transaction,
});
await field_trip_events.setField_trip( data.field_trip || null, {
transaction,
});
await field_trip_events.setAge_group( data.age_group || null, {
transaction,
});
return field_trip_events;
}
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 field_trip_eventsData = data.map((item, index) => ({
id: item.id || undefined,
depart_datetime: item.depart_datetime
||
null
,
return_datetime: item.return_datetime
||
null
,
price_per_student: item.price_per_student
||
null
,
capacity: item.capacity
||
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 field_trip_events = await db.field_trip_events.bulkCreate(field_trip_eventsData, { transaction });
// For each item created, replace relation files
return field_trip_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const field_trip_events = await db.field_trip_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.depart_datetime !== undefined) updatePayload.depart_datetime = data.depart_datetime;
if (data.return_datetime !== undefined) updatePayload.return_datetime = data.return_datetime;
if (data.price_per_student !== undefined) updatePayload.price_per_student = data.price_per_student;
if (data.capacity !== undefined) updatePayload.capacity = data.capacity;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await field_trip_events.update(updatePayload, {transaction});
if (data.camp_session !== undefined) {
await field_trip_events.setCamp_session(
data.camp_session,
{ transaction }
);
}
if (data.field_trip !== undefined) {
await field_trip_events.setField_trip(
data.field_trip,
{ transaction }
);
}
if (data.age_group !== undefined) {
await field_trip_events.setAge_group(
data.age_group,
{ transaction }
);
}
return field_trip_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const field_trip_events = await db.field_trip_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of field_trip_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of field_trip_events) {
await record.destroy({transaction});
}
});
return field_trip_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const field_trip_events = await db.field_trip_events.findByPk(id, options);
await field_trip_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await field_trip_events.destroy({
transaction
});
return field_trip_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const field_trip_events = await db.field_trip_events.findOne(
{ where },
{ transaction },
);
if (!field_trip_events) {
return field_trip_events;
}
const output = field_trip_events.get({plain: true});
output.trip_registrations_field_trip_event = await field_trip_events.getTrip_registrations_field_trip_event({
transaction
});
output.camp_session = await field_trip_events.getCamp_session({
transaction
});
output.field_trip = await field_trip_events.getField_trip({
transaction
});
output.age_group = await field_trip_events.getAge_group({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.field_trip_catalog,
as: 'field_trip',
where: filter.field_trip ? {
[Op.or]: [
{ id: { [Op.in]: filter.field_trip.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.field_trip.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.age_groups,
as: 'age_group',
where: filter.age_group ? {
[Op.or]: [
{ id: { [Op.in]: filter.age_group.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.age_group.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
depart_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
return_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.depart_datetimeRange) {
const [start, end] = filter.depart_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
depart_datetime: {
...where.depart_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
depart_datetime: {
...where.depart_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.return_datetimeRange) {
const [start, end] = filter.return_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
return_datetime: {
...where.return_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
return_datetime: {
...where.return_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.price_per_studentRange) {
const [start, end] = filter.price_per_studentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_per_student: {
...where.price_per_student,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_per_student: {
...where.price_per_student,
[Op.lte]: end,
},
};
}
}
if (filter.capacityRange) {
const [start, end] = filter.capacityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
capacity: {
...where.capacity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
capacity: {
...where.capacity,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.field_trip_events.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(
'field_trip_events',
'status',
query,
),
],
};
}
const records = await db.field_trip_events.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,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,564 @@
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 GuardiansDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const guardians = await db.guardians.create(
{
id: data.id || undefined,
primary_phone: data.primary_phone
||
null
,
secondary_phone: data.secondary_phone
||
null
,
address_line1: data.address_line1
||
null
,
city: data.city
||
null
,
state: data.state
||
null
,
postal_code: data.postal_code
||
null
,
emergency_contact_name: data.emergency_contact_name
||
null
,
emergency_contact_phone: data.emergency_contact_phone
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await guardians.setUser( data.user || null, {
transaction,
});
return guardians;
}
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 guardiansData = data.map((item, index) => ({
id: item.id || undefined,
primary_phone: item.primary_phone
||
null
,
secondary_phone: item.secondary_phone
||
null
,
address_line1: item.address_line1
||
null
,
city: item.city
||
null
,
state: item.state
||
null
,
postal_code: item.postal_code
||
null
,
emergency_contact_name: item.emergency_contact_name
||
null
,
emergency_contact_phone: item.emergency_contact_phone
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const guardians = await db.guardians.bulkCreate(guardiansData, { transaction });
// For each item created, replace relation files
return guardians;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const guardians = await db.guardians.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.primary_phone !== undefined) updatePayload.primary_phone = data.primary_phone;
if (data.secondary_phone !== undefined) updatePayload.secondary_phone = data.secondary_phone;
if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state !== undefined) updatePayload.state = data.state;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
if (data.emergency_contact_name !== undefined) updatePayload.emergency_contact_name = data.emergency_contact_name;
if (data.emergency_contact_phone !== undefined) updatePayload.emergency_contact_phone = data.emergency_contact_phone;
updatePayload.updatedById = currentUser.id;
await guardians.update(updatePayload, {transaction});
if (data.user !== undefined) {
await guardians.setUser(
data.user,
{ transaction }
);
}
return guardians;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const guardians = await db.guardians.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of guardians) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of guardians) {
await record.destroy({transaction});
}
});
return guardians;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const guardians = await db.guardians.findByPk(id, options);
await guardians.update({
deletedBy: currentUser.id
}, {
transaction,
});
await guardians.destroy({
transaction
});
return guardians;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const guardians = await db.guardians.findOne(
{ where },
{ transaction },
);
if (!guardians) {
return guardians;
}
const output = guardians.get({plain: true});
output.campers_primary_guardian = await guardians.getCampers_primary_guardian({
transaction
});
output.document_signatures_guardian = await guardians.getDocument_signatures_guardian({
transaction
});
output.user = await guardians.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.primary_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'guardians',
'primary_phone',
filter.primary_phone,
),
};
}
if (filter.secondary_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'guardians',
'secondary_phone',
filter.secondary_phone,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'guardians',
'address_line1',
filter.address_line1,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'guardians',
'city',
filter.city,
),
};
}
if (filter.state) {
where = {
...where,
[Op.and]: Utils.ilike(
'guardians',
'state',
filter.state,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'guardians',
'postal_code',
filter.postal_code,
),
};
}
if (filter.emergency_contact_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'guardians',
'emergency_contact_name',
filter.emergency_contact_name,
),
};
}
if (filter.emergency_contact_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'guardians',
'emergency_contact_phone',
filter.emergency_contact_phone,
),
};
}
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.guardians.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(
'guardians',
'primary_phone',
query,
),
],
};
}
const records = await db.guardians.findAll({
attributes: [ 'id', 'primary_phone' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['primary_phone', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.primary_phone,
}));
}
};

View File

@ -0,0 +1,559 @@
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,
payment_kind: data.payment_kind
||
null
,
amount: data.amount
||
null
,
status: data.status
||
null
,
method: data.method
||
null
,
reference_code: data.reference_code
||
null
,
due_datetime: data.due_datetime
||
null
,
paid_datetime: data.paid_datetime
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payments.setEnrollment( data.enrollment || null, {
transaction,
});
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,
payment_kind: item.payment_kind
||
null
,
amount: item.amount
||
null
,
status: item.status
||
null
,
method: item.method
||
null
,
reference_code: item.reference_code
||
null
,
due_datetime: item.due_datetime
||
null
,
paid_datetime: item.paid_datetime
||
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
return payments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.payment_kind !== undefined) updatePayload.payment_kind = data.payment_kind;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.method !== undefined) updatePayload.method = data.method;
if (data.reference_code !== undefined) updatePayload.reference_code = data.reference_code;
if (data.due_datetime !== undefined) updatePayload.due_datetime = data.due_datetime;
if (data.paid_datetime !== undefined) updatePayload.paid_datetime = data.paid_datetime;
updatePayload.updatedById = currentUser.id;
await payments.update(updatePayload, {transaction});
if (data.enrollment !== undefined) {
await payments.setEnrollment(
data.enrollment,
{ transaction }
);
}
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.enrollment = await payments.getEnrollment({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.enrollments,
as: 'enrollment',
where: filter.enrollment ? {
[Op.or]: [
{ id: { [Op.in]: filter.enrollment.split('|').map(term => Utils.uuid(term)) } },
{
notes: {
[Op.or]: filter.enrollment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reference_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'reference_code',
filter.reference_code,
),
};
}
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.due_datetimeRange) {
const [start, end] = filter.due_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
due_datetime: {
...where.due_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
due_datetime: {
...where.due_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.paid_datetimeRange) {
const [start, end] = filter.paid_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
paid_datetime: {
...where.paid_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
paid_datetime: {
...where.paid_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.payment_kind) {
where = {
...where,
payment_kind: filter.payment_kind,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.method) {
where = {
...where,
method: filter.method,
};
}
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.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'payments',
'reference_code',
query,
),
],
};
}
const records = await db.payments.findAll({
attributes: [ 'id', 'reference_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reference_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reference_code,
}));
}
};

View File

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

View File

@ -0,0 +1,583 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Pricing_plansDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const pricing_plans = await db.pricing_plans.create(
{
id: data.id || undefined,
name: data.name
||
null
,
plan_type: data.plan_type
||
null
,
monthly_tuition: data.monthly_tuition
||
null
,
included_summary: data.included_summary
||
null
,
includes_dinner: data.includes_dinner
||
false
,
includes_pickup: data.includes_pickup
||
false
,
includes_dropoff: data.includes_dropoff
||
false
,
includes_third_shift: data.includes_third_shift
||
false
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await pricing_plans.setCamp_session( data.camp_session || null, {
transaction,
});
return pricing_plans;
}
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 pricing_plansData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
plan_type: item.plan_type
||
null
,
monthly_tuition: item.monthly_tuition
||
null
,
included_summary: item.included_summary
||
null
,
includes_dinner: item.includes_dinner
||
false
,
includes_pickup: item.includes_pickup
||
false
,
includes_dropoff: item.includes_dropoff
||
false
,
includes_third_shift: item.includes_third_shift
||
false
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const pricing_plans = await db.pricing_plans.bulkCreate(pricing_plansData, { transaction });
// For each item created, replace relation files
return pricing_plans;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const pricing_plans = await db.pricing_plans.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.plan_type !== undefined) updatePayload.plan_type = data.plan_type;
if (data.monthly_tuition !== undefined) updatePayload.monthly_tuition = data.monthly_tuition;
if (data.included_summary !== undefined) updatePayload.included_summary = data.included_summary;
if (data.includes_dinner !== undefined) updatePayload.includes_dinner = data.includes_dinner;
if (data.includes_pickup !== undefined) updatePayload.includes_pickup = data.includes_pickup;
if (data.includes_dropoff !== undefined) updatePayload.includes_dropoff = data.includes_dropoff;
if (data.includes_third_shift !== undefined) updatePayload.includes_third_shift = data.includes_third_shift;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await pricing_plans.update(updatePayload, {transaction});
if (data.camp_session !== undefined) {
await pricing_plans.setCamp_session(
data.camp_session,
{ transaction }
);
}
return pricing_plans;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const pricing_plans = await db.pricing_plans.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of pricing_plans) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of pricing_plans) {
await record.destroy({transaction});
}
});
return pricing_plans;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const pricing_plans = await db.pricing_plans.findByPk(id, options);
await pricing_plans.update({
deletedBy: currentUser.id
}, {
transaction,
});
await pricing_plans.destroy({
transaction
});
return pricing_plans;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const pricing_plans = await db.pricing_plans.findOne(
{ where },
{ transaction },
);
if (!pricing_plans) {
return pricing_plans;
}
const output = pricing_plans.get({plain: true});
output.enrollments_pricing_plan = await pricing_plans.getEnrollments_pricing_plan({
transaction
});
output.camp_session = await pricing_plans.getCamp_session({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.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(
'pricing_plans',
'name',
filter.name,
),
};
}
if (filter.included_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'pricing_plans',
'included_summary',
filter.included_summary,
),
};
}
if (filter.monthly_tuitionRange) {
const [start, end] = filter.monthly_tuitionRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
monthly_tuition: {
...where.monthly_tuition,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
monthly_tuition: {
...where.monthly_tuition,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.plan_type) {
where = {
...where,
plan_type: filter.plan_type,
};
}
if (filter.includes_dinner) {
where = {
...where,
includes_dinner: filter.includes_dinner,
};
}
if (filter.includes_pickup) {
where = {
...where,
includes_pickup: filter.includes_pickup,
};
}
if (filter.includes_dropoff) {
where = {
...where,
includes_dropoff: filter.includes_dropoff,
};
}
if (filter.includes_third_shift) {
where = {
...where,
includes_third_shift: filter.includes_third_shift,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.pricing_plans.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(
'pricing_plans',
'name',
query,
),
],
};
}
const records = await db.pricing_plans.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,
}));
}
};

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

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

View File

@ -0,0 +1,570 @@
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 Special_tripsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const special_trips = await db.special_trips.create(
{
id: data.id || undefined,
name: data.name
||
null
,
trip_type: data.trip_type
||
null
,
destination: data.destination
||
null
,
start_datetime: data.start_datetime
||
null
,
end_datetime: data.end_datetime
||
null
,
package_notes: data.package_notes
||
null
,
separate_payment_required: data.separate_payment_required
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await special_trips.setCamp_session( data.camp_session || null, {
transaction,
});
return special_trips;
}
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 special_tripsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
trip_type: item.trip_type
||
null
,
destination: item.destination
||
null
,
start_datetime: item.start_datetime
||
null
,
end_datetime: item.end_datetime
||
null
,
package_notes: item.package_notes
||
null
,
separate_payment_required: item.separate_payment_required
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const special_trips = await db.special_trips.bulkCreate(special_tripsData, { transaction });
// For each item created, replace relation files
return special_trips;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const special_trips = await db.special_trips.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.trip_type !== undefined) updatePayload.trip_type = data.trip_type;
if (data.destination !== undefined) updatePayload.destination = data.destination;
if (data.start_datetime !== undefined) updatePayload.start_datetime = data.start_datetime;
if (data.end_datetime !== undefined) updatePayload.end_datetime = data.end_datetime;
if (data.package_notes !== undefined) updatePayload.package_notes = data.package_notes;
if (data.separate_payment_required !== undefined) updatePayload.separate_payment_required = data.separate_payment_required;
updatePayload.updatedById = currentUser.id;
await special_trips.update(updatePayload, {transaction});
if (data.camp_session !== undefined) {
await special_trips.setCamp_session(
data.camp_session,
{ transaction }
);
}
return special_trips;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const special_trips = await db.special_trips.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of special_trips) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of special_trips) {
await record.destroy({transaction});
}
});
return special_trips;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const special_trips = await db.special_trips.findByPk(id, options);
await special_trips.update({
deletedBy: currentUser.id
}, {
transaction,
});
await special_trips.destroy({
transaction
});
return special_trips;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const special_trips = await db.special_trips.findOne(
{ where },
{ transaction },
);
if (!special_trips) {
return special_trips;
}
const output = special_trips.get({plain: true});
output.camp_session = await special_trips.getCamp_session({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.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(
'special_trips',
'name',
filter.name,
),
};
}
if (filter.destination) {
where = {
...where,
[Op.and]: Utils.ilike(
'special_trips',
'destination',
filter.destination,
),
};
}
if (filter.package_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'special_trips',
'package_notes',
filter.package_notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_datetimeRange) {
const [start, end] = filter.start_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_datetime: {
...where.start_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_datetime: {
...where.start_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.end_datetimeRange) {
const [start, end] = filter.end_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_datetime: {
...where.end_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_datetime: {
...where.end_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.trip_type) {
where = {
...where,
trip_type: filter.trip_type,
};
}
if (filter.separate_payment_required) {
where = {
...where,
separate_payment_required: filter.separate_payment_required,
};
}
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.special_trips.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(
'special_trips',
'name',
query,
),
],
};
}
const records = await db.special_trips.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,519 @@
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 Staff_assignmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const staff_assignments = await db.staff_assignments.create(
{
id: data.id || undefined,
assignment_role: data.assignment_role
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await staff_assignments.setStaff_user( data.staff_user || null, {
transaction,
});
await staff_assignments.setCamp_session( data.camp_session || null, {
transaction,
});
await staff_assignments.setAge_group( data.age_group || null, {
transaction,
});
await staff_assignments.setSubject( data.subject || null, {
transaction,
});
return staff_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 staff_assignmentsData = data.map((item, index) => ({
id: item.id || undefined,
assignment_role: item.assignment_role
||
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 staff_assignments = await db.staff_assignments.bulkCreate(staff_assignmentsData, { transaction });
// For each item created, replace relation files
return staff_assignments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const staff_assignments = await db.staff_assignments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.assignment_role !== undefined) updatePayload.assignment_role = data.assignment_role;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await staff_assignments.update(updatePayload, {transaction});
if (data.staff_user !== undefined) {
await staff_assignments.setStaff_user(
data.staff_user,
{ transaction }
);
}
if (data.camp_session !== undefined) {
await staff_assignments.setCamp_session(
data.camp_session,
{ transaction }
);
}
if (data.age_group !== undefined) {
await staff_assignments.setAge_group(
data.age_group,
{ transaction }
);
}
if (data.subject !== undefined) {
await staff_assignments.setSubject(
data.subject,
{ transaction }
);
}
return staff_assignments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const staff_assignments = await db.staff_assignments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of staff_assignments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of staff_assignments) {
await record.destroy({transaction});
}
});
return staff_assignments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const staff_assignments = await db.staff_assignments.findByPk(id, options);
await staff_assignments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await staff_assignments.destroy({
transaction
});
return staff_assignments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const staff_assignments = await db.staff_assignments.findOne(
{ where },
{ transaction },
);
if (!staff_assignments) {
return staff_assignments;
}
const output = staff_assignments.get({plain: true});
output.staff_user = await staff_assignments.getStaff_user({
transaction
});
output.camp_session = await staff_assignments.getCamp_session({
transaction
});
output.age_group = await staff_assignments.getAge_group({
transaction
});
output.subject = await staff_assignments.getSubject({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'staff_user',
where: filter.staff_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.staff_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.staff_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.age_groups,
as: 'age_group',
where: filter.age_group ? {
[Op.or]: [
{ id: { [Op.in]: filter.age_group.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.age_group.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.curriculum_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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'staff_assignments',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.assignment_role) {
where = {
...where,
assignment_role: filter.assignment_role,
};
}
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.staff_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'staff_assignments',
'notes',
query,
),
],
};
}
const records = await db.staff_assignments.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,480 @@
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 Trip_registrationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trip_registrations = await db.trip_registrations.create(
{
id: data.id || undefined,
status: data.status
||
null
,
permission_granted: data.permission_granted
||
false
,
registered_datetime: data.registered_datetime
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await trip_registrations.setField_trip_event( data.field_trip_event || null, {
transaction,
});
await trip_registrations.setEnrollment( data.enrollment || null, {
transaction,
});
return trip_registrations;
}
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 trip_registrationsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
permission_granted: item.permission_granted
||
false
,
registered_datetime: item.registered_datetime
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const trip_registrations = await db.trip_registrations.bulkCreate(trip_registrationsData, { transaction });
// For each item created, replace relation files
return trip_registrations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const trip_registrations = await db.trip_registrations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.permission_granted !== undefined) updatePayload.permission_granted = data.permission_granted;
if (data.registered_datetime !== undefined) updatePayload.registered_datetime = data.registered_datetime;
updatePayload.updatedById = currentUser.id;
await trip_registrations.update(updatePayload, {transaction});
if (data.field_trip_event !== undefined) {
await trip_registrations.setField_trip_event(
data.field_trip_event,
{ transaction }
);
}
if (data.enrollment !== undefined) {
await trip_registrations.setEnrollment(
data.enrollment,
{ transaction }
);
}
return trip_registrations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trip_registrations = await db.trip_registrations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of trip_registrations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of trip_registrations) {
await record.destroy({transaction});
}
});
return trip_registrations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const trip_registrations = await db.trip_registrations.findByPk(id, options);
await trip_registrations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await trip_registrations.destroy({
transaction
});
return trip_registrations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const trip_registrations = await db.trip_registrations.findOne(
{ where },
{ transaction },
);
if (!trip_registrations) {
return trip_registrations;
}
const output = trip_registrations.get({plain: true});
output.field_trip_event = await trip_registrations.getField_trip_event({
transaction
});
output.enrollment = await trip_registrations.getEnrollment({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.field_trip_events,
as: 'field_trip_event',
where: filter.field_trip_event ? {
[Op.or]: [
{ id: { [Op.in]: filter.field_trip_event.split('|').map(term => Utils.uuid(term)) } },
{
status: {
[Op.or]: filter.field_trip_event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.enrollments,
as: 'enrollment',
where: filter.enrollment ? {
[Op.or]: [
{ id: { [Op.in]: filter.enrollment.split('|').map(term => Utils.uuid(term)) } },
{
notes: {
[Op.or]: filter.enrollment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.registered_datetimeRange) {
const [start, end] = filter.registered_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
registered_datetime: {
...where.registered_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
registered_datetime: {
...where.registered_datetime,
[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.permission_granted) {
where = {
...where,
permission_granted: filter.permission_granted,
};
}
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.trip_registrations.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(
'trip_registrations',
'status',
query,
),
],
};
}
const records = await db.trip_registrations.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,
}));
}
};

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

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

View File

@ -0,0 +1,476 @@
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 Waiver_documentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const waiver_documents = await db.waiver_documents.create(
{
id: data.id || undefined,
title: data.title
||
null
,
document_type: data.document_type
||
null
,
is_required: data.is_required
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await waiver_documents.setCamp_session( data.camp_session || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.waiver_documents.getTableName(),
belongsToColumn: 'document_file',
belongsToId: waiver_documents.id,
},
data.document_file,
options,
);
return waiver_documents;
}
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 waiver_documentsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
document_type: item.document_type
||
null
,
is_required: item.is_required
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const waiver_documents = await db.waiver_documents.bulkCreate(waiver_documentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < waiver_documents.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.waiver_documents.getTableName(),
belongsToColumn: 'document_file',
belongsToId: waiver_documents[i].id,
},
data[i].document_file,
options,
);
}
return waiver_documents;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const waiver_documents = await db.waiver_documents.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
updatePayload.updatedById = currentUser.id;
await waiver_documents.update(updatePayload, {transaction});
if (data.camp_session !== undefined) {
await waiver_documents.setCamp_session(
data.camp_session,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.waiver_documents.getTableName(),
belongsToColumn: 'document_file',
belongsToId: waiver_documents.id,
},
data.document_file,
options,
);
return waiver_documents;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const waiver_documents = await db.waiver_documents.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of waiver_documents) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of waiver_documents) {
await record.destroy({transaction});
}
});
return waiver_documents;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const waiver_documents = await db.waiver_documents.findByPk(id, options);
await waiver_documents.update({
deletedBy: currentUser.id
}, {
transaction,
});
await waiver_documents.destroy({
transaction
});
return waiver_documents;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const waiver_documents = await db.waiver_documents.findOne(
{ where },
{ transaction },
);
if (!waiver_documents) {
return waiver_documents;
}
const output = waiver_documents.get({plain: true});
output.document_signatures_waiver_document = await waiver_documents.getDocument_signatures_waiver_document({
transaction
});
output.document_file = await waiver_documents.getDocument_file({
transaction
});
output.camp_session = await waiver_documents.getCamp_session({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'document_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'waiver_documents',
'title',
filter.title,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.document_type) {
where = {
...where,
document_type: filter.document_type,
};
}
if (filter.is_required) {
where = {
...where,
is_required: filter.is_required,
};
}
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.waiver_documents.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(
'waiver_documents',
'title',
query,
),
],
};
}
const records = await db.waiver_documents.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,541 @@
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 Weekly_themesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const weekly_themes = await db.weekly_themes.create(
{
id: data.id || undefined,
week_number: data.week_number
||
null
,
title: data.title
||
null
,
tagline: data.tagline
||
null
,
start_datetime: data.start_datetime
||
null
,
end_datetime: data.end_datetime
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await weekly_themes.setCamp_session( data.camp_session || null, {
transaction,
});
return weekly_themes;
}
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 weekly_themesData = data.map((item, index) => ({
id: item.id || undefined,
week_number: item.week_number
||
null
,
title: item.title
||
null
,
tagline: item.tagline
||
null
,
start_datetime: item.start_datetime
||
null
,
end_datetime: item.end_datetime
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const weekly_themes = await db.weekly_themes.bulkCreate(weekly_themesData, { transaction });
// For each item created, replace relation files
return weekly_themes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const weekly_themes = await db.weekly_themes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.week_number !== undefined) updatePayload.week_number = data.week_number;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.tagline !== undefined) updatePayload.tagline = data.tagline;
if (data.start_datetime !== undefined) updatePayload.start_datetime = data.start_datetime;
if (data.end_datetime !== undefined) updatePayload.end_datetime = data.end_datetime;
updatePayload.updatedById = currentUser.id;
await weekly_themes.update(updatePayload, {transaction});
if (data.camp_session !== undefined) {
await weekly_themes.setCamp_session(
data.camp_session,
{ transaction }
);
}
return weekly_themes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const weekly_themes = await db.weekly_themes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of weekly_themes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of weekly_themes) {
await record.destroy({transaction});
}
});
return weekly_themes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const weekly_themes = await db.weekly_themes.findByPk(id, options);
await weekly_themes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await weekly_themes.destroy({
transaction
});
return weekly_themes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const weekly_themes = await db.weekly_themes.findOne(
{ where },
{ transaction },
);
if (!weekly_themes) {
return weekly_themes;
}
const output = weekly_themes.get({plain: true});
output.camp_session = await weekly_themes.getCamp_session({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.camp_sessions,
as: 'camp_session',
where: filter.camp_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.camp_session.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.camp_session.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(
'weekly_themes',
'title',
filter.title,
),
};
}
if (filter.tagline) {
where = {
...where,
[Op.and]: Utils.ilike(
'weekly_themes',
'tagline',
filter.tagline,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_datetime: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.week_numberRange) {
const [start, end] = filter.week_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
week_number: {
...where.week_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
week_number: {
...where.week_number,
[Op.lte]: end,
},
};
}
}
if (filter.start_datetimeRange) {
const [start, end] = filter.start_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_datetime: {
...where.start_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_datetime: {
...where.start_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.end_datetimeRange) {
const [start, end] = filter.end_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_datetime: {
...where.end_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_datetime: {
...where.end_datetime,
[Op.lte]: end,
},
};
}
}
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.weekly_themes.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(
'weekly_themes',
'title',
query,
),
],
};
}
const records = await db.weekly_themes.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,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_relentless_generation_camp_app',
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,180 @@
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 activity_blocks = sequelize.define(
'activity_blocks',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
program_shift: {
type: DataTypes.ENUM,
values: [
"day_camp",
"third_shift"
],
},
block_start_datetime: {
type: DataTypes.DATE,
},
block_end_datetime: {
type: DataTypes.DATE,
},
block_type: {
type: DataTypes.ENUM,
values: [
"meal",
"devotion",
"academics",
"arts_skills_rotation",
"recreation",
"bible_study",
"leadership_lab",
"quiet_time",
"pickup_dropoff"
],
},
details: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
activity_blocks.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.activity_blocks.belongsTo(db.age_groups, {
as: 'age_group',
foreignKey: {
name: 'age_groupId',
},
constraints: false,
});
db.activity_blocks.belongsTo(db.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.activity_blocks.belongsTo(db.users, {
as: 'createdBy',
});
db.activity_blocks.belongsTo(db.users, {
as: 'updatedBy',
});
};
return activity_blocks;
};

View File

@ -0,0 +1,157 @@
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 age_groups = sequelize.define(
'age_groups',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
min_grade: {
type: DataTypes.INTEGER,
},
max_grade: {
type: DataTypes.INTEGER,
},
theme_scripture_reference: {
type: DataTypes.TEXT,
},
theme_scripture_text: {
type: DataTypes.TEXT,
},
focus_summary: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
age_groups.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.age_groups.hasMany(db.enrollments, {
as: 'enrollments_age_group',
foreignKey: {
name: 'age_groupId',
},
constraints: false,
});
db.age_groups.hasMany(db.field_trip_events, {
as: 'field_trip_events_age_group',
foreignKey: {
name: 'age_groupId',
},
constraints: false,
});
db.age_groups.hasMany(db.activity_blocks, {
as: 'activity_blocks_age_group',
foreignKey: {
name: 'age_groupId',
},
constraints: false,
});
db.age_groups.hasMany(db.staff_assignments, {
as: 'staff_assignments_age_group',
foreignKey: {
name: 'age_groupId',
},
constraints: false,
});
//end loop
db.age_groups.belongsTo(db.users, {
as: 'createdBy',
});
db.age_groups.belongsTo(db.users, {
as: 'updatedBy',
});
};
return age_groups;
};

View File

@ -0,0 +1,157 @@
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,
},
message: {
type: DataTypes.TEXT,
},
audience: {
type: DataTypes.ENUM,
values: [
"all",
"guardians",
"staff",
"k_2",
"grades_3_5",
"grades_6_12"
],
},
publish_datetime: {
type: DataTypes.DATE,
},
expire_datetime: {
type: DataTypes.DATE,
},
is_published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.announcements.belongsTo(db.users, {
as: 'createdBy',
});
db.announcements.belongsTo(db.users, {
as: 'updatedBy',
});
};
return announcements;
};

View File

@ -0,0 +1,252 @@
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 camp_sessions = sequelize.define(
'camp_sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
theme_title: {
type: DataTypes.TEXT,
},
theme_summary: {
type: DataTypes.TEXT,
},
theme_scripture_reference: {
type: DataTypes.TEXT,
},
theme_scripture_text: {
type: DataTypes.TEXT,
},
start_datetime: {
type: DataTypes.DATE,
},
end_datetime: {
type: DataTypes.DATE,
},
day_camp_hours: {
type: DataTypes.TEXT,
},
third_shift_hours: {
type: DataTypes.TEXT,
},
is_published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
camp_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.camp_sessions.hasMany(db.weekly_themes, {
as: 'weekly_themes_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.camp_sessions.hasMany(db.pricing_plans, {
as: 'pricing_plans_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.camp_sessions.hasMany(db.fee_rules, {
as: 'fee_rules_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.camp_sessions.hasMany(db.enrollments, {
as: 'enrollments_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.camp_sessions.hasMany(db.waiver_documents, {
as: 'waiver_documents_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.camp_sessions.hasMany(db.field_trip_events, {
as: 'field_trip_events_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.camp_sessions.hasMany(db.special_trips, {
as: 'special_trips_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.camp_sessions.hasMany(db.end_of_summer_trip_options, {
as: 'end_of_summer_trip_options_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.camp_sessions.hasMany(db.activity_blocks, {
as: 'activity_blocks_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.camp_sessions.hasMany(db.staff_assignments, {
as: 'staff_assignments_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.camp_sessions.hasMany(db.announcements, {
as: 'announcements_camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
//end loop
db.camp_sessions.belongsTo(db.campuses, {
as: 'campus',
foreignKey: {
name: 'campusId',
},
constraints: false,
});
db.camp_sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.camp_sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return camp_sessions;
};

View File

@ -0,0 +1,180 @@
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 campers = sequelize.define(
'campers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
first_name: {
type: DataTypes.TEXT,
},
last_name: {
type: DataTypes.TEXT,
},
date_of_birth: {
type: DataTypes.DATE,
},
grade_level: {
type: DataTypes.INTEGER,
},
gender: {
type: DataTypes.ENUM,
values: [
"female",
"male",
"nonbinary",
"prefer_not_to_say"
],
},
allergies: {
type: DataTypes.TEXT,
},
medical_notes: {
type: DataTypes.TEXT,
},
special_needs_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
campers.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.campers.hasMany(db.enrollments, {
as: 'enrollments_camper',
foreignKey: {
name: 'camperId',
},
constraints: false,
});
//end loop
db.campers.belongsTo(db.guardians, {
as: 'primary_guardian',
foreignKey: {
name: 'primary_guardianId',
},
constraints: false,
});
db.campers.hasMany(db.file, {
as: 'profile_photo',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.campers.getTableName(),
belongsToColumn: 'profile_photo',
},
});
db.campers.belongsTo(db.users, {
as: 'createdBy',
});
db.campers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return campers;
};

View File

@ -0,0 +1,126 @@
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 campuses = sequelize.define(
'campuses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
campuses.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.campuses.hasMany(db.camp_sessions, {
as: 'camp_sessions_campus',
foreignKey: {
name: 'campusId',
},
constraints: false,
});
//end loop
db.campuses.belongsTo(db.users, {
as: 'createdBy',
});
db.campuses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return campuses;
};

View File

@ -0,0 +1,161 @@
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 curriculum_subjects = sequelize.define(
'curriculum_subjects',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
subject_type: {
type: DataTypes.ENUM,
values: [
"math",
"ela",
"spanish",
"stem",
"bible",
"arts",
"music",
"dance",
"cooking",
"drama",
"choir",
"leadership"
],
},
description: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
curriculum_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.curriculum_subjects.hasMany(db.staff_assignments, {
as: 'staff_assignments_subject',
foreignKey: {
name: 'subjectId',
},
constraints: false,
});
//end loop
db.curriculum_subjects.belongsTo(db.users, {
as: 'createdBy',
});
db.curriculum_subjects.belongsTo(db.users, {
as: 'updatedBy',
});
};
return curriculum_subjects;
};

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 document_signatures = sequelize.define(
'document_signatures',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"required",
"signed",
"declined"
],
},
signed_datetime: {
type: DataTypes.DATE,
},
signature_name: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
document_signatures.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.document_signatures.belongsTo(db.waiver_documents, {
as: 'waiver_document',
foreignKey: {
name: 'waiver_documentId',
},
constraints: false,
});
db.document_signatures.belongsTo(db.enrollments, {
as: 'enrollment',
foreignKey: {
name: 'enrollmentId',
},
constraints: false,
});
db.document_signatures.belongsTo(db.guardians, {
as: 'guardian',
foreignKey: {
name: 'guardianId',
},
constraints: false,
});
db.document_signatures.belongsTo(db.users, {
as: 'createdBy',
});
db.document_signatures.belongsTo(db.users, {
as: 'updatedBy',
});
};
return document_signatures;
};

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 end_of_summer_trip_options = sequelize.define(
'end_of_summer_trip_options',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
option_type: {
type: DataTypes.ENUM,
values: [
"day_trip",
"overnight"
],
},
destination: {
type: DataTypes.TEXT,
},
estimated_price: {
type: DataTypes.DECIMAL,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
end_of_summer_trip_options.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.end_of_summer_trip_options.hasMany(db.end_of_summer_trip_selections, {
as: 'end_of_summer_trip_selections_trip_option',
foreignKey: {
name: 'trip_optionId',
},
constraints: false,
});
//end loop
db.end_of_summer_trip_options.belongsTo(db.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.end_of_summer_trip_options.belongsTo(db.users, {
as: 'createdBy',
});
db.end_of_summer_trip_options.belongsTo(db.users, {
as: 'updatedBy',
});
};
return end_of_summer_trip_options;
};

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 end_of_summer_trip_selections = sequelize.define(
'end_of_summer_trip_selections',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"selected",
"confirmed",
"cancelled"
],
},
selected_datetime: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
end_of_summer_trip_selections.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.end_of_summer_trip_selections.belongsTo(db.enrollments, {
as: 'enrollment',
foreignKey: {
name: 'enrollmentId',
},
constraints: false,
});
db.end_of_summer_trip_selections.belongsTo(db.end_of_summer_trip_options, {
as: 'trip_option',
foreignKey: {
name: 'trip_optionId',
},
constraints: false,
});
db.end_of_summer_trip_selections.belongsTo(db.users, {
as: 'createdBy',
});
db.end_of_summer_trip_selections.belongsTo(db.users, {
as: 'updatedBy',
});
};
return end_of_summer_trip_selections;
};

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 enrollments = sequelize.define(
'enrollments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
submitted_datetime: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"submitted",
"approved",
"waitlisted",
"cancelled"
],
},
application_fee_waived: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
enrollments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.enrollments.hasMany(db.payments, {
as: 'payments_enrollment',
foreignKey: {
name: 'enrollmentId',
},
constraints: false,
});
db.enrollments.hasMany(db.document_signatures, {
as: 'document_signatures_enrollment',
foreignKey: {
name: 'enrollmentId',
},
constraints: false,
});
db.enrollments.hasMany(db.trip_registrations, {
as: 'trip_registrations_enrollment',
foreignKey: {
name: 'enrollmentId',
},
constraints: false,
});
db.enrollments.hasMany(db.end_of_summer_trip_selections, {
as: 'end_of_summer_trip_selections_enrollment',
foreignKey: {
name: 'enrollmentId',
},
constraints: false,
});
//end loop
db.enrollments.belongsTo(db.campers, {
as: 'camper',
foreignKey: {
name: 'camperId',
},
constraints: false,
});
db.enrollments.belongsTo(db.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.enrollments.belongsTo(db.pricing_plans, {
as: 'pricing_plan',
foreignKey: {
name: 'pricing_planId',
},
constraints: false,
});
db.enrollments.belongsTo(db.age_groups, {
as: 'age_group',
foreignKey: {
name: 'age_groupId',
},
constraints: false,
});
db.enrollments.belongsTo(db.users, {
as: 'createdBy',
});
db.enrollments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return enrollments;
};

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 fee_rules = sequelize.define(
'fee_rules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
fee_kind: {
type: DataTypes.ENUM,
values: [
"application_fee"
],
},
amount: {
type: DataTypes.DECIMAL,
},
waiver_first_n: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
fee_rules.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.fee_rules.belongsTo(db.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.fee_rules.belongsTo(db.users, {
as: 'createdBy',
});
db.fee_rules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return fee_rules;
};

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 field_trip_catalog = sequelize.define(
'field_trip_catalog',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
category: {
type: DataTypes.ENUM,
values: [
"educational_environmental",
"museums_culture",
"stem_learning",
"fun_recreation",
"movies",
"zoo",
"premium"
],
},
location_name: {
type: DataTypes.TEXT,
},
grade_range: {
type: DataTypes.TEXT,
},
typical_min_rate: {
type: DataTypes.DECIMAL,
},
typical_max_rate: {
type: DataTypes.DECIMAL,
},
separate_payment_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
field_trip_catalog.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.field_trip_catalog.hasMany(db.field_trip_events, {
as: 'field_trip_events_field_trip',
foreignKey: {
name: 'field_tripId',
},
constraints: false,
});
//end loop
db.field_trip_catalog.belongsTo(db.users, {
as: 'createdBy',
});
db.field_trip_catalog.belongsTo(db.users, {
as: 'updatedBy',
});
};
return field_trip_catalog;
};

View File

@ -0,0 +1,168 @@
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 field_trip_events = sequelize.define(
'field_trip_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
depart_datetime: {
type: DataTypes.DATE,
},
return_datetime: {
type: DataTypes.DATE,
},
price_per_student: {
type: DataTypes.DECIMAL,
},
capacity: {
type: DataTypes.INTEGER,
},
status: {
type: DataTypes.ENUM,
values: [
"planned",
"open",
"full",
"cancelled",
"completed"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
field_trip_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.field_trip_events.hasMany(db.trip_registrations, {
as: 'trip_registrations_field_trip_event',
foreignKey: {
name: 'field_trip_eventId',
},
constraints: false,
});
//end loop
db.field_trip_events.belongsTo(db.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.field_trip_events.belongsTo(db.field_trip_catalog, {
as: 'field_trip',
foreignKey: {
name: 'field_tripId',
},
constraints: false,
});
db.field_trip_events.belongsTo(db.age_groups, {
as: 'age_group',
foreignKey: {
name: 'age_groupId',
},
constraints: false,
});
db.field_trip_events.belongsTo(db.users, {
as: 'createdBy',
});
db.field_trip_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return field_trip_events;
};

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,163 @@
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 guardians = sequelize.define(
'guardians',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
primary_phone: {
type: DataTypes.TEXT,
},
secondary_phone: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
emergency_contact_name: {
type: DataTypes.TEXT,
},
emergency_contact_phone: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
guardians.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.guardians.hasMany(db.campers, {
as: 'campers_primary_guardian',
foreignKey: {
name: 'primary_guardianId',
},
constraints: false,
});
db.guardians.hasMany(db.document_signatures, {
as: 'document_signatures_guardian',
foreignKey: {
name: 'guardianId',
},
constraints: false,
});
//end loop
db.guardians.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.guardians.belongsTo(db.users, {
as: 'createdBy',
});
db.guardians.belongsTo(db.users, {
as: 'updatedBy',
});
};
return guardians;
};

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,191 @@
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,
},
payment_kind: {
type: DataTypes.ENUM,
values: [
"application_fee",
"monthly_tuition",
"field_trip",
"special_trip",
"end_of_summer_trip"
],
},
amount: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"paid",
"failed",
"refunded",
"waived"
],
},
method: {
type: DataTypes.ENUM,
values: [
"cash",
"check",
"card",
"online"
],
},
reference_code: {
type: DataTypes.TEXT,
},
due_datetime: {
type: DataTypes.DATE,
},
paid_datetime: {
type: DataTypes.DATE,
},
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.enrollments, {
as: 'enrollment',
foreignKey: {
name: 'enrollmentId',
},
constraints: false,
});
db.payments.belongsTo(db.users, {
as: 'createdBy',
});
db.payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payments;
};

View File

@ -0,0 +1,90 @@
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,192 @@
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 pricing_plans = sequelize.define(
'pricing_plans',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
plan_type: {
type: DataTypes.ENUM,
values: [
"standard_day_camp",
"pickup_dropoff_only",
"late_shift_only",
"combined_package"
],
},
monthly_tuition: {
type: DataTypes.DECIMAL,
},
included_summary: {
type: DataTypes.TEXT,
},
includes_dinner: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
includes_pickup: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
includes_dropoff: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
includes_third_shift: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
pricing_plans.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.pricing_plans.hasMany(db.enrollments, {
as: 'enrollments_pricing_plan',
foreignKey: {
name: 'pricing_planId',
},
constraints: false,
});
//end loop
db.pricing_plans.belongsTo(db.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.pricing_plans.belongsTo(db.users, {
as: 'createdBy',
});
db.pricing_plans.belongsTo(db.users, {
as: 'updatedBy',
});
};
return pricing_plans;
};

View File

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

View File

@ -0,0 +1,152 @@
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 special_trips = sequelize.define(
'special_trips',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
trip_type: {
type: DataTypes.ENUM,
values: [
"state_aim",
"national_aim"
],
},
destination: {
type: DataTypes.TEXT,
},
start_datetime: {
type: DataTypes.DATE,
},
end_datetime: {
type: DataTypes.DATE,
},
package_notes: {
type: DataTypes.TEXT,
},
separate_payment_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
special_trips.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.special_trips.belongsTo(db.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.special_trips.belongsTo(db.users, {
as: 'createdBy',
});
db.special_trips.belongsTo(db.users, {
as: 'updatedBy',
});
};
return special_trips;
};

View File

@ -0,0 +1,147 @@
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 staff_assignments = sequelize.define(
'staff_assignments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
assignment_role: {
type: DataTypes.ENUM,
values: [
"teacher",
"counselor",
"shift_lead",
"driver",
"volunteer"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
staff_assignments.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.staff_assignments.belongsTo(db.users, {
as: 'staff_user',
foreignKey: {
name: 'staff_userId',
},
constraints: false,
});
db.staff_assignments.belongsTo(db.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.staff_assignments.belongsTo(db.age_groups, {
as: 'age_group',
foreignKey: {
name: 'age_groupId',
},
constraints: false,
});
db.staff_assignments.belongsTo(db.curriculum_subjects, {
as: 'subject',
foreignKey: {
name: 'subjectId',
},
constraints: false,
});
db.staff_assignments.belongsTo(db.users, {
as: 'createdBy',
});
db.staff_assignments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return staff_assignments;
};

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 trip_registrations = sequelize.define(
'trip_registrations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"requested",
"confirmed",
"cancelled"
],
},
permission_granted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
registered_datetime: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
trip_registrations.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.trip_registrations.belongsTo(db.field_trip_events, {
as: 'field_trip_event',
foreignKey: {
name: 'field_trip_eventId',
},
constraints: false,
});
db.trip_registrations.belongsTo(db.enrollments, {
as: 'enrollment',
foreignKey: {
name: 'enrollmentId',
},
constraints: false,
});
db.trip_registrations.belongsTo(db.users, {
as: 'createdBy',
});
db.trip_registrations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return trip_registrations;
};

View File

@ -0,0 +1,264 @@
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.guardians, {
as: 'guardians_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.staff_assignments, {
as: 'staff_assignments_staff_user',
foreignKey: {
name: 'staff_userId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

View File

@ -0,0 +1,151 @@
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 waiver_documents = sequelize.define(
'waiver_documents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
document_type: {
type: DataTypes.ENUM,
values: [
"liability_waiver",
"media_release",
"medical_consent",
"behavior_agreement",
"field_trip_permission"
],
},
is_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
waiver_documents.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.waiver_documents.hasMany(db.document_signatures, {
as: 'document_signatures_waiver_document',
foreignKey: {
name: 'waiver_documentId',
},
constraints: false,
});
//end loop
db.waiver_documents.belongsTo(db.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.waiver_documents.hasMany(db.file, {
as: 'document_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.waiver_documents.getTableName(),
belongsToColumn: 'document_file',
},
});
db.waiver_documents.belongsTo(db.users, {
as: 'createdBy',
});
db.waiver_documents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return waiver_documents;
};

View File

@ -0,0 +1,126 @@
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 weekly_themes = sequelize.define(
'weekly_themes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
week_number: {
type: DataTypes.INTEGER,
},
title: {
type: DataTypes.TEXT,
},
tagline: {
type: DataTypes.TEXT,
},
start_datetime: {
type: DataTypes.DATE,
},
end_datetime: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
weekly_themes.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.weekly_themes.belongsTo(db.camp_sessions, {
as: 'camp_session',
foreignKey: {
name: 'camp_sessionId',
},
constraints: false,
});
db.weekly_themes.belongsTo(db.users, {
as: 'createdBy',
});
db.weekly_themes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return weekly_themes;
};

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

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

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

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

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

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

@ -0,0 +1,226 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const campusesRoutes = require('./routes/campuses');
const camp_sessionsRoutes = require('./routes/camp_sessions');
const age_groupsRoutes = require('./routes/age_groups');
const weekly_themesRoutes = require('./routes/weekly_themes');
const pricing_plansRoutes = require('./routes/pricing_plans');
const fee_rulesRoutes = require('./routes/fee_rules');
const guardiansRoutes = require('./routes/guardians');
const campersRoutes = require('./routes/campers');
const enrollmentsRoutes = require('./routes/enrollments');
const paymentsRoutes = require('./routes/payments');
const waiver_documentsRoutes = require('./routes/waiver_documents');
const document_signaturesRoutes = require('./routes/document_signatures');
const field_trip_catalogRoutes = require('./routes/field_trip_catalog');
const field_trip_eventsRoutes = require('./routes/field_trip_events');
const trip_registrationsRoutes = require('./routes/trip_registrations');
const special_tripsRoutes = require('./routes/special_trips');
const end_of_summer_trip_optionsRoutes = require('./routes/end_of_summer_trip_options');
const end_of_summer_trip_selectionsRoutes = require('./routes/end_of_summer_trip_selections');
const activity_blocksRoutes = require('./routes/activity_blocks');
const curriculum_subjectsRoutes = require('./routes/curriculum_subjects');
const staff_assignmentsRoutes = require('./routes/staff_assignments');
const announcementsRoutes = require('./routes/announcements');
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: "Relentless Generation Camp App",
description: "Relentless Generation Camp App 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/campuses', passport.authenticate('jwt', {session: false}), campusesRoutes);
app.use('/api/camp_sessions', passport.authenticate('jwt', {session: false}), camp_sessionsRoutes);
app.use('/api/age_groups', passport.authenticate('jwt', {session: false}), age_groupsRoutes);
app.use('/api/weekly_themes', passport.authenticate('jwt', {session: false}), weekly_themesRoutes);
app.use('/api/pricing_plans', passport.authenticate('jwt', {session: false}), pricing_plansRoutes);
app.use('/api/fee_rules', passport.authenticate('jwt', {session: false}), fee_rulesRoutes);
app.use('/api/guardians', passport.authenticate('jwt', {session: false}), guardiansRoutes);
app.use('/api/campers', passport.authenticate('jwt', {session: false}), campersRoutes);
app.use('/api/enrollments', passport.authenticate('jwt', {session: false}), enrollmentsRoutes);
app.use('/api/payments', passport.authenticate('jwt', {session: false}), paymentsRoutes);
app.use('/api/waiver_documents', passport.authenticate('jwt', {session: false}), waiver_documentsRoutes);
app.use('/api/document_signatures', passport.authenticate('jwt', {session: false}), document_signaturesRoutes);
app.use('/api/field_trip_catalog', passport.authenticate('jwt', {session: false}), field_trip_catalogRoutes);
app.use('/api/field_trip_events', passport.authenticate('jwt', {session: false}), field_trip_eventsRoutes);
app.use('/api/trip_registrations', passport.authenticate('jwt', {session: false}), trip_registrationsRoutes);
app.use('/api/special_trips', passport.authenticate('jwt', {session: false}), special_tripsRoutes);
app.use('/api/end_of_summer_trip_options', passport.authenticate('jwt', {session: false}), end_of_summer_trip_optionsRoutes);
app.use('/api/end_of_summer_trip_selections', passport.authenticate('jwt', {session: false}), end_of_summer_trip_selectionsRoutes);
app.use('/api/activity_blocks', passport.authenticate('jwt', {session: false}), activity_blocksRoutes);
app.use('/api/curriculum_subjects', passport.authenticate('jwt', {session: false}), curriculum_subjectsRoutes);
app.use('/api/staff_assignments', passport.authenticate('jwt', {session: false}), staff_assignmentsRoutes);
app.use('/api/announcements', passport.authenticate('jwt', {session: false}), announcementsRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
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,434 @@
const express = require('express');
const Activity_blocksService = require('../services/activity_blocks');
const Activity_blocksDBApi = require('../db/api/activity_blocks');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('activity_blocks'));
/**
* @swagger
* components:
* schemas:
* Activity_blocks:
* type: object
* properties:
* name:
* type: string
* default: name
* details:
* type: string
* default: details
*
*
*/
/**
* @swagger
* tags:
* name: Activity_blocks
* description: The Activity_blocks managing API
*/
/**
* @swagger
* /api/activity_blocks:
* post:
* security:
* - bearerAuth: []
* tags: [Activity_blocks]
* 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/Activity_blocks"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Activity_blocks"
* 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 Activity_blocksService.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: [Activity_blocks]
* 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/Activity_blocks"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Activity_blocks"
* 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 Activity_blocksService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/activity_blocks/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Activity_blocks]
* 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/Activity_blocks"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Activity_blocks"
* 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 Activity_blocksService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/activity_blocks/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Activity_blocks]
* 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/Activity_blocks"
* 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 Activity_blocksService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/activity_blocks/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Activity_blocks]
* 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/Activity_blocks"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Activity_blocksService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/activity_blocks:
* get:
* security:
* - bearerAuth: []
* tags: [Activity_blocks]
* summary: Get all activity_blocks
* description: Get all activity_blocks
* responses:
* 200:
* description: Activity_blocks list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Activity_blocks"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await Activity_blocksDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','details',
'block_start_datetime','block_end_datetime',
];
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/activity_blocks/count:
* get:
* security:
* - bearerAuth: []
* tags: [Activity_blocks]
* summary: Count all activity_blocks
* description: Count all activity_blocks
* responses:
* 200:
* description: Activity_blocks count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Activity_blocks"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Activity_blocksDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/activity_blocks/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Activity_blocks]
* summary: Find all activity_blocks that match search criteria
* description: Find all activity_blocks that match search criteria
* responses:
* 200:
* description: Activity_blocks list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Activity_blocks"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Activity_blocksDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/activity_blocks/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Activity_blocks]
* 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/Activity_blocks"
* 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 Activity_blocksDBApi.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 Age_groupsService = require('../services/age_groups');
const Age_groupsDBApi = require('../db/api/age_groups');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('age_groups'));
/**
* @swagger
* components:
* schemas:
* Age_groups:
* type: object
* properties:
* name:
* type: string
* default: name
* theme_scripture_reference:
* type: string
* default: theme_scripture_reference
* theme_scripture_text:
* type: string
* default: theme_scripture_text
* focus_summary:
* type: string
* default: focus_summary
* min_grade:
* type: integer
* format: int64
* max_grade:
* type: integer
* format: int64
*/
/**
* @swagger
* tags:
* name: Age_groups
* description: The Age_groups managing API
*/
/**
* @swagger
* /api/age_groups:
* post:
* security:
* - bearerAuth: []
* tags: [Age_groups]
* 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/Age_groups"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Age_groups"
* 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 Age_groupsService.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: [Age_groups]
* 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/Age_groups"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Age_groups"
* 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 Age_groupsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/age_groups/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Age_groups]
* 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/Age_groups"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Age_groups"
* 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 Age_groupsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/age_groups/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Age_groups]
* 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/Age_groups"
* 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 Age_groupsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/age_groups/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Age_groups]
* 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/Age_groups"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Age_groupsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/age_groups:
* get:
* security:
* - bearerAuth: []
* tags: [Age_groups]
* summary: Get all age_groups
* description: Get all age_groups
* responses:
* 200:
* description: Age_groups list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Age_groups"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await Age_groupsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','theme_scripture_reference','theme_scripture_text','focus_summary',
'min_grade','max_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/age_groups/count:
* get:
* security:
* - bearerAuth: []
* tags: [Age_groups]
* summary: Count all age_groups
* description: Count all age_groups
* responses:
* 200:
* description: Age_groups count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Age_groups"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Age_groupsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/age_groups/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Age_groups]
* summary: Find all age_groups that match search criteria
* description: Find all age_groups that match search criteria
* responses:
* 200:
* description: Age_groups list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Age_groups"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Age_groupsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/age_groups/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Age_groups]
* 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/Age_groups"
* 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 Age_groupsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,433 @@
const express = require('express');
const AnnouncementsService = require('../services/announcements');
const AnnouncementsDBApi = require('../db/api/announcements');
const wrapAsync = require('../helpers').wrapAsync;
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
* message:
* type: string
* default: message
*
*/
/**
* @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 currentUser = req.currentUser;
const payload = await AnnouncementsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','title','message',
'publish_datetime','expire_datetime',
];
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 currentUser = req.currentUser;
const payload = await AnnouncementsDBApi.findAll(
req.query,
null,
{ 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 payload = await AnnouncementsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
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;

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

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

View File

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

View File

@ -0,0 +1,445 @@
const express = require('express');
const CampersService = require('../services/campers');
const CampersDBApi = require('../db/api/campers');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('campers'));
/**
* @swagger
* components:
* schemas:
* Campers:
* type: object
* properties:
* first_name:
* type: string
* default: first_name
* last_name:
* type: string
* default: last_name
* allergies:
* type: string
* default: allergies
* medical_notes:
* type: string
* default: medical_notes
* special_needs_notes:
* type: string
* default: special_needs_notes
* grade_level:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Campers
* description: The Campers managing API
*/
/**
* @swagger
* /api/campers:
* post:
* security:
* - bearerAuth: []
* tags: [Campers]
* 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/Campers"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Campers"
* 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 CampersService.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: [Campers]
* 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/Campers"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Campers"
* 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 CampersService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/campers/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Campers]
* 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/Campers"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Campers"
* 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 CampersService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/campers/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Campers]
* 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/Campers"
* 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 CampersService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/campers/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Campers]
* 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/Campers"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await CampersService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/campers:
* get:
* security:
* - bearerAuth: []
* tags: [Campers]
* summary: Get all campers
* description: Get all campers
* responses:
* 200:
* description: Campers list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Campers"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await CampersDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','first_name','last_name','allergies','medical_notes','special_needs_notes',
'grade_level',
'date_of_birth',
];
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/campers/count:
* get:
* security:
* - bearerAuth: []
* tags: [Campers]
* summary: Count all campers
* description: Count all campers
* responses:
* 200:
* description: Campers count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Campers"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await CampersDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/campers/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Campers]
* summary: Find all campers that match search criteria
* description: Find all campers that match search criteria
* responses:
* 200:
* description: Campers list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Campers"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await CampersDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/campers/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Campers]
* 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/Campers"
* 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 CampersDBApi.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 CampusesService = require('../services/campuses');
const CampusesDBApi = require('../db/api/campuses');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('campuses'));
/**
* @swagger
* components:
* schemas:
* Campuses:
* type: object
* properties:
* name:
* type: string
* default: name
* address_line1:
* type: string
* default: address_line1
* city:
* type: string
* default: city
* state:
* type: string
* default: state
* postal_code:
* type: string
* default: postal_code
*/
/**
* @swagger
* tags:
* name: Campuses
* description: The Campuses managing API
*/
/**
* @swagger
* /api/campuses:
* post:
* security:
* - bearerAuth: []
* tags: [Campuses]
* 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/Campuses"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Campuses"
* 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 CampusesService.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: [Campuses]
* 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/Campuses"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Campuses"
* 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 CampusesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/campuses/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Campuses]
* 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/Campuses"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Campuses"
* 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 CampusesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/campuses/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Campuses]
* 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/Campuses"
* 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 CampusesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/campuses/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Campuses]
* 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/Campuses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await CampusesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/campuses:
* get:
* security:
* - bearerAuth: []
* tags: [Campuses]
* summary: Get all campuses
* description: Get all campuses
* responses:
* 200:
* description: Campuses list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Campuses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await CampusesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','address_line1','city','state','postal_code',
];
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/campuses/count:
* get:
* security:
* - bearerAuth: []
* tags: [Campuses]
* summary: Count all campuses
* description: Count all campuses
* responses:
* 200:
* description: Campuses count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Campuses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await CampusesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/campuses/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Campuses]
* summary: Find all campuses that match search criteria
* description: Find all campuses that match search criteria
* responses:
* 200:
* description: Campuses list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Campuses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await CampusesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/campuses/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Campuses]
* 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/Campuses"
* 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 CampusesDBApi.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,433 @@
const express = require('express');
const Curriculum_subjectsService = require('../services/curriculum_subjects');
const Curriculum_subjectsDBApi = require('../db/api/curriculum_subjects');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('curriculum_subjects'));
/**
* @swagger
* components:
* schemas:
* Curriculum_subjects:
* type: object
* properties:
* name:
* type: string
* default: name
* description:
* type: string
* default: description
*
*/
/**
* @swagger
* tags:
* name: Curriculum_subjects
* description: The Curriculum_subjects managing API
*/
/**
* @swagger
* /api/curriculum_subjects:
* post:
* security:
* - bearerAuth: []
* tags: [Curriculum_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/Curriculum_subjects"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Curriculum_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 Curriculum_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: [Curriculum_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/Curriculum_subjects"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Curriculum_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 Curriculum_subjectsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/curriculum_subjects/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Curriculum_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/Curriculum_subjects"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Curriculum_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 Curriculum_subjectsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/curriculum_subjects/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Curriculum_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/Curriculum_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 Curriculum_subjectsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/curriculum_subjects/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Curriculum_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/Curriculum_subjects"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Curriculum_subjectsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/curriculum_subjects:
* get:
* security:
* - bearerAuth: []
* tags: [Curriculum_subjects]
* summary: Get all curriculum_subjects
* description: Get all curriculum_subjects
* responses:
* 200:
* description: Curriculum_subjects list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Curriculum_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 currentUser = req.currentUser;
const payload = await Curriculum_subjectsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','description',
];
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/curriculum_subjects/count:
* get:
* security:
* - bearerAuth: []
* tags: [Curriculum_subjects]
* summary: Count all curriculum_subjects
* description: Count all curriculum_subjects
* responses:
* 200:
* description: Curriculum_subjects count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Curriculum_subjects"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Curriculum_subjectsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/curriculum_subjects/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Curriculum_subjects]
* summary: Find all curriculum_subjects that match search criteria
* description: Find all curriculum_subjects that match search criteria
* responses:
* 200:
* description: Curriculum_subjects list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Curriculum_subjects"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Curriculum_subjectsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/curriculum_subjects/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Curriculum_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/Curriculum_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 Curriculum_subjectsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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