Initial version

This commit is contained in:
Flatlogic Bot 2026-03-25 17:47:36 +00:00
commit a7d3305462
886 changed files with 305764 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>Frontline Onboarding SaaS</h2>
<p>AI-driven gamified onboarding and coaching platform for frontline teams to improve engagement and speed to proficiency.</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 @@
# Frontline Onboarding SaaS
## 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_39324
DB_USER=app_39324
DB_PASS=bacd0295-2417-4eef-9cfa-a241b9670b7e
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 @@
#Frontline Onboarding SaaS - 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_frontline_onboarding_saas;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_frontline_onboarding_saas 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": "frontlineonboardingsaas",
"description": "Frontline Onboarding SaaS - 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});
});
}

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

@ -0,0 +1,80 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "bacd0295",
user_pass: "a241b9670b7e",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'bacd0295-2417-4eef-9cfa-a241b9670b7e',
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: 'Frontline Onboarding SaaS <app@flatlogic.app>',
host: 'email-smtp.us-east-1.amazonaws.com',
port: 587,
auth: {
user: process.env.EMAIL_USER || '',
pass: process.env.EMAIL_PASS,
},
tls: {
rejectUnauthorized: false
}
},
roles: {
super_admin: 'Super Administrator',
admin: 'Administrator',
user: 'User',
},
project_uuid: 'bacd0295-2417-4eef-9cfa-a241b9670b7e',
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 = 'Mountain trail with milestone markers';
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,599 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Ai_content_requestsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_content_requests = await db.ai_content_requests.create(
{
id: data.id || undefined,
request_type: data.request_type
||
null
,
prompt_text: data.prompt_text
||
null
,
status: data.status
||
null
,
requested_at: data.requested_at
||
null
,
completed_at: data.completed_at
||
null
,
output_text: data.output_text
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_content_requests.setOrganization(currentUser.organization.id || null, {
transaction,
});
await ai_content_requests.setRequested_by( data.requested_by || null, {
transaction,
});
return ai_content_requests;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const ai_content_requestsData = data.map((item, index) => ({
id: item.id || undefined,
request_type: item.request_type
||
null
,
prompt_text: item.prompt_text
||
null
,
status: item.status
||
null
,
requested_at: item.requested_at
||
null
,
completed_at: item.completed_at
||
null
,
output_text: item.output_text
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ai_content_requests = await db.ai_content_requests.bulkCreate(ai_content_requestsData, { transaction });
// For each item created, replace relation files
return ai_content_requests;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const ai_content_requests = await db.ai_content_requests.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.request_type !== undefined) updatePayload.request_type = data.request_type;
if (data.prompt_text !== undefined) updatePayload.prompt_text = data.prompt_text;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.output_text !== undefined) updatePayload.output_text = data.output_text;
updatePayload.updatedById = currentUser.id;
await ai_content_requests.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await ai_content_requests.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.requested_by !== undefined) {
await ai_content_requests.setRequested_by(
data.requested_by,
{ transaction }
);
}
return ai_content_requests;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_content_requests = await db.ai_content_requests.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ai_content_requests) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ai_content_requests) {
await record.destroy({transaction});
}
});
return ai_content_requests;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_content_requests = await db.ai_content_requests.findByPk(id, options);
await ai_content_requests.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ai_content_requests.destroy({
transaction
});
return ai_content_requests;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ai_content_requests = await db.ai_content_requests.findOne(
{ where },
{ transaction },
);
if (!ai_content_requests) {
return ai_content_requests;
}
const output = ai_content_requests.get({plain: true});
output.organization = await ai_content_requests.getOrganization({
transaction
});
output.requested_by = await ai_content_requests.getRequested_by({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.prompt_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_content_requests',
'prompt_text',
filter.prompt_text,
),
};
}
if (filter.output_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_content_requests',
'output_text',
filter.output_text,
),
};
}
if (filter.requested_atRange) {
const [start, end] = filter.requested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.request_type) {
where = {
...where,
request_type: filter.request_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.ai_content_requests.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'ai_content_requests',
'request_type',
query,
),
],
};
}
const records = await db.ai_content_requests.findAll({
attributes: [ 'id', 'request_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['request_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.request_type,
}));
}
};

View File

@ -0,0 +1,618 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Audit_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.create(
{
id: data.id || undefined,
event_name: data.event_name
||
null
,
entity_name: data.entity_name
||
null
,
entity_reference: data.entity_reference
||
null
,
event_payload_json: data.event_payload_json
||
null
,
occurred_at: data.occurred_at
||
null
,
ip_address: data.ip_address
||
null
,
user_agent: data.user_agent
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audit_events.setOrganization(currentUser.organization.id || null, {
transaction,
});
await audit_events.setActor( data.actor || null, {
transaction,
});
return audit_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 audit_eventsData = data.map((item, index) => ({
id: item.id || undefined,
event_name: item.event_name
||
null
,
entity_name: item.entity_name
||
null
,
entity_reference: item.entity_reference
||
null
,
event_payload_json: item.event_payload_json
||
null
,
occurred_at: item.occurred_at
||
null
,
ip_address: item.ip_address
||
null
,
user_agent: item.user_agent
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const audit_events = await db.audit_events.bulkCreate(audit_eventsData, { transaction });
// For each item created, replace relation files
return audit_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const audit_events = await db.audit_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.event_name !== undefined) updatePayload.event_name = data.event_name;
if (data.entity_name !== undefined) updatePayload.entity_name = data.entity_name;
if (data.entity_reference !== undefined) updatePayload.entity_reference = data.entity_reference;
if (data.event_payload_json !== undefined) updatePayload.event_payload_json = data.event_payload_json;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
updatePayload.updatedById = currentUser.id;
await audit_events.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await audit_events.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.actor !== undefined) {
await audit_events.setActor(
data.actor,
{ transaction }
);
}
return audit_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of audit_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of audit_events) {
await record.destroy({transaction});
}
});
return audit_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findByPk(id, options);
await audit_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await audit_events.destroy({
transaction
});
return audit_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findOne(
{ where },
{ transaction },
);
if (!audit_events) {
return audit_events;
}
const output = audit_events.get({plain: true});
output.organization = await audit_events.getOrganization({
transaction
});
output.actor = await audit_events.getActor({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.users,
as: 'actor',
where: filter.actor ? {
[Op.or]: [
{ id: { [Op.in]: filter.actor.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.actor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.event_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'event_name',
filter.event_name,
),
};
}
if (filter.entity_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'entity_name',
filter.entity_name,
),
};
}
if (filter.entity_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'entity_reference',
filter.entity_reference,
),
};
}
if (filter.event_payload_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'event_payload_json',
filter.event_payload_json,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'ip_address',
filter.ip_address,
),
};
}
if (filter.user_agent) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'user_agent',
filter.user_agent,
),
};
}
if (filter.occurred_atRange) {
const [start, end] = filter.occurred_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.audit_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'audit_events',
'event_name',
query,
),
],
};
}
const records = await db.audit_events.findAll({
attributes: [ 'id', 'event_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['event_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.event_name,
}));
}
};

View File

@ -0,0 +1,573 @@
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 BadgesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const badges = await db.badges.create(
{
id: data.id || undefined,
badge_name: data.badge_name
||
null
,
badge_description: data.badge_description
||
null
,
award_rule_type: data.award_rule_type
||
null
,
threshold_value: data.threshold_value
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await badges.setOrganization(currentUser.organization.id || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.badges.getTableName(),
belongsToColumn: 'badge_images',
belongsToId: badges.id,
},
data.badge_images,
options,
);
return badges;
}
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 badgesData = data.map((item, index) => ({
id: item.id || undefined,
badge_name: item.badge_name
||
null
,
badge_description: item.badge_description
||
null
,
award_rule_type: item.award_rule_type
||
null
,
threshold_value: item.threshold_value
||
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 badges = await db.badges.bulkCreate(badgesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < badges.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.badges.getTableName(),
belongsToColumn: 'badge_images',
belongsToId: badges[i].id,
},
data[i].badge_images,
options,
);
}
return badges;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const badges = await db.badges.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.badge_name !== undefined) updatePayload.badge_name = data.badge_name;
if (data.badge_description !== undefined) updatePayload.badge_description = data.badge_description;
if (data.award_rule_type !== undefined) updatePayload.award_rule_type = data.award_rule_type;
if (data.threshold_value !== undefined) updatePayload.threshold_value = data.threshold_value;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await badges.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await badges.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.badges.getTableName(),
belongsToColumn: 'badge_images',
belongsToId: badges.id,
},
data.badge_images,
options,
);
return badges;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const badges = await db.badges.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of badges) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of badges) {
await record.destroy({transaction});
}
});
return badges;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const badges = await db.badges.findByPk(id, options);
await badges.update({
deletedBy: currentUser.id
}, {
transaction,
});
await badges.destroy({
transaction
});
return badges;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const badges = await db.badges.findOne(
{ where },
{ transaction },
);
if (!badges) {
return badges;
}
const output = badges.get({plain: true});
output.user_badges_badge = await badges.getUser_badges_badge({
transaction
});
output.organization = await badges.getOrganization({
transaction
});
output.badge_images = await badges.getBadge_images({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.file,
as: 'badge_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.badge_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'badges',
'badge_name',
filter.badge_name,
),
};
}
if (filter.badge_description) {
where = {
...where,
[Op.and]: Utils.ilike(
'badges',
'badge_description',
filter.badge_description,
),
};
}
if (filter.threshold_valueRange) {
const [start, end] = filter.threshold_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
threshold_value: {
...where.threshold_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
threshold_value: {
...where.threshold_value,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.award_rule_type) {
where = {
...where,
award_rule_type: filter.award_rule_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.badges.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'badges',
'badge_name',
query,
),
],
};
}
const records = await db.badges.findAll({
attributes: [ 'id', 'badge_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['badge_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.badge_name,
}));
}
};

View File

@ -0,0 +1,625 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Challenge_participantsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const challenge_participants = await db.challenge_participants.create(
{
id: data.id || undefined,
participant_type: data.participant_type
||
null
,
current_value: data.current_value
||
null
,
status: data.status
||
null
,
rank_position: data.rank_position
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await challenge_participants.setChallenge( data.challenge || null, {
transaction,
});
await challenge_participants.setUser( data.user || null, {
transaction,
});
await challenge_participants.setTeam( data.team || null, {
transaction,
});
await challenge_participants.setOrganizations( data.organizations || null, {
transaction,
});
return challenge_participants;
}
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 challenge_participantsData = data.map((item, index) => ({
id: item.id || undefined,
participant_type: item.participant_type
||
null
,
current_value: item.current_value
||
null
,
status: item.status
||
null
,
rank_position: item.rank_position
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const challenge_participants = await db.challenge_participants.bulkCreate(challenge_participantsData, { transaction });
// For each item created, replace relation files
return challenge_participants;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const challenge_participants = await db.challenge_participants.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.participant_type !== undefined) updatePayload.participant_type = data.participant_type;
if (data.current_value !== undefined) updatePayload.current_value = data.current_value;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.rank_position !== undefined) updatePayload.rank_position = data.rank_position;
updatePayload.updatedById = currentUser.id;
await challenge_participants.update(updatePayload, {transaction});
if (data.challenge !== undefined) {
await challenge_participants.setChallenge(
data.challenge,
{ transaction }
);
}
if (data.user !== undefined) {
await challenge_participants.setUser(
data.user,
{ transaction }
);
}
if (data.team !== undefined) {
await challenge_participants.setTeam(
data.team,
{ transaction }
);
}
if (data.organizations !== undefined) {
await challenge_participants.setOrganizations(
data.organizations,
{ transaction }
);
}
return challenge_participants;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const challenge_participants = await db.challenge_participants.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of challenge_participants) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of challenge_participants) {
await record.destroy({transaction});
}
});
return challenge_participants;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const challenge_participants = await db.challenge_participants.findByPk(id, options);
await challenge_participants.update({
deletedBy: currentUser.id
}, {
transaction,
});
await challenge_participants.destroy({
transaction
});
return challenge_participants;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const challenge_participants = await db.challenge_participants.findOne(
{ where },
{ transaction },
);
if (!challenge_participants) {
return challenge_participants;
}
const output = challenge_participants.get({plain: true});
output.challenge = await challenge_participants.getChallenge({
transaction
});
output.user = await challenge_participants.getUser({
transaction
});
output.team = await challenge_participants.getTeam({
transaction
});
output.organizations = await challenge_participants.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.challenges,
as: 'challenge',
where: filter.challenge ? {
[Op.or]: [
{ id: { [Op.in]: filter.challenge.split('|').map(term => Utils.uuid(term)) } },
{
challenge_name: {
[Op.or]: filter.challenge.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.teams,
as: 'team',
where: filter.team ? {
[Op.or]: [
{ id: { [Op.in]: filter.team.split('|').map(term => Utils.uuid(term)) } },
{
team_name: {
[Op.or]: filter.team.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.current_valueRange) {
const [start, end] = filter.current_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_value: {
...where.current_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_value: {
...where.current_value,
[Op.lte]: end,
},
};
}
}
if (filter.rank_positionRange) {
const [start, end] = filter.rank_positionRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rank_position: {
...where.rank_position,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rank_position: {
...where.rank_position,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.participant_type) {
where = {
...where,
participant_type: filter.participant_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.challenge_participants.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'challenge_participants',
'participant_type',
query,
),
],
};
}
const records = await db.challenge_participants.findAll({
attributes: [ 'id', 'participant_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['participant_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.participant_type,
}));
}
};

View File

@ -0,0 +1,752 @@
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 ChallengesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const challenges = await db.challenges.create(
{
id: data.id || undefined,
challenge_name: data.challenge_name
||
null
,
challenge_type: data.challenge_type
||
null
,
metric_type: data.metric_type
||
null
,
description: data.description
||
null
,
target_value: data.target_value
||
null
,
reward_points: data.reward_points
||
null
,
reward_coins: data.reward_coins
||
null
,
starts_at: data.starts_at
||
null
,
ends_at: data.ends_at
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await challenges.setOrganization(currentUser.organization.id || null, {
transaction,
});
await challenges.setCreated_by( data.created_by || null, {
transaction,
});
return challenges;
}
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 challengesData = data.map((item, index) => ({
id: item.id || undefined,
challenge_name: item.challenge_name
||
null
,
challenge_type: item.challenge_type
||
null
,
metric_type: item.metric_type
||
null
,
description: item.description
||
null
,
target_value: item.target_value
||
null
,
reward_points: item.reward_points
||
null
,
reward_coins: item.reward_coins
||
null
,
starts_at: item.starts_at
||
null
,
ends_at: item.ends_at
||
null
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const challenges = await db.challenges.bulkCreate(challengesData, { transaction });
// For each item created, replace relation files
return challenges;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const challenges = await db.challenges.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.challenge_name !== undefined) updatePayload.challenge_name = data.challenge_name;
if (data.challenge_type !== undefined) updatePayload.challenge_type = data.challenge_type;
if (data.metric_type !== undefined) updatePayload.metric_type = data.metric_type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.target_value !== undefined) updatePayload.target_value = data.target_value;
if (data.reward_points !== undefined) updatePayload.reward_points = data.reward_points;
if (data.reward_coins !== undefined) updatePayload.reward_coins = data.reward_coins;
if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await challenges.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await challenges.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.created_by !== undefined) {
await challenges.setCreated_by(
data.created_by,
{ transaction }
);
}
return challenges;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const challenges = await db.challenges.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of challenges) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of challenges) {
await record.destroy({transaction});
}
});
return challenges;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const challenges = await db.challenges.findByPk(id, options);
await challenges.update({
deletedBy: currentUser.id
}, {
transaction,
});
await challenges.destroy({
transaction
});
return challenges;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const challenges = await db.challenges.findOne(
{ where },
{ transaction },
);
if (!challenges) {
return challenges;
}
const output = challenges.get({plain: true});
output.challenge_participants_challenge = await challenges.getChallenge_participants_challenge({
transaction
});
output.organization = await challenges.getOrganization({
transaction
});
output.created_by = await challenges.getCreated_by({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.users,
as: 'created_by',
where: filter.created_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.challenge_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'challenges',
'challenge_name',
filter.challenge_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'challenges',
'description',
filter.description,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
starts_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ends_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.target_valueRange) {
const [start, end] = filter.target_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.lte]: end,
},
};
}
}
if (filter.reward_pointsRange) {
const [start, end] = filter.reward_pointsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reward_points: {
...where.reward_points,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reward_points: {
...where.reward_points,
[Op.lte]: end,
},
};
}
}
if (filter.reward_coinsRange) {
const [start, end] = filter.reward_coinsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reward_coins: {
...where.reward_coins,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reward_coins: {
...where.reward_coins,
[Op.lte]: end,
},
};
}
}
if (filter.starts_atRange) {
const [start, end] = filter.starts_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.lte]: end,
},
};
}
}
if (filter.ends_atRange) {
const [start, end] = filter.ends_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.challenge_type) {
where = {
...where,
challenge_type: filter.challenge_type,
};
}
if (filter.metric_type) {
where = {
...where,
metric_type: filter.metric_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.challenges.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'challenges',
'challenge_name',
query,
),
],
};
}
const records = await db.challenges.findAll({
attributes: [ 'id', 'challenge_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['challenge_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.challenge_name,
}));
}
};

View File

@ -0,0 +1,630 @@
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 Checklist_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.create(
{
id: data.id || undefined,
item_title: data.item_title
||
null
,
sequence_order: data.sequence_order
||
null
,
item_type: data.item_type
||
null
,
instructions: data.instructions
||
null
,
link_url: data.link_url
||
null
,
is_required: data.is_required
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await checklist_items.setChecklist( data.checklist || null, {
transaction,
});
await checklist_items.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.checklist_items.getTableName(),
belongsToColumn: 'attachment_files',
belongsToId: checklist_items.id,
},
data.attachment_files,
options,
);
return checklist_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const checklist_itemsData = data.map((item, index) => ({
id: item.id || undefined,
item_title: item.item_title
||
null
,
sequence_order: item.sequence_order
||
null
,
item_type: item.item_type
||
null
,
instructions: item.instructions
||
null
,
link_url: item.link_url
||
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 checklist_items = await db.checklist_items.bulkCreate(checklist_itemsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < checklist_items.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.checklist_items.getTableName(),
belongsToColumn: 'attachment_files',
belongsToId: checklist_items[i].id,
},
data[i].attachment_files,
options,
);
}
return checklist_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const checklist_items = await db.checklist_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.item_title !== undefined) updatePayload.item_title = data.item_title;
if (data.sequence_order !== undefined) updatePayload.sequence_order = data.sequence_order;
if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
if (data.link_url !== undefined) updatePayload.link_url = data.link_url;
if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
updatePayload.updatedById = currentUser.id;
await checklist_items.update(updatePayload, {transaction});
if (data.checklist !== undefined) {
await checklist_items.setChecklist(
data.checklist,
{ transaction }
);
}
if (data.organizations !== undefined) {
await checklist_items.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.checklist_items.getTableName(),
belongsToColumn: 'attachment_files',
belongsToId: checklist_items.id,
},
data.attachment_files,
options,
);
return checklist_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of checklist_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of checklist_items) {
await record.destroy({transaction});
}
});
return checklist_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.findByPk(id, options);
await checklist_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await checklist_items.destroy({
transaction
});
return checklist_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.findOne(
{ where },
{ transaction },
);
if (!checklist_items) {
return checklist_items;
}
const output = checklist_items.get({plain: true});
output.checklist = await checklist_items.getChecklist({
transaction
});
output.attachment_files = await checklist_items.getAttachment_files({
transaction
});
output.organizations = await checklist_items.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.checklists,
as: 'checklist',
where: filter.checklist ? {
[Op.or]: [
{ id: { [Op.in]: filter.checklist.split('|').map(term => Utils.uuid(term)) } },
{
checklist_name: {
[Op.or]: filter.checklist.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'attachment_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.item_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklist_items',
'item_title',
filter.item_title,
),
};
}
if (filter.instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklist_items',
'instructions',
filter.instructions,
),
};
}
if (filter.link_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklist_items',
'link_url',
filter.link_url,
),
};
}
if (filter.sequence_orderRange) {
const [start, end] = filter.sequence_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.item_type) {
where = {
...where,
item_type: filter.item_type,
};
}
if (filter.is_required) {
where = {
...where,
is_required: filter.is_required,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.checklist_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'checklist_items',
'item_title',
query,
),
],
};
}
const records = await db.checklist_items.findAll({
attributes: [ 'id', 'item_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['item_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.item_title,
}));
}
};

View File

@ -0,0 +1,531 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ChecklistsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.create(
{
id: data.id || undefined,
checklist_name: data.checklist_name
||
null
,
checklist_stage: data.checklist_stage
||
null
,
description: data.description
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await checklists.setProgram( data.program || null, {
transaction,
});
await checklists.setOrganizations( data.organizations || null, {
transaction,
});
return checklists;
}
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 checklistsData = data.map((item, index) => ({
id: item.id || undefined,
checklist_name: item.checklist_name
||
null
,
checklist_stage: item.checklist_stage
||
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 checklists = await db.checklists.bulkCreate(checklistsData, { transaction });
// For each item created, replace relation files
return checklists;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const checklists = await db.checklists.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.checklist_name !== undefined) updatePayload.checklist_name = data.checklist_name;
if (data.checklist_stage !== undefined) updatePayload.checklist_stage = data.checklist_stage;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await checklists.update(updatePayload, {transaction});
if (data.program !== undefined) {
await checklists.setProgram(
data.program,
{ transaction }
);
}
if (data.organizations !== undefined) {
await checklists.setOrganizations(
data.organizations,
{ transaction }
);
}
return checklists;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of checklists) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of checklists) {
await record.destroy({transaction});
}
});
return checklists;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.findByPk(id, options);
await checklists.update({
deletedBy: currentUser.id
}, {
transaction,
});
await checklists.destroy({
transaction
});
return checklists;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.findOne(
{ where },
{ transaction },
);
if (!checklists) {
return checklists;
}
const output = checklists.get({plain: true});
output.checklist_items_checklist = await checklists.getChecklist_items_checklist({
transaction
});
output.program = await checklists.getProgram({
transaction
});
output.organizations = await checklists.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.programs,
as: 'program',
where: filter.program ? {
[Op.or]: [
{ id: { [Op.in]: filter.program.split('|').map(term => Utils.uuid(term)) } },
{
program_name: {
[Op.or]: filter.program.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.checklist_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklists',
'checklist_name',
filter.checklist_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklists',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.checklist_stage) {
where = {
...where,
checklist_stage: filter.checklist_stage,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.checklists.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'checklists',
'checklist_name',
query,
),
],
};
}
const records = await db.checklists.findAll({
attributes: [ 'id', 'checklist_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['checklist_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.checklist_name,
}));
}
};

View File

@ -0,0 +1,715 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Coaching_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const coaching_sessions = await db.coaching_sessions.create(
{
id: data.id || undefined,
session_type: data.session_type
||
null
,
status: data.status
||
null
,
scheduled_at: data.scheduled_at
||
null
,
completed_at: data.completed_at
||
null
,
agenda: data.agenda
||
null
,
notes: data.notes
||
null
,
action_items: data.action_items
||
null
,
follow_up_at: data.follow_up_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await coaching_sessions.setOrganization(currentUser.organization.id || null, {
transaction,
});
await coaching_sessions.setCoach( data.coach || null, {
transaction,
});
await coaching_sessions.setCoachee( data.coachee || null, {
transaction,
});
return coaching_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 coaching_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
session_type: item.session_type
||
null
,
status: item.status
||
null
,
scheduled_at: item.scheduled_at
||
null
,
completed_at: item.completed_at
||
null
,
agenda: item.agenda
||
null
,
notes: item.notes
||
null
,
action_items: item.action_items
||
null
,
follow_up_at: item.follow_up_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const coaching_sessions = await db.coaching_sessions.bulkCreate(coaching_sessionsData, { transaction });
// For each item created, replace relation files
return coaching_sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const coaching_sessions = await db.coaching_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.session_type !== undefined) updatePayload.session_type = data.session_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.agenda !== undefined) updatePayload.agenda = data.agenda;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.action_items !== undefined) updatePayload.action_items = data.action_items;
if (data.follow_up_at !== undefined) updatePayload.follow_up_at = data.follow_up_at;
updatePayload.updatedById = currentUser.id;
await coaching_sessions.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await coaching_sessions.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.coach !== undefined) {
await coaching_sessions.setCoach(
data.coach,
{ transaction }
);
}
if (data.coachee !== undefined) {
await coaching_sessions.setCoachee(
data.coachee,
{ transaction }
);
}
return coaching_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const coaching_sessions = await db.coaching_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of coaching_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of coaching_sessions) {
await record.destroy({transaction});
}
});
return coaching_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const coaching_sessions = await db.coaching_sessions.findByPk(id, options);
await coaching_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await coaching_sessions.destroy({
transaction
});
return coaching_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const coaching_sessions = await db.coaching_sessions.findOne(
{ where },
{ transaction },
);
if (!coaching_sessions) {
return coaching_sessions;
}
const output = coaching_sessions.get({plain: true});
output.organization = await coaching_sessions.getOrganization({
transaction
});
output.coach = await coaching_sessions.getCoach({
transaction
});
output.coachee = await coaching_sessions.getCoachee({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.users,
as: 'coach',
where: filter.coach ? {
[Op.or]: [
{ id: { [Op.in]: filter.coach.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.coach.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'coachee',
where: filter.coachee ? {
[Op.or]: [
{ id: { [Op.in]: filter.coachee.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.coachee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.agenda) {
where = {
...where,
[Op.and]: Utils.ilike(
'coaching_sessions',
'agenda',
filter.agenda,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'coaching_sessions',
'notes',
filter.notes,
),
};
}
if (filter.action_items) {
where = {
...where,
[Op.and]: Utils.ilike(
'coaching_sessions',
'action_items',
filter.action_items,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
scheduled_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
follow_up_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.scheduled_atRange) {
const [start, end] = filter.scheduled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.follow_up_atRange) {
const [start, end] = filter.follow_up_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
follow_up_at: {
...where.follow_up_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
follow_up_at: {
...where.follow_up_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.session_type) {
where = {
...where,
session_type: filter.session_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.coaching_sessions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'coaching_sessions',
'session_type',
query,
),
],
};
}
const records = await db.coaching_sessions.findAll({
attributes: [ 'id', 'session_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['session_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.session_type,
}));
}
};

View File

@ -0,0 +1,554 @@
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 Content_assetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const content_assets = await db.content_assets.create(
{
id: data.id || undefined,
asset_title: data.asset_title
||
null
,
asset_type: data.asset_type
||
null
,
body: data.body
||
null
,
asset_url: data.asset_url
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await content_assets.setOrganization(currentUser.organization.id || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.content_assets.getTableName(),
belongsToColumn: 'asset_files',
belongsToId: content_assets.id,
},
data.asset_files,
options,
);
return content_assets;
}
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 content_assetsData = data.map((item, index) => ({
id: item.id || undefined,
asset_title: item.asset_title
||
null
,
asset_type: item.asset_type
||
null
,
body: item.body
||
null
,
asset_url: item.asset_url
||
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 content_assets = await db.content_assets.bulkCreate(content_assetsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < content_assets.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.content_assets.getTableName(),
belongsToColumn: 'asset_files',
belongsToId: content_assets[i].id,
},
data[i].asset_files,
options,
);
}
return content_assets;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const content_assets = await db.content_assets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.asset_title !== undefined) updatePayload.asset_title = data.asset_title;
if (data.asset_type !== undefined) updatePayload.asset_type = data.asset_type;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.asset_url !== undefined) updatePayload.asset_url = data.asset_url;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await content_assets.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await content_assets.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.content_assets.getTableName(),
belongsToColumn: 'asset_files',
belongsToId: content_assets.id,
},
data.asset_files,
options,
);
return content_assets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const content_assets = await db.content_assets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of content_assets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of content_assets) {
await record.destroy({transaction});
}
});
return content_assets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const content_assets = await db.content_assets.findByPk(id, options);
await content_assets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await content_assets.destroy({
transaction
});
return content_assets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const content_assets = await db.content_assets.findOne(
{ where },
{ transaction },
);
if (!content_assets) {
return content_assets;
}
const output = content_assets.get({plain: true});
output.organization = await content_assets.getOrganization({
transaction
});
output.asset_files = await content_assets.getAsset_files({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.file,
as: 'asset_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.asset_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'content_assets',
'asset_title',
filter.asset_title,
),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'content_assets',
'body',
filter.body,
),
};
}
if (filter.asset_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'content_assets',
'asset_url',
filter.asset_url,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.asset_type) {
where = {
...where,
asset_type: filter.asset_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.content_assets.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'content_assets',
'asset_title',
query,
),
],
};
}
const records = await db.content_assets.findAll({
attributes: [ 'id', 'asset_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['asset_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.asset_title,
}));
}
};

View File

@ -0,0 +1,701 @@
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,
enrollment_status: data.enrollment_status
||
null
,
assigned_at: data.assigned_at
||
null
,
started_at: data.started_at
||
null
,
completed_at: data.completed_at
||
null
,
due_at: data.due_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await enrollments.setOrganization(currentUser.organization.id || null, {
transaction,
});
await enrollments.setProgram( data.program || null, {
transaction,
});
await enrollments.setUser( data.user || null, {
transaction,
});
await enrollments.setAssigned_by( data.assigned_by || 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,
enrollment_status: item.enrollment_status
||
null
,
assigned_at: item.assigned_at
||
null
,
started_at: item.started_at
||
null
,
completed_at: item.completed_at
||
null
,
due_at: item.due_at
||
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 globalAccess = currentUser.app_role?.globalAccess;
const enrollments = await db.enrollments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.enrollment_status !== undefined) updatePayload.enrollment_status = data.enrollment_status;
if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
updatePayload.updatedById = currentUser.id;
await enrollments.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await enrollments.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.program !== undefined) {
await enrollments.setProgram(
data.program,
{ transaction }
);
}
if (data.user !== undefined) {
await enrollments.setUser(
data.user,
{ transaction }
);
}
if (data.assigned_by !== undefined) {
await enrollments.setAssigned_by(
data.assigned_by,
{ 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.mission_attempts_enrollment = await enrollments.getMission_attempts_enrollment({
transaction
});
output.organization = await enrollments.getOrganization({
transaction
});
output.program = await enrollments.getProgram({
transaction
});
output.user = await enrollments.getUser({
transaction
});
output.assigned_by = await enrollments.getAssigned_by({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.programs,
as: 'program',
where: filter.program ? {
[Op.or]: [
{ id: { [Op.in]: filter.program.split('|').map(term => Utils.uuid(term)) } },
{
program_name: {
[Op.or]: filter.program.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assigned_by',
where: filter.assigned_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assigned_by.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]: [
{
due_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
completed_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.assigned_atRange) {
const [start, end] = filter.assigned_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.lte]: end,
},
};
}
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.due_atRange) {
const [start, end] = filter.due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.enrollment_status) {
where = {
...where,
enrollment_status: filter.enrollment_status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'enrollments',
'enrollment_status',
query,
),
],
};
}
const records = await db.enrollments.findAll({
attributes: [ 'id', 'enrollment_status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['enrollment_status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.enrollment_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,555 @@
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 Knowledge_gap_assessmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const knowledge_gap_assessments = await db.knowledge_gap_assessments.create(
{
id: data.id || undefined,
assessment_type: data.assessment_type
||
null
,
assessed_at: data.assessed_at
||
null
,
overall_score: data.overall_score
||
null
,
insights_summary: data.insights_summary
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await knowledge_gap_assessments.setOrganization(currentUser.organization.id || null, {
transaction,
});
await knowledge_gap_assessments.setUser( data.user || null, {
transaction,
});
return knowledge_gap_assessments;
}
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 knowledge_gap_assessmentsData = data.map((item, index) => ({
id: item.id || undefined,
assessment_type: item.assessment_type
||
null
,
assessed_at: item.assessed_at
||
null
,
overall_score: item.overall_score
||
null
,
insights_summary: item.insights_summary
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const knowledge_gap_assessments = await db.knowledge_gap_assessments.bulkCreate(knowledge_gap_assessmentsData, { transaction });
// For each item created, replace relation files
return knowledge_gap_assessments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const knowledge_gap_assessments = await db.knowledge_gap_assessments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.assessment_type !== undefined) updatePayload.assessment_type = data.assessment_type;
if (data.assessed_at !== undefined) updatePayload.assessed_at = data.assessed_at;
if (data.overall_score !== undefined) updatePayload.overall_score = data.overall_score;
if (data.insights_summary !== undefined) updatePayload.insights_summary = data.insights_summary;
updatePayload.updatedById = currentUser.id;
await knowledge_gap_assessments.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await knowledge_gap_assessments.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.user !== undefined) {
await knowledge_gap_assessments.setUser(
data.user,
{ transaction }
);
}
return knowledge_gap_assessments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const knowledge_gap_assessments = await db.knowledge_gap_assessments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of knowledge_gap_assessments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of knowledge_gap_assessments) {
await record.destroy({transaction});
}
});
return knowledge_gap_assessments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const knowledge_gap_assessments = await db.knowledge_gap_assessments.findByPk(id, options);
await knowledge_gap_assessments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await knowledge_gap_assessments.destroy({
transaction
});
return knowledge_gap_assessments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const knowledge_gap_assessments = await db.knowledge_gap_assessments.findOne(
{ where },
{ transaction },
);
if (!knowledge_gap_assessments) {
return knowledge_gap_assessments;
}
const output = knowledge_gap_assessments.get({plain: true});
output.organization = await knowledge_gap_assessments.getOrganization({
transaction
});
output.user = await knowledge_gap_assessments.getUser({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
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.insights_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'knowledge_gap_assessments',
'insights_summary',
filter.insights_summary,
),
};
}
if (filter.assessed_atRange) {
const [start, end] = filter.assessed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
assessed_at: {
...where.assessed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
assessed_at: {
...where.assessed_at,
[Op.lte]: end,
},
};
}
}
if (filter.overall_scoreRange) {
const [start, end] = filter.overall_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
overall_score: {
...where.overall_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
overall_score: {
...where.overall_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.assessment_type) {
where = {
...where,
assessment_type: filter.assessment_type,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.knowledge_gap_assessments.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'knowledge_gap_assessments',
'assessment_type',
query,
),
],
};
}
const records = await db.knowledge_gap_assessments.findAll({
attributes: [ 'id', 'assessment_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['assessment_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.assessment_type,
}));
}
};

View File

@ -0,0 +1,575 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Kpi_definitionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const kpi_definitions = await db.kpi_definitions.create(
{
id: data.id || undefined,
kpi_name: data.kpi_name
||
null
,
kpi_key: data.kpi_key
||
null
,
unit: data.unit
||
null
,
direction: data.direction
||
null
,
target_value: data.target_value
||
null
,
description: data.description
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await kpi_definitions.setOrganization(currentUser.organization.id || null, {
transaction,
});
return kpi_definitions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const kpi_definitionsData = data.map((item, index) => ({
id: item.id || undefined,
kpi_name: item.kpi_name
||
null
,
kpi_key: item.kpi_key
||
null
,
unit: item.unit
||
null
,
direction: item.direction
||
null
,
target_value: item.target_value
||
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 kpi_definitions = await db.kpi_definitions.bulkCreate(kpi_definitionsData, { transaction });
// For each item created, replace relation files
return kpi_definitions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const kpi_definitions = await db.kpi_definitions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.kpi_name !== undefined) updatePayload.kpi_name = data.kpi_name;
if (data.kpi_key !== undefined) updatePayload.kpi_key = data.kpi_key;
if (data.unit !== undefined) updatePayload.unit = data.unit;
if (data.direction !== undefined) updatePayload.direction = data.direction;
if (data.target_value !== undefined) updatePayload.target_value = data.target_value;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await kpi_definitions.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await kpi_definitions.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
return kpi_definitions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const kpi_definitions = await db.kpi_definitions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of kpi_definitions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of kpi_definitions) {
await record.destroy({transaction});
}
});
return kpi_definitions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const kpi_definitions = await db.kpi_definitions.findByPk(id, options);
await kpi_definitions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await kpi_definitions.destroy({
transaction
});
return kpi_definitions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const kpi_definitions = await db.kpi_definitions.findOne(
{ where },
{ transaction },
);
if (!kpi_definitions) {
return kpi_definitions;
}
const output = kpi_definitions.get({plain: true});
output.kpi_measurements_kpi_definition = await kpi_definitions.getKpi_measurements_kpi_definition({
transaction
});
output.organization = await kpi_definitions.getOrganization({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.kpi_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'kpi_definitions',
'kpi_name',
filter.kpi_name,
),
};
}
if (filter.kpi_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'kpi_definitions',
'kpi_key',
filter.kpi_key,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'kpi_definitions',
'description',
filter.description,
),
};
}
if (filter.target_valueRange) {
const [start, end] = filter.target_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.unit) {
where = {
...where,
unit: filter.unit,
};
}
if (filter.direction) {
where = {
...where,
direction: filter.direction,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.kpi_definitions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'kpi_definitions',
'kpi_name',
query,
),
],
};
}
const records = await db.kpi_definitions.findAll({
attributes: [ 'id', 'kpi_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['kpi_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.kpi_name,
}));
}
};

View File

@ -0,0 +1,592 @@
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 Kpi_measurementsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const kpi_measurements = await db.kpi_measurements.create(
{
id: data.id || undefined,
measured_at: data.measured_at
||
null
,
value: data.value
||
null
,
source: data.source
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await kpi_measurements.setKpi_definition( data.kpi_definition || null, {
transaction,
});
await kpi_measurements.setOrganization(currentUser.organization.id || null, {
transaction,
});
await kpi_measurements.setUser( data.user || null, {
transaction,
});
return kpi_measurements;
}
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 kpi_measurementsData = data.map((item, index) => ({
id: item.id || undefined,
measured_at: item.measured_at
||
null
,
value: item.value
||
null
,
source: item.source
||
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 kpi_measurements = await db.kpi_measurements.bulkCreate(kpi_measurementsData, { transaction });
// For each item created, replace relation files
return kpi_measurements;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const kpi_measurements = await db.kpi_measurements.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.measured_at !== undefined) updatePayload.measured_at = data.measured_at;
if (data.value !== undefined) updatePayload.value = data.value;
if (data.source !== undefined) updatePayload.source = data.source;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await kpi_measurements.update(updatePayload, {transaction});
if (data.kpi_definition !== undefined) {
await kpi_measurements.setKpi_definition(
data.kpi_definition,
{ transaction }
);
}
if (data.organization !== undefined) {
await kpi_measurements.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.user !== undefined) {
await kpi_measurements.setUser(
data.user,
{ transaction }
);
}
return kpi_measurements;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const kpi_measurements = await db.kpi_measurements.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of kpi_measurements) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of kpi_measurements) {
await record.destroy({transaction});
}
});
return kpi_measurements;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const kpi_measurements = await db.kpi_measurements.findByPk(id, options);
await kpi_measurements.update({
deletedBy: currentUser.id
}, {
transaction,
});
await kpi_measurements.destroy({
transaction
});
return kpi_measurements;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const kpi_measurements = await db.kpi_measurements.findOne(
{ where },
{ transaction },
);
if (!kpi_measurements) {
return kpi_measurements;
}
const output = kpi_measurements.get({plain: true});
output.kpi_definition = await kpi_measurements.getKpi_definition({
transaction
});
output.organization = await kpi_measurements.getOrganization({
transaction
});
output.user = await kpi_measurements.getUser({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.kpi_definitions,
as: 'kpi_definition',
where: filter.kpi_definition ? {
[Op.or]: [
{ id: { [Op.in]: filter.kpi_definition.split('|').map(term => Utils.uuid(term)) } },
{
kpi_name: {
[Op.or]: filter.kpi_definition.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organization',
},
{
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.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'kpi_measurements',
'notes',
filter.notes,
),
};
}
if (filter.measured_atRange) {
const [start, end] = filter.measured_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
measured_at: {
...where.measured_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
measured_at: {
...where.measured_at,
[Op.lte]: end,
},
};
}
}
if (filter.valueRange) {
const [start, end] = filter.valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
value: {
...where.value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
value: {
...where.value,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.source) {
where = {
...where,
source: filter.source,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.kpi_measurements.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'kpi_measurements',
'source',
query,
),
],
};
}
const records = await db.kpi_measurements.findAll({
attributes: [ 'id', 'source' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['source', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.source,
}));
}
};

View File

@ -0,0 +1,533 @@
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 Learning_pathsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const learning_paths = await db.learning_paths.create(
{
id: data.id || undefined,
path_name: data.path_name
||
null
,
audience: data.audience
||
null
,
description: data.description
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await learning_paths.setProgram( data.program || null, {
transaction,
});
await learning_paths.setOrganizations( data.organizations || null, {
transaction,
});
return learning_paths;
}
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 learning_pathsData = data.map((item, index) => ({
id: item.id || undefined,
path_name: item.path_name
||
null
,
audience: item.audience
||
null
,
description: item.description
||
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 learning_paths = await db.learning_paths.bulkCreate(learning_pathsData, { transaction });
// For each item created, replace relation files
return learning_paths;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const learning_paths = await db.learning_paths.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.path_name !== undefined) updatePayload.path_name = data.path_name;
if (data.audience !== undefined) updatePayload.audience = data.audience;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await learning_paths.update(updatePayload, {transaction});
if (data.program !== undefined) {
await learning_paths.setProgram(
data.program,
{ transaction }
);
}
if (data.organizations !== undefined) {
await learning_paths.setOrganizations(
data.organizations,
{ transaction }
);
}
return learning_paths;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const learning_paths = await db.learning_paths.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of learning_paths) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of learning_paths) {
await record.destroy({transaction});
}
});
return learning_paths;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const learning_paths = await db.learning_paths.findByPk(id, options);
await learning_paths.update({
deletedBy: currentUser.id
}, {
transaction,
});
await learning_paths.destroy({
transaction
});
return learning_paths;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const learning_paths = await db.learning_paths.findOne(
{ where },
{ transaction },
);
if (!learning_paths) {
return learning_paths;
}
const output = learning_paths.get({plain: true});
output.missions_learning_path = await learning_paths.getMissions_learning_path({
transaction
});
output.program = await learning_paths.getProgram({
transaction
});
output.organizations = await learning_paths.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.programs,
as: 'program',
where: filter.program ? {
[Op.or]: [
{ id: { [Op.in]: filter.program.split('|').map(term => Utils.uuid(term)) } },
{
program_name: {
[Op.or]: filter.program.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.path_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'learning_paths',
'path_name',
filter.path_name,
),
};
}
if (filter.audience) {
where = {
...where,
[Op.and]: Utils.ilike(
'learning_paths',
'audience',
filter.audience,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'learning_paths',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.learning_paths.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'learning_paths',
'path_name',
query,
),
],
};
}
const records = await db.learning_paths.findAll({
attributes: [ 'id', 'path_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['path_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.path_name,
}));
}
};

View File

@ -0,0 +1,757 @@
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 Mission_attemptsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mission_attempts = await db.mission_attempts.create(
{
id: data.id || undefined,
attempt_status: data.attempt_status
||
null
,
started_at: data.started_at
||
null
,
submitted_at: data.submitted_at
||
null
,
completed_at: data.completed_at
||
null
,
score: data.score
||
null
,
points_earned: data.points_earned
||
null
,
coins_earned: data.coins_earned
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await mission_attempts.setMission( data.mission || null, {
transaction,
});
await mission_attempts.setUser( data.user || null, {
transaction,
});
await mission_attempts.setEnrollment( data.enrollment || null, {
transaction,
});
await mission_attempts.setOrganizations( data.organizations || null, {
transaction,
});
return mission_attempts;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const mission_attemptsData = data.map((item, index) => ({
id: item.id || undefined,
attempt_status: item.attempt_status
||
null
,
started_at: item.started_at
||
null
,
submitted_at: item.submitted_at
||
null
,
completed_at: item.completed_at
||
null
,
score: item.score
||
null
,
points_earned: item.points_earned
||
null
,
coins_earned: item.coins_earned
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const mission_attempts = await db.mission_attempts.bulkCreate(mission_attemptsData, { transaction });
// For each item created, replace relation files
return mission_attempts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const mission_attempts = await db.mission_attempts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.attempt_status !== undefined) updatePayload.attempt_status = data.attempt_status;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.score !== undefined) updatePayload.score = data.score;
if (data.points_earned !== undefined) updatePayload.points_earned = data.points_earned;
if (data.coins_earned !== undefined) updatePayload.coins_earned = data.coins_earned;
updatePayload.updatedById = currentUser.id;
await mission_attempts.update(updatePayload, {transaction});
if (data.mission !== undefined) {
await mission_attempts.setMission(
data.mission,
{ transaction }
);
}
if (data.user !== undefined) {
await mission_attempts.setUser(
data.user,
{ transaction }
);
}
if (data.enrollment !== undefined) {
await mission_attempts.setEnrollment(
data.enrollment,
{ transaction }
);
}
if (data.organizations !== undefined) {
await mission_attempts.setOrganizations(
data.organizations,
{ transaction }
);
}
return mission_attempts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mission_attempts = await db.mission_attempts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of mission_attempts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of mission_attempts) {
await record.destroy({transaction});
}
});
return mission_attempts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mission_attempts = await db.mission_attempts.findByPk(id, options);
await mission_attempts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await mission_attempts.destroy({
transaction
});
return mission_attempts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const mission_attempts = await db.mission_attempts.findOne(
{ where },
{ transaction },
);
if (!mission_attempts) {
return mission_attempts;
}
const output = mission_attempts.get({plain: true});
output.quiz_submissions_mission_attempt = await mission_attempts.getQuiz_submissions_mission_attempt({
transaction
});
output.mission = await mission_attempts.getMission({
transaction
});
output.user = await mission_attempts.getUser({
transaction
});
output.enrollment = await mission_attempts.getEnrollment({
transaction
});
output.organizations = await mission_attempts.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.missions,
as: 'mission',
where: filter.mission ? {
[Op.or]: [
{ id: { [Op.in]: filter.mission.split('|').map(term => Utils.uuid(term)) } },
{
mission_title: {
[Op.or]: filter.mission.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.enrollments,
as: 'enrollment',
where: filter.enrollment ? {
[Op.or]: [
{ id: { [Op.in]: filter.enrollment.split('|').map(term => Utils.uuid(term)) } },
{
enrollment_status: {
[Op.or]: filter.enrollment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.submitted_atRange) {
const [start, end] = filter.submitted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.scoreRange) {
const [start, end] = filter.scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score: {
...where.score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score: {
...where.score,
[Op.lte]: end,
},
};
}
}
if (filter.points_earnedRange) {
const [start, end] = filter.points_earnedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
points_earned: {
...where.points_earned,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
points_earned: {
...where.points_earned,
[Op.lte]: end,
},
};
}
}
if (filter.coins_earnedRange) {
const [start, end] = filter.coins_earnedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
coins_earned: {
...where.coins_earned,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
coins_earned: {
...where.coins_earned,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.attempt_status) {
where = {
...where,
attempt_status: filter.attempt_status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.mission_attempts.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'mission_attempts',
'attempt_status',
query,
),
],
};
}
const records = await db.mission_attempts.findAll({
attributes: [ 'id', 'attempt_status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['attempt_status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.attempt_status,
}));
}
};

View File

@ -0,0 +1,797 @@
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 MissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const missions = await db.missions.create(
{
id: data.id || undefined,
mission_title: data.mission_title
||
null
,
mission_code: data.mission_code
||
null
,
mission_type: data.mission_type
||
null
,
sequence_order: data.sequence_order
||
null
,
estimated_minutes: data.estimated_minutes
||
null
,
instructions: data.instructions
||
null
,
video_url: data.video_url
||
null
,
is_required: data.is_required
||
false
,
points_awarded: data.points_awarded
||
null
,
coins_awarded: data.coins_awarded
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await missions.setLearning_path( data.learning_path || null, {
transaction,
});
await missions.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.missions.getTableName(),
belongsToColumn: 'resource_files',
belongsToId: missions.id,
},
data.resource_files,
options,
);
return missions;
}
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 missionsData = data.map((item, index) => ({
id: item.id || undefined,
mission_title: item.mission_title
||
null
,
mission_code: item.mission_code
||
null
,
mission_type: item.mission_type
||
null
,
sequence_order: item.sequence_order
||
null
,
estimated_minutes: item.estimated_minutes
||
null
,
instructions: item.instructions
||
null
,
video_url: item.video_url
||
null
,
is_required: item.is_required
||
false
,
points_awarded: item.points_awarded
||
null
,
coins_awarded: item.coins_awarded
||
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 missions = await db.missions.bulkCreate(missionsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < missions.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.missions.getTableName(),
belongsToColumn: 'resource_files',
belongsToId: missions[i].id,
},
data[i].resource_files,
options,
);
}
return missions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const missions = await db.missions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.mission_title !== undefined) updatePayload.mission_title = data.mission_title;
if (data.mission_code !== undefined) updatePayload.mission_code = data.mission_code;
if (data.mission_type !== undefined) updatePayload.mission_type = data.mission_type;
if (data.sequence_order !== undefined) updatePayload.sequence_order = data.sequence_order;
if (data.estimated_minutes !== undefined) updatePayload.estimated_minutes = data.estimated_minutes;
if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
if (data.video_url !== undefined) updatePayload.video_url = data.video_url;
if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
if (data.points_awarded !== undefined) updatePayload.points_awarded = data.points_awarded;
if (data.coins_awarded !== undefined) updatePayload.coins_awarded = data.coins_awarded;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await missions.update(updatePayload, {transaction});
if (data.learning_path !== undefined) {
await missions.setLearning_path(
data.learning_path,
{ transaction }
);
}
if (data.organizations !== undefined) {
await missions.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.missions.getTableName(),
belongsToColumn: 'resource_files',
belongsToId: missions.id,
},
data.resource_files,
options,
);
return missions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const missions = await db.missions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of missions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of missions) {
await record.destroy({transaction});
}
});
return missions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const missions = await db.missions.findByPk(id, options);
await missions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await missions.destroy({
transaction
});
return missions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const missions = await db.missions.findOne(
{ where },
{ transaction },
);
if (!missions) {
return missions;
}
const output = missions.get({plain: true});
output.mission_attempts_mission = await missions.getMission_attempts_mission({
transaction
});
output.quizzes_mission = await missions.getQuizzes_mission({
transaction
});
output.simulations_mission = await missions.getSimulations_mission({
transaction
});
output.learning_path = await missions.getLearning_path({
transaction
});
output.resource_files = await missions.getResource_files({
transaction
});
output.organizations = await missions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.learning_paths,
as: 'learning_path',
where: filter.learning_path ? {
[Op.or]: [
{ id: { [Op.in]: filter.learning_path.split('|').map(term => Utils.uuid(term)) } },
{
path_name: {
[Op.or]: filter.learning_path.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'resource_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.mission_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'missions',
'mission_title',
filter.mission_title,
),
};
}
if (filter.mission_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'missions',
'mission_code',
filter.mission_code,
),
};
}
if (filter.instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'missions',
'instructions',
filter.instructions,
),
};
}
if (filter.video_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'missions',
'video_url',
filter.video_url,
),
};
}
if (filter.sequence_orderRange) {
const [start, end] = filter.sequence_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.lte]: end,
},
};
}
}
if (filter.estimated_minutesRange) {
const [start, end] = filter.estimated_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_minutes: {
...where.estimated_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_minutes: {
...where.estimated_minutes,
[Op.lte]: end,
},
};
}
}
if (filter.points_awardedRange) {
const [start, end] = filter.points_awardedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
points_awarded: {
...where.points_awarded,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
points_awarded: {
...where.points_awarded,
[Op.lte]: end,
},
};
}
}
if (filter.coins_awardedRange) {
const [start, end] = filter.coins_awardedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
coins_awarded: {
...where.coins_awarded,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
coins_awarded: {
...where.coins_awarded,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.mission_type) {
where = {
...where,
mission_type: filter.mission_type,
};
}
if (filter.is_required) {
where = {
...where,
is_required: filter.is_required,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.missions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'missions',
'mission_title',
query,
),
],
};
}
const records = await db.missions.findAll({
attributes: [ 'id', 'mission_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['mission_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.mission_title,
}));
}
};

View File

@ -0,0 +1,551 @@
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 OrganizationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return organizations;
}
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 organizationsData = 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 organizations = await db.organizations.bulkCreate(organizationsData, { transaction });
// For each item created, replace relation files
return organizations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const organizations = await db.organizations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await organizations.update(updatePayload, {transaction});
return organizations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of organizations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of organizations) {
await record.destroy({transaction});
}
});
return organizations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findByPk(id, options);
await organizations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await organizations.destroy({
transaction
});
return organizations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findOne(
{ where },
{ transaction },
);
if (!organizations) {
return organizations;
}
const output = organizations.get({plain: true});
output.users_organizations = await organizations.getUsers_organizations({
transaction
});
output.role_permissions_organizations = await organizations.getRole_permissions_organizations({
transaction
});
output.role_assignments_organization = await organizations.getRole_assignments_organization({
transaction
});
output.teams_organization = await organizations.getTeams_organization({
transaction
});
output.team_memberships_organizations = await organizations.getTeam_memberships_organizations({
transaction
});
output.programs_organization = await organizations.getPrograms_organization({
transaction
});
output.learning_paths_organizations = await organizations.getLearning_paths_organizations({
transaction
});
output.missions_organizations = await organizations.getMissions_organizations({
transaction
});
output.checklists_organizations = await organizations.getChecklists_organizations({
transaction
});
output.checklist_items_organizations = await organizations.getChecklist_items_organizations({
transaction
});
output.enrollments_organization = await organizations.getEnrollments_organization({
transaction
});
output.mission_attempts_organizations = await organizations.getMission_attempts_organizations({
transaction
});
output.quizzes_organizations = await organizations.getQuizzes_organizations({
transaction
});
output.quiz_questions_organizations = await organizations.getQuiz_questions_organizations({
transaction
});
output.quiz_choices_organizations = await organizations.getQuiz_choices_organizations({
transaction
});
output.quiz_submissions_organizations = await organizations.getQuiz_submissions_organizations({
transaction
});
output.quiz_answers_organizations = await organizations.getQuiz_answers_organizations({
transaction
});
output.simulations_organizations = await organizations.getSimulations_organizations({
transaction
});
output.simulation_steps_organizations = await organizations.getSimulation_steps_organizations({
transaction
});
output.content_assets_organization = await organizations.getContent_assets_organization({
transaction
});
output.ai_content_requests_organization = await organizations.getAi_content_requests_organization({
transaction
});
output.knowledge_gap_assessments_organization = await organizations.getKnowledge_gap_assessments_organization({
transaction
});
output.badges_organization = await organizations.getBadges_organization({
transaction
});
output.user_badges_organizations = await organizations.getUser_badges_organizations({
transaction
});
output.point_ledger_entries_organization = await organizations.getPoint_ledger_entries_organization({
transaction
});
output.challenges_organization = await organizations.getChallenges_organization({
transaction
});
output.challenge_participants_organizations = await organizations.getChallenge_participants_organizations({
transaction
});
output.reward_catalog_items_organization = await organizations.getReward_catalog_items_organization({
transaction
});
output.reward_redemptions_organization = await organizations.getReward_redemptions_organization({
transaction
});
output.recognition_posts_organization = await organizations.getRecognition_posts_organization({
transaction
});
output.coaching_sessions_organization = await organizations.getCoaching_sessions_organization({
transaction
});
output.kpi_definitions_organization = await organizations.getKpi_definitions_organization({
transaction
});
output.kpi_measurements_organization = await organizations.getKpi_measurements_organization({
transaction
});
output.qa_evaluations_organization = await organizations.getQa_evaluations_organization({
transaction
});
output.qa_scorecards_organizations = await organizations.getQa_scorecards_organizations({
transaction
});
output.surveys_organization = await organizations.getSurveys_organization({
transaction
});
output.survey_questions_organizations = await organizations.getSurvey_questions_organizations({
transaction
});
output.survey_responses_organization = await organizations.getSurvey_responses_organization({
transaction
});
output.survey_response_items_organizations = await organizations.getSurvey_response_items_organizations({
transaction
});
output.reports_organization = await organizations.getReports_organization({
transaction
});
output.audit_events_organization = await organizations.getAudit_events_organization({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
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(
'organizations',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.organizations.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'organizations',
'name',
query,
),
],
};
}
const records = await db.organizations.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,377 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PermissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return permissions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const permissionsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const permissions = await db.permissions.bulkCreate(permissionsData, { transaction });
// For each item created, replace relation files
return permissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const permissions = await db.permissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await permissions.update(updatePayload, {transaction});
return permissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of permissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of permissions) {
await record.destroy({transaction});
}
});
return permissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findByPk(id, options);
await permissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await permissions.destroy({
transaction
});
return permissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findOne(
{ where },
{ transaction },
);
if (!permissions) {
return permissions;
}
const output = permissions.get({plain: true});
output.role_permissions_permission = await permissions.getRole_permissions_permission({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'permissions',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.permissions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'permissions',
'name',
query,
),
],
};
}
const records = await db.permissions.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,592 @@
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 Point_ledger_entriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const point_ledger_entries = await db.point_ledger_entries.create(
{
id: data.id || undefined,
entry_type: data.entry_type
||
null
,
points_delta: data.points_delta
||
null
,
coins_delta: data.coins_delta
||
null
,
reason: data.reason
||
null
,
occurred_at: data.occurred_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await point_ledger_entries.setOrganization(currentUser.organization.id || null, {
transaction,
});
await point_ledger_entries.setUser( data.user || null, {
transaction,
});
return point_ledger_entries;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const point_ledger_entriesData = data.map((item, index) => ({
id: item.id || undefined,
entry_type: item.entry_type
||
null
,
points_delta: item.points_delta
||
null
,
coins_delta: item.coins_delta
||
null
,
reason: item.reason
||
null
,
occurred_at: item.occurred_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const point_ledger_entries = await db.point_ledger_entries.bulkCreate(point_ledger_entriesData, { transaction });
// For each item created, replace relation files
return point_ledger_entries;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const point_ledger_entries = await db.point_ledger_entries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.entry_type !== undefined) updatePayload.entry_type = data.entry_type;
if (data.points_delta !== undefined) updatePayload.points_delta = data.points_delta;
if (data.coins_delta !== undefined) updatePayload.coins_delta = data.coins_delta;
if (data.reason !== undefined) updatePayload.reason = data.reason;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
updatePayload.updatedById = currentUser.id;
await point_ledger_entries.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await point_ledger_entries.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.user !== undefined) {
await point_ledger_entries.setUser(
data.user,
{ transaction }
);
}
return point_ledger_entries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const point_ledger_entries = await db.point_ledger_entries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of point_ledger_entries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of point_ledger_entries) {
await record.destroy({transaction});
}
});
return point_ledger_entries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const point_ledger_entries = await db.point_ledger_entries.findByPk(id, options);
await point_ledger_entries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await point_ledger_entries.destroy({
transaction
});
return point_ledger_entries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const point_ledger_entries = await db.point_ledger_entries.findOne(
{ where },
{ transaction },
);
if (!point_ledger_entries) {
return point_ledger_entries;
}
const output = point_ledger_entries.get({plain: true});
output.organization = await point_ledger_entries.getOrganization({
transaction
});
output.user = await point_ledger_entries.getUser({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
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.reason) {
where = {
...where,
[Op.and]: Utils.ilike(
'point_ledger_entries',
'reason',
filter.reason,
),
};
}
if (filter.points_deltaRange) {
const [start, end] = filter.points_deltaRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
points_delta: {
...where.points_delta,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
points_delta: {
...where.points_delta,
[Op.lte]: end,
},
};
}
}
if (filter.coins_deltaRange) {
const [start, end] = filter.coins_deltaRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
coins_delta: {
...where.coins_delta,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
coins_delta: {
...where.coins_delta,
[Op.lte]: end,
},
};
}
}
if (filter.occurred_atRange) {
const [start, end] = filter.occurred_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.entry_type) {
where = {
...where,
entry_type: filter.entry_type,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.point_ledger_entries.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'point_ledger_entries',
'reason',
query,
),
],
};
}
const records = await db.point_ledger_entries.findAll({
attributes: [ 'id', 'reason' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reason', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reason,
}));
}
};

View File

@ -0,0 +1,539 @@
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 ProgramsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const programs = await db.programs.create(
{
id: data.id || undefined,
program_name: data.program_name
||
null
,
program_type: data.program_type
||
null
,
description: data.description
||
null
,
is_published: data.is_published
||
false
,
published_at: data.published_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await programs.setOrganization(currentUser.organization.id || null, {
transaction,
});
return programs;
}
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 programsData = data.map((item, index) => ({
id: item.id || undefined,
program_name: item.program_name
||
null
,
program_type: item.program_type
||
null
,
description: item.description
||
null
,
is_published: item.is_published
||
false
,
published_at: item.published_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const programs = await db.programs.bulkCreate(programsData, { transaction });
// For each item created, replace relation files
return programs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const programs = await db.programs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.program_name !== undefined) updatePayload.program_name = data.program_name;
if (data.program_type !== undefined) updatePayload.program_type = data.program_type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
updatePayload.updatedById = currentUser.id;
await programs.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await programs.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
return programs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const programs = await db.programs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of programs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of programs) {
await record.destroy({transaction});
}
});
return programs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const programs = await db.programs.findByPk(id, options);
await programs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await programs.destroy({
transaction
});
return programs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const programs = await db.programs.findOne(
{ where },
{ transaction },
);
if (!programs) {
return programs;
}
const output = programs.get({plain: true});
output.learning_paths_program = await programs.getLearning_paths_program({
transaction
});
output.checklists_program = await programs.getChecklists_program({
transaction
});
output.enrollments_program = await programs.getEnrollments_program({
transaction
});
output.organization = await programs.getOrganization({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.program_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'programs',
'program_name',
filter.program_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'programs',
'description',
filter.description,
),
};
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.program_type) {
where = {
...where,
program_type: filter.program_type,
};
}
if (filter.is_published) {
where = {
...where,
is_published: filter.is_published,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.programs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'programs',
'program_name',
query,
),
],
};
}
const records = await db.programs.findAll({
attributes: [ 'id', 'program_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['program_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.program_name,
}));
}
};

View File

@ -0,0 +1,677 @@
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 Qa_evaluationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_evaluations = await db.qa_evaluations.create(
{
id: data.id || undefined,
channel: data.channel
||
null
,
interaction_reference: data.interaction_reference
||
null
,
interaction_at: data.interaction_at
||
null
,
evaluated_at: data.evaluated_at
||
null
,
overall_score: data.overall_score
||
null
,
result: data.result
||
null
,
summary_notes: data.summary_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await qa_evaluations.setOrganization(currentUser.organization.id || null, {
transaction,
});
await qa_evaluations.setEvaluator( data.evaluator || null, {
transaction,
});
await qa_evaluations.setAgent( data.agent || null, {
transaction,
});
return qa_evaluations;
}
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 qa_evaluationsData = data.map((item, index) => ({
id: item.id || undefined,
channel: item.channel
||
null
,
interaction_reference: item.interaction_reference
||
null
,
interaction_at: item.interaction_at
||
null
,
evaluated_at: item.evaluated_at
||
null
,
overall_score: item.overall_score
||
null
,
result: item.result
||
null
,
summary_notes: item.summary_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const qa_evaluations = await db.qa_evaluations.bulkCreate(qa_evaluationsData, { transaction });
// For each item created, replace relation files
return qa_evaluations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const qa_evaluations = await db.qa_evaluations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.interaction_reference !== undefined) updatePayload.interaction_reference = data.interaction_reference;
if (data.interaction_at !== undefined) updatePayload.interaction_at = data.interaction_at;
if (data.evaluated_at !== undefined) updatePayload.evaluated_at = data.evaluated_at;
if (data.overall_score !== undefined) updatePayload.overall_score = data.overall_score;
if (data.result !== undefined) updatePayload.result = data.result;
if (data.summary_notes !== undefined) updatePayload.summary_notes = data.summary_notes;
updatePayload.updatedById = currentUser.id;
await qa_evaluations.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await qa_evaluations.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.evaluator !== undefined) {
await qa_evaluations.setEvaluator(
data.evaluator,
{ transaction }
);
}
if (data.agent !== undefined) {
await qa_evaluations.setAgent(
data.agent,
{ transaction }
);
}
return qa_evaluations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_evaluations = await db.qa_evaluations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of qa_evaluations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of qa_evaluations) {
await record.destroy({transaction});
}
});
return qa_evaluations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const qa_evaluations = await db.qa_evaluations.findByPk(id, options);
await qa_evaluations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await qa_evaluations.destroy({
transaction
});
return qa_evaluations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const qa_evaluations = await db.qa_evaluations.findOne(
{ where },
{ transaction },
);
if (!qa_evaluations) {
return qa_evaluations;
}
const output = qa_evaluations.get({plain: true});
output.qa_scorecards_qa_evaluation = await qa_evaluations.getQa_scorecards_qa_evaluation({
transaction
});
output.organization = await qa_evaluations.getOrganization({
transaction
});
output.evaluator = await qa_evaluations.getEvaluator({
transaction
});
output.agent = await qa_evaluations.getAgent({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.users,
as: 'evaluator',
where: filter.evaluator ? {
[Op.or]: [
{ id: { [Op.in]: filter.evaluator.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.evaluator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'agent',
where: filter.agent ? {
[Op.or]: [
{ id: { [Op.in]: filter.agent.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.agent.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.interaction_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_evaluations',
'interaction_reference',
filter.interaction_reference,
),
};
}
if (filter.summary_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_evaluations',
'summary_notes',
filter.summary_notes,
),
};
}
if (filter.interaction_atRange) {
const [start, end] = filter.interaction_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
interaction_at: {
...where.interaction_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
interaction_at: {
...where.interaction_at,
[Op.lte]: end,
},
};
}
}
if (filter.evaluated_atRange) {
const [start, end] = filter.evaluated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
evaluated_at: {
...where.evaluated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
evaluated_at: {
...where.evaluated_at,
[Op.lte]: end,
},
};
}
}
if (filter.overall_scoreRange) {
const [start, end] = filter.overall_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
overall_score: {
...where.overall_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
overall_score: {
...where.overall_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.channel) {
where = {
...where,
channel: filter.channel,
};
}
if (filter.result) {
where = {
...where,
result: filter.result,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.qa_evaluations.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'qa_evaluations',
'interaction_reference',
query,
),
],
};
}
const records = await db.qa_evaluations.findAll({
attributes: [ 'id', 'interaction_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['interaction_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.interaction_reference,
}));
}
};

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 Qa_scorecardsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_scorecards = await db.qa_scorecards.create(
{
id: data.id || undefined,
category_name: data.category_name
||
null
,
category_score: data.category_score
||
null
,
max_score: data.max_score
||
null
,
comments: data.comments
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await qa_scorecards.setQa_evaluation( data.qa_evaluation || null, {
transaction,
});
await qa_scorecards.setOrganizations( data.organizations || null, {
transaction,
});
return qa_scorecards;
}
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 qa_scorecardsData = data.map((item, index) => ({
id: item.id || undefined,
category_name: item.category_name
||
null
,
category_score: item.category_score
||
null
,
max_score: item.max_score
||
null
,
comments: item.comments
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const qa_scorecards = await db.qa_scorecards.bulkCreate(qa_scorecardsData, { transaction });
// For each item created, replace relation files
return qa_scorecards;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const qa_scorecards = await db.qa_scorecards.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.category_name !== undefined) updatePayload.category_name = data.category_name;
if (data.category_score !== undefined) updatePayload.category_score = data.category_score;
if (data.max_score !== undefined) updatePayload.max_score = data.max_score;
if (data.comments !== undefined) updatePayload.comments = data.comments;
updatePayload.updatedById = currentUser.id;
await qa_scorecards.update(updatePayload, {transaction});
if (data.qa_evaluation !== undefined) {
await qa_scorecards.setQa_evaluation(
data.qa_evaluation,
{ transaction }
);
}
if (data.organizations !== undefined) {
await qa_scorecards.setOrganizations(
data.organizations,
{ transaction }
);
}
return qa_scorecards;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_scorecards = await db.qa_scorecards.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of qa_scorecards) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of qa_scorecards) {
await record.destroy({transaction});
}
});
return qa_scorecards;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const qa_scorecards = await db.qa_scorecards.findByPk(id, options);
await qa_scorecards.update({
deletedBy: currentUser.id
}, {
transaction,
});
await qa_scorecards.destroy({
transaction
});
return qa_scorecards;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const qa_scorecards = await db.qa_scorecards.findOne(
{ where },
{ transaction },
);
if (!qa_scorecards) {
return qa_scorecards;
}
const output = qa_scorecards.get({plain: true});
output.qa_evaluation = await qa_scorecards.getQa_evaluation({
transaction
});
output.organizations = await qa_scorecards.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.qa_evaluations,
as: 'qa_evaluation',
where: filter.qa_evaluation ? {
[Op.or]: [
{ id: { [Op.in]: filter.qa_evaluation.split('|').map(term => Utils.uuid(term)) } },
{
interaction_reference: {
[Op.or]: filter.qa_evaluation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.category_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_scorecards',
'category_name',
filter.category_name,
),
};
}
if (filter.comments) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_scorecards',
'comments',
filter.comments,
),
};
}
if (filter.category_scoreRange) {
const [start, end] = filter.category_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
category_score: {
...where.category_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
category_score: {
...where.category_score,
[Op.lte]: end,
},
};
}
}
if (filter.max_scoreRange) {
const [start, end] = filter.max_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_score: {
...where.max_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_score: {
...where.max_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.qa_scorecards.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'qa_scorecards',
'category_name',
query,
),
],
};
}
const records = await db.qa_scorecards.findAll({
attributes: [ 'id', 'category_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['category_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.category_name,
}));
}
};

View File

@ -0,0 +1,557 @@
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 Quiz_answersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quiz_answers = await db.quiz_answers.create(
{
id: data.id || undefined,
answer_text: data.answer_text
||
null
,
is_correct: data.is_correct
||
false
,
points_earned: data.points_earned
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await quiz_answers.setQuiz_submission( data.quiz_submission || null, {
transaction,
});
await quiz_answers.setQuiz_question( data.quiz_question || null, {
transaction,
});
await quiz_answers.setOrganizations( data.organizations || null, {
transaction,
});
return quiz_answers;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const quiz_answersData = data.map((item, index) => ({
id: item.id || undefined,
answer_text: item.answer_text
||
null
,
is_correct: item.is_correct
||
false
,
points_earned: item.points_earned
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const quiz_answers = await db.quiz_answers.bulkCreate(quiz_answersData, { transaction });
// For each item created, replace relation files
return quiz_answers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const quiz_answers = await db.quiz_answers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.answer_text !== undefined) updatePayload.answer_text = data.answer_text;
if (data.is_correct !== undefined) updatePayload.is_correct = data.is_correct;
if (data.points_earned !== undefined) updatePayload.points_earned = data.points_earned;
updatePayload.updatedById = currentUser.id;
await quiz_answers.update(updatePayload, {transaction});
if (data.quiz_submission !== undefined) {
await quiz_answers.setQuiz_submission(
data.quiz_submission,
{ transaction }
);
}
if (data.quiz_question !== undefined) {
await quiz_answers.setQuiz_question(
data.quiz_question,
{ transaction }
);
}
if (data.organizations !== undefined) {
await quiz_answers.setOrganizations(
data.organizations,
{ transaction }
);
}
return quiz_answers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quiz_answers = await db.quiz_answers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of quiz_answers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of quiz_answers) {
await record.destroy({transaction});
}
});
return quiz_answers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const quiz_answers = await db.quiz_answers.findByPk(id, options);
await quiz_answers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await quiz_answers.destroy({
transaction
});
return quiz_answers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const quiz_answers = await db.quiz_answers.findOne(
{ where },
{ transaction },
);
if (!quiz_answers) {
return quiz_answers;
}
const output = quiz_answers.get({plain: true});
output.quiz_submission = await quiz_answers.getQuiz_submission({
transaction
});
output.quiz_question = await quiz_answers.getQuiz_question({
transaction
});
output.organizations = await quiz_answers.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.quiz_submissions,
as: 'quiz_submission',
where: filter.quiz_submission ? {
[Op.or]: [
{ id: { [Op.in]: filter.quiz_submission.split('|').map(term => Utils.uuid(term)) } },
{
submitted_at: {
[Op.or]: filter.quiz_submission.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.quiz_questions,
as: 'quiz_question',
where: filter.quiz_question ? {
[Op.or]: [
{ id: { [Op.in]: filter.quiz_question.split('|').map(term => Utils.uuid(term)) } },
{
prompt: {
[Op.or]: filter.quiz_question.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.answer_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'quiz_answers',
'answer_text',
filter.answer_text,
),
};
}
if (filter.points_earnedRange) {
const [start, end] = filter.points_earnedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
points_earned: {
...where.points_earned,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
points_earned: {
...where.points_earned,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_correct) {
where = {
...where,
is_correct: filter.is_correct,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.quiz_answers.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'quiz_answers',
'answer_text',
query,
),
],
};
}
const records = await db.quiz_answers.findAll({
attributes: [ 'id', 'answer_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['answer_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.answer_text,
}));
}
};

View File

@ -0,0 +1,520 @@
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 Quiz_choicesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quiz_choices = await db.quiz_choices.create(
{
id: data.id || undefined,
choice_text: data.choice_text
||
null
,
is_correct: data.is_correct
||
false
,
sequence_order: data.sequence_order
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await quiz_choices.setQuiz_question( data.quiz_question || null, {
transaction,
});
await quiz_choices.setOrganizations( data.organizations || null, {
transaction,
});
return quiz_choices;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const quiz_choicesData = data.map((item, index) => ({
id: item.id || undefined,
choice_text: item.choice_text
||
null
,
is_correct: item.is_correct
||
false
,
sequence_order: item.sequence_order
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const quiz_choices = await db.quiz_choices.bulkCreate(quiz_choicesData, { transaction });
// For each item created, replace relation files
return quiz_choices;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const quiz_choices = await db.quiz_choices.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.choice_text !== undefined) updatePayload.choice_text = data.choice_text;
if (data.is_correct !== undefined) updatePayload.is_correct = data.is_correct;
if (data.sequence_order !== undefined) updatePayload.sequence_order = data.sequence_order;
updatePayload.updatedById = currentUser.id;
await quiz_choices.update(updatePayload, {transaction});
if (data.quiz_question !== undefined) {
await quiz_choices.setQuiz_question(
data.quiz_question,
{ transaction }
);
}
if (data.organizations !== undefined) {
await quiz_choices.setOrganizations(
data.organizations,
{ transaction }
);
}
return quiz_choices;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quiz_choices = await db.quiz_choices.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of quiz_choices) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of quiz_choices) {
await record.destroy({transaction});
}
});
return quiz_choices;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const quiz_choices = await db.quiz_choices.findByPk(id, options);
await quiz_choices.update({
deletedBy: currentUser.id
}, {
transaction,
});
await quiz_choices.destroy({
transaction
});
return quiz_choices;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const quiz_choices = await db.quiz_choices.findOne(
{ where },
{ transaction },
);
if (!quiz_choices) {
return quiz_choices;
}
const output = quiz_choices.get({plain: true});
output.quiz_question = await quiz_choices.getQuiz_question({
transaction
});
output.organizations = await quiz_choices.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.quiz_questions,
as: 'quiz_question',
where: filter.quiz_question ? {
[Op.or]: [
{ id: { [Op.in]: filter.quiz_question.split('|').map(term => Utils.uuid(term)) } },
{
prompt: {
[Op.or]: filter.quiz_question.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.choice_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'quiz_choices',
'choice_text',
filter.choice_text,
),
};
}
if (filter.sequence_orderRange) {
const [start, end] = filter.sequence_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_correct) {
where = {
...where,
is_correct: filter.is_correct,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.quiz_choices.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'quiz_choices',
'choice_text',
query,
),
],
};
}
const records = await db.quiz_choices.findAll({
attributes: [ 'id', 'choice_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['choice_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.choice_text,
}));
}
};

View File

@ -0,0 +1,563 @@
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 Quiz_questionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quiz_questions = await db.quiz_questions.create(
{
id: data.id || undefined,
question_type: data.question_type
||
null
,
prompt: data.prompt
||
null
,
sequence_order: data.sequence_order
||
null
,
points: data.points
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await quiz_questions.setQuiz( data.quiz || null, {
transaction,
});
await quiz_questions.setOrganizations( data.organizations || null, {
transaction,
});
return quiz_questions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const quiz_questionsData = data.map((item, index) => ({
id: item.id || undefined,
question_type: item.question_type
||
null
,
prompt: item.prompt
||
null
,
sequence_order: item.sequence_order
||
null
,
points: item.points
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const quiz_questions = await db.quiz_questions.bulkCreate(quiz_questionsData, { transaction });
// For each item created, replace relation files
return quiz_questions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const quiz_questions = await db.quiz_questions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.question_type !== undefined) updatePayload.question_type = data.question_type;
if (data.prompt !== undefined) updatePayload.prompt = data.prompt;
if (data.sequence_order !== undefined) updatePayload.sequence_order = data.sequence_order;
if (data.points !== undefined) updatePayload.points = data.points;
updatePayload.updatedById = currentUser.id;
await quiz_questions.update(updatePayload, {transaction});
if (data.quiz !== undefined) {
await quiz_questions.setQuiz(
data.quiz,
{ transaction }
);
}
if (data.organizations !== undefined) {
await quiz_questions.setOrganizations(
data.organizations,
{ transaction }
);
}
return quiz_questions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quiz_questions = await db.quiz_questions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of quiz_questions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of quiz_questions) {
await record.destroy({transaction});
}
});
return quiz_questions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const quiz_questions = await db.quiz_questions.findByPk(id, options);
await quiz_questions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await quiz_questions.destroy({
transaction
});
return quiz_questions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const quiz_questions = await db.quiz_questions.findOne(
{ where },
{ transaction },
);
if (!quiz_questions) {
return quiz_questions;
}
const output = quiz_questions.get({plain: true});
output.quiz_choices_quiz_question = await quiz_questions.getQuiz_choices_quiz_question({
transaction
});
output.quiz_answers_quiz_question = await quiz_questions.getQuiz_answers_quiz_question({
transaction
});
output.quiz = await quiz_questions.getQuiz({
transaction
});
output.organizations = await quiz_questions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.quizzes,
as: 'quiz',
where: filter.quiz ? {
[Op.or]: [
{ id: { [Op.in]: filter.quiz.split('|').map(term => Utils.uuid(term)) } },
{
quiz_title: {
[Op.or]: filter.quiz.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.prompt) {
where = {
...where,
[Op.and]: Utils.ilike(
'quiz_questions',
'prompt',
filter.prompt,
),
};
}
if (filter.sequence_orderRange) {
const [start, end] = filter.sequence_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.lte]: end,
},
};
}
}
if (filter.pointsRange) {
const [start, end] = filter.pointsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
points: {
...where.points,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
points: {
...where.points,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.question_type) {
where = {
...where,
question_type: filter.question_type,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.quiz_questions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'quiz_questions',
'prompt',
query,
),
],
};
}
const records = await db.quiz_questions.findAll({
attributes: [ 'id', 'prompt' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['prompt', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.prompt,
}));
}
};

View File

@ -0,0 +1,611 @@
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 Quiz_submissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quiz_submissions = await db.quiz_submissions.create(
{
id: data.id || undefined,
submitted_at: data.submitted_at
||
null
,
score: data.score
||
null
,
is_passed: data.is_passed
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await quiz_submissions.setQuiz( data.quiz || null, {
transaction,
});
await quiz_submissions.setUser( data.user || null, {
transaction,
});
await quiz_submissions.setMission_attempt( data.mission_attempt || null, {
transaction,
});
await quiz_submissions.setOrganizations( data.organizations || null, {
transaction,
});
return quiz_submissions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const quiz_submissionsData = data.map((item, index) => ({
id: item.id || undefined,
submitted_at: item.submitted_at
||
null
,
score: item.score
||
null
,
is_passed: item.is_passed
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const quiz_submissions = await db.quiz_submissions.bulkCreate(quiz_submissionsData, { transaction });
// For each item created, replace relation files
return quiz_submissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const quiz_submissions = await db.quiz_submissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
if (data.score !== undefined) updatePayload.score = data.score;
if (data.is_passed !== undefined) updatePayload.is_passed = data.is_passed;
updatePayload.updatedById = currentUser.id;
await quiz_submissions.update(updatePayload, {transaction});
if (data.quiz !== undefined) {
await quiz_submissions.setQuiz(
data.quiz,
{ transaction }
);
}
if (data.user !== undefined) {
await quiz_submissions.setUser(
data.user,
{ transaction }
);
}
if (data.mission_attempt !== undefined) {
await quiz_submissions.setMission_attempt(
data.mission_attempt,
{ transaction }
);
}
if (data.organizations !== undefined) {
await quiz_submissions.setOrganizations(
data.organizations,
{ transaction }
);
}
return quiz_submissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quiz_submissions = await db.quiz_submissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of quiz_submissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of quiz_submissions) {
await record.destroy({transaction});
}
});
return quiz_submissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const quiz_submissions = await db.quiz_submissions.findByPk(id, options);
await quiz_submissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await quiz_submissions.destroy({
transaction
});
return quiz_submissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const quiz_submissions = await db.quiz_submissions.findOne(
{ where },
{ transaction },
);
if (!quiz_submissions) {
return quiz_submissions;
}
const output = quiz_submissions.get({plain: true});
output.quiz_answers_quiz_submission = await quiz_submissions.getQuiz_answers_quiz_submission({
transaction
});
output.quiz = await quiz_submissions.getQuiz({
transaction
});
output.user = await quiz_submissions.getUser({
transaction
});
output.mission_attempt = await quiz_submissions.getMission_attempt({
transaction
});
output.organizations = await quiz_submissions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.quizzes,
as: 'quiz',
where: filter.quiz ? {
[Op.or]: [
{ id: { [Op.in]: filter.quiz.split('|').map(term => Utils.uuid(term)) } },
{
quiz_title: {
[Op.or]: filter.quiz.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.mission_attempts,
as: 'mission_attempt',
where: filter.mission_attempt ? {
[Op.or]: [
{ id: { [Op.in]: filter.mission_attempt.split('|').map(term => Utils.uuid(term)) } },
{
attempt_status: {
[Op.or]: filter.mission_attempt.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.submitted_atRange) {
const [start, end] = filter.submitted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.lte]: end,
},
};
}
}
if (filter.scoreRange) {
const [start, end] = filter.scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score: {
...where.score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score: {
...where.score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_passed) {
where = {
...where,
is_passed: filter.is_passed,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.quiz_submissions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'quiz_submissions',
'submitted_at',
query,
),
],
};
}
const records = await db.quiz_submissions.findAll({
attributes: [ 'id', 'submitted_at' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['submitted_at', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.submitted_at,
}));
}
};

View File

@ -0,0 +1,548 @@
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 QuizzesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quizzes = await db.quizzes.create(
{
id: data.id || undefined,
quiz_title: data.quiz_title
||
null
,
grading_method: data.grading_method
||
null
,
passing_score: data.passing_score
||
null
,
shuffle_questions: data.shuffle_questions
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await quizzes.setMission( data.mission || null, {
transaction,
});
await quizzes.setOrganizations( data.organizations || null, {
transaction,
});
return quizzes;
}
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 quizzesData = data.map((item, index) => ({
id: item.id || undefined,
quiz_title: item.quiz_title
||
null
,
grading_method: item.grading_method
||
null
,
passing_score: item.passing_score
||
null
,
shuffle_questions: item.shuffle_questions
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const quizzes = await db.quizzes.bulkCreate(quizzesData, { transaction });
// For each item created, replace relation files
return quizzes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const quizzes = await db.quizzes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.quiz_title !== undefined) updatePayload.quiz_title = data.quiz_title;
if (data.grading_method !== undefined) updatePayload.grading_method = data.grading_method;
if (data.passing_score !== undefined) updatePayload.passing_score = data.passing_score;
if (data.shuffle_questions !== undefined) updatePayload.shuffle_questions = data.shuffle_questions;
updatePayload.updatedById = currentUser.id;
await quizzes.update(updatePayload, {transaction});
if (data.mission !== undefined) {
await quizzes.setMission(
data.mission,
{ transaction }
);
}
if (data.organizations !== undefined) {
await quizzes.setOrganizations(
data.organizations,
{ transaction }
);
}
return quizzes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quizzes = await db.quizzes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of quizzes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of quizzes) {
await record.destroy({transaction});
}
});
return quizzes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const quizzes = await db.quizzes.findByPk(id, options);
await quizzes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await quizzes.destroy({
transaction
});
return quizzes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const quizzes = await db.quizzes.findOne(
{ where },
{ transaction },
);
if (!quizzes) {
return quizzes;
}
const output = quizzes.get({plain: true});
output.quiz_questions_quiz = await quizzes.getQuiz_questions_quiz({
transaction
});
output.quiz_submissions_quiz = await quizzes.getQuiz_submissions_quiz({
transaction
});
output.mission = await quizzes.getMission({
transaction
});
output.organizations = await quizzes.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.missions,
as: 'mission',
where: filter.mission ? {
[Op.or]: [
{ id: { [Op.in]: filter.mission.split('|').map(term => Utils.uuid(term)) } },
{
mission_title: {
[Op.or]: filter.mission.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.quiz_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'quizzes',
'quiz_title',
filter.quiz_title,
),
};
}
if (filter.passing_scoreRange) {
const [start, end] = filter.passing_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
passing_score: {
...where.passing_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
passing_score: {
...where.passing_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.grading_method) {
where = {
...where,
grading_method: filter.grading_method,
};
}
if (filter.shuffle_questions) {
where = {
...where,
shuffle_questions: filter.shuffle_questions,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.quizzes.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'quizzes',
'quiz_title',
query,
),
],
};
}
const records = await db.quizzes.findAll({
attributes: [ 'id', 'quiz_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['quiz_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.quiz_title,
}));
}
};

View File

@ -0,0 +1,693 @@
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 Recognition_postsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const recognition_posts = await db.recognition_posts.create(
{
id: data.id || undefined,
recognition_type: data.recognition_type
||
null
,
message: data.message
||
null
,
points_awarded: data.points_awarded
||
null
,
coins_awarded: data.coins_awarded
||
null
,
posted_at: data.posted_at
||
null
,
is_public: data.is_public
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await recognition_posts.setOrganization(currentUser.organization.id || null, {
transaction,
});
await recognition_posts.setFrom_user( data.from_user || null, {
transaction,
});
await recognition_posts.setTo_user( data.to_user || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.recognition_posts.getTableName(),
belongsToColumn: 'media_images',
belongsToId: recognition_posts.id,
},
data.media_images,
options,
);
return recognition_posts;
}
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 recognition_postsData = data.map((item, index) => ({
id: item.id || undefined,
recognition_type: item.recognition_type
||
null
,
message: item.message
||
null
,
points_awarded: item.points_awarded
||
null
,
coins_awarded: item.coins_awarded
||
null
,
posted_at: item.posted_at
||
null
,
is_public: item.is_public
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const recognition_posts = await db.recognition_posts.bulkCreate(recognition_postsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < recognition_posts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.recognition_posts.getTableName(),
belongsToColumn: 'media_images',
belongsToId: recognition_posts[i].id,
},
data[i].media_images,
options,
);
}
return recognition_posts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const recognition_posts = await db.recognition_posts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.recognition_type !== undefined) updatePayload.recognition_type = data.recognition_type;
if (data.message !== undefined) updatePayload.message = data.message;
if (data.points_awarded !== undefined) updatePayload.points_awarded = data.points_awarded;
if (data.coins_awarded !== undefined) updatePayload.coins_awarded = data.coins_awarded;
if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
updatePayload.updatedById = currentUser.id;
await recognition_posts.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await recognition_posts.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.from_user !== undefined) {
await recognition_posts.setFrom_user(
data.from_user,
{ transaction }
);
}
if (data.to_user !== undefined) {
await recognition_posts.setTo_user(
data.to_user,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.recognition_posts.getTableName(),
belongsToColumn: 'media_images',
belongsToId: recognition_posts.id,
},
data.media_images,
options,
);
return recognition_posts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const recognition_posts = await db.recognition_posts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of recognition_posts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of recognition_posts) {
await record.destroy({transaction});
}
});
return recognition_posts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const recognition_posts = await db.recognition_posts.findByPk(id, options);
await recognition_posts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await recognition_posts.destroy({
transaction
});
return recognition_posts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const recognition_posts = await db.recognition_posts.findOne(
{ where },
{ transaction },
);
if (!recognition_posts) {
return recognition_posts;
}
const output = recognition_posts.get({plain: true});
output.organization = await recognition_posts.getOrganization({
transaction
});
output.from_user = await recognition_posts.getFrom_user({
transaction
});
output.to_user = await recognition_posts.getTo_user({
transaction
});
output.media_images = await recognition_posts.getMedia_images({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.users,
as: 'from_user',
where: filter.from_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.from_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.from_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'to_user',
where: filter.to_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.to_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.to_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'media_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'recognition_posts',
'message',
filter.message,
),
};
}
if (filter.points_awardedRange) {
const [start, end] = filter.points_awardedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
points_awarded: {
...where.points_awarded,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
points_awarded: {
...where.points_awarded,
[Op.lte]: end,
},
};
}
}
if (filter.coins_awardedRange) {
const [start, end] = filter.coins_awardedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
coins_awarded: {
...where.coins_awarded,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
coins_awarded: {
...where.coins_awarded,
[Op.lte]: end,
},
};
}
}
if (filter.posted_atRange) {
const [start, end] = filter.posted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.recognition_type) {
where = {
...where,
recognition_type: filter.recognition_type,
};
}
if (filter.is_public) {
where = {
...where,
is_public: filter.is_public,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.recognition_posts.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'recognition_posts',
'message',
query,
),
],
};
}
const records = await db.recognition_posts.findAll({
attributes: [ 'id', 'message' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['message', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.message,
}));
}
};

View File

@ -0,0 +1,659 @@
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 ReportsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.create(
{
id: data.id || undefined,
report_name: data.report_name
||
null
,
report_type: data.report_type
||
null
,
period_type: data.period_type
||
null
,
period_start_at: data.period_start_at
||
null
,
period_end_at: data.period_end_at
||
null
,
filters_json: data.filters_json
||
null
,
generated_at: data.generated_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await reports.setOrganization(currentUser.organization.id || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.reports.getTableName(),
belongsToColumn: 'export_files',
belongsToId: reports.id,
},
data.export_files,
options,
);
return reports;
}
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 reportsData = data.map((item, index) => ({
id: item.id || undefined,
report_name: item.report_name
||
null
,
report_type: item.report_type
||
null
,
period_type: item.period_type
||
null
,
period_start_at: item.period_start_at
||
null
,
period_end_at: item.period_end_at
||
null
,
filters_json: item.filters_json
||
null
,
generated_at: item.generated_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const reports = await db.reports.bulkCreate(reportsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < reports.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.reports.getTableName(),
belongsToColumn: 'export_files',
belongsToId: reports[i].id,
},
data[i].export_files,
options,
);
}
return reports;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const reports = await db.reports.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.report_name !== undefined) updatePayload.report_name = data.report_name;
if (data.report_type !== undefined) updatePayload.report_type = data.report_type;
if (data.period_type !== undefined) updatePayload.period_type = data.period_type;
if (data.period_start_at !== undefined) updatePayload.period_start_at = data.period_start_at;
if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
if (data.filters_json !== undefined) updatePayload.filters_json = data.filters_json;
if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
updatePayload.updatedById = currentUser.id;
await reports.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await reports.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.reports.getTableName(),
belongsToColumn: 'export_files',
belongsToId: reports.id,
},
data.export_files,
options,
);
return reports;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of reports) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of reports) {
await record.destroy({transaction});
}
});
return reports;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.findByPk(id, options);
await reports.update({
deletedBy: currentUser.id
}, {
transaction,
});
await reports.destroy({
transaction
});
return reports;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.findOne(
{ where },
{ transaction },
);
if (!reports) {
return reports;
}
const output = reports.get({plain: true});
output.organization = await reports.getOrganization({
transaction
});
output.export_files = await reports.getExport_files({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.file,
as: 'export_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.report_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'reports',
'report_name',
filter.report_name,
),
};
}
if (filter.filters_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'reports',
'filters_json',
filter.filters_json,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
period_start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
period_end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.period_start_atRange) {
const [start, end] = filter.period_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_start_at: {
...where.period_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_start_at: {
...where.period_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.period_end_atRange) {
const [start, end] = filter.period_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_end_at: {
...where.period_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_end_at: {
...where.period_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.generated_atRange) {
const [start, end] = filter.generated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
generated_at: {
...where.generated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
generated_at: {
...where.generated_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.report_type) {
where = {
...where,
report_type: filter.report_type,
};
}
if (filter.period_type) {
where = {
...where,
period_type: filter.period_type,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.reports.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'reports',
'report_name',
query,
),
],
};
}
const records = await db.reports.findAll({
attributes: [ 'id', 'report_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['report_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.report_name,
}));
}
};

View File

@ -0,0 +1,610 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Reward_catalog_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reward_catalog_items = await db.reward_catalog_items.create(
{
id: data.id || undefined,
item_name: data.item_name
||
null
,
item_type: data.item_type
||
null
,
description: data.description
||
null
,
cost_coins: data.cost_coins
||
null
,
inventory_quantity: data.inventory_quantity
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await reward_catalog_items.setOrganization(currentUser.organization.id || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.reward_catalog_items.getTableName(),
belongsToColumn: 'item_images',
belongsToId: reward_catalog_items.id,
},
data.item_images,
options,
);
return reward_catalog_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const reward_catalog_itemsData = data.map((item, index) => ({
id: item.id || undefined,
item_name: item.item_name
||
null
,
item_type: item.item_type
||
null
,
description: item.description
||
null
,
cost_coins: item.cost_coins
||
null
,
inventory_quantity: item.inventory_quantity
||
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 reward_catalog_items = await db.reward_catalog_items.bulkCreate(reward_catalog_itemsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < reward_catalog_items.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.reward_catalog_items.getTableName(),
belongsToColumn: 'item_images',
belongsToId: reward_catalog_items[i].id,
},
data[i].item_images,
options,
);
}
return reward_catalog_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const reward_catalog_items = await db.reward_catalog_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.item_name !== undefined) updatePayload.item_name = data.item_name;
if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.cost_coins !== undefined) updatePayload.cost_coins = data.cost_coins;
if (data.inventory_quantity !== undefined) updatePayload.inventory_quantity = data.inventory_quantity;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await reward_catalog_items.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await reward_catalog_items.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.reward_catalog_items.getTableName(),
belongsToColumn: 'item_images',
belongsToId: reward_catalog_items.id,
},
data.item_images,
options,
);
return reward_catalog_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reward_catalog_items = await db.reward_catalog_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of reward_catalog_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of reward_catalog_items) {
await record.destroy({transaction});
}
});
return reward_catalog_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reward_catalog_items = await db.reward_catalog_items.findByPk(id, options);
await reward_catalog_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await reward_catalog_items.destroy({
transaction
});
return reward_catalog_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const reward_catalog_items = await db.reward_catalog_items.findOne(
{ where },
{ transaction },
);
if (!reward_catalog_items) {
return reward_catalog_items;
}
const output = reward_catalog_items.get({plain: true});
output.reward_redemptions_reward_catalog_item = await reward_catalog_items.getReward_redemptions_reward_catalog_item({
transaction
});
output.organization = await reward_catalog_items.getOrganization({
transaction
});
output.item_images = await reward_catalog_items.getItem_images({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.file,
as: 'item_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.item_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'reward_catalog_items',
'item_name',
filter.item_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'reward_catalog_items',
'description',
filter.description,
),
};
}
if (filter.cost_coinsRange) {
const [start, end] = filter.cost_coinsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cost_coins: {
...where.cost_coins,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cost_coins: {
...where.cost_coins,
[Op.lte]: end,
},
};
}
}
if (filter.inventory_quantityRange) {
const [start, end] = filter.inventory_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
inventory_quantity: {
...where.inventory_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
inventory_quantity: {
...where.inventory_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.item_type) {
where = {
...where,
item_type: filter.item_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.reward_catalog_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'reward_catalog_items',
'item_name',
query,
),
],
};
}
const records = await db.reward_catalog_items.findAll({
attributes: [ 'id', 'item_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['item_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.item_name,
}));
}
};

View File

@ -0,0 +1,666 @@
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 Reward_redemptionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reward_redemptions = await db.reward_redemptions.create(
{
id: data.id || undefined,
quantity: data.quantity
||
null
,
coins_spent: data.coins_spent
||
null
,
fulfillment_status: data.fulfillment_status
||
null
,
requested_at: data.requested_at
||
null
,
fulfilled_at: data.fulfilled_at
||
null
,
fulfillment_note: data.fulfillment_note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await reward_redemptions.setReward_catalog_item( data.reward_catalog_item || null, {
transaction,
});
await reward_redemptions.setOrganization(currentUser.organization.id || null, {
transaction,
});
await reward_redemptions.setUser( data.user || null, {
transaction,
});
return reward_redemptions;
}
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 reward_redemptionsData = data.map((item, index) => ({
id: item.id || undefined,
quantity: item.quantity
||
null
,
coins_spent: item.coins_spent
||
null
,
fulfillment_status: item.fulfillment_status
||
null
,
requested_at: item.requested_at
||
null
,
fulfilled_at: item.fulfilled_at
||
null
,
fulfillment_note: item.fulfillment_note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const reward_redemptions = await db.reward_redemptions.bulkCreate(reward_redemptionsData, { transaction });
// For each item created, replace relation files
return reward_redemptions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const reward_redemptions = await db.reward_redemptions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.coins_spent !== undefined) updatePayload.coins_spent = data.coins_spent;
if (data.fulfillment_status !== undefined) updatePayload.fulfillment_status = data.fulfillment_status;
if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
if (data.fulfilled_at !== undefined) updatePayload.fulfilled_at = data.fulfilled_at;
if (data.fulfillment_note !== undefined) updatePayload.fulfillment_note = data.fulfillment_note;
updatePayload.updatedById = currentUser.id;
await reward_redemptions.update(updatePayload, {transaction});
if (data.reward_catalog_item !== undefined) {
await reward_redemptions.setReward_catalog_item(
data.reward_catalog_item,
{ transaction }
);
}
if (data.organization !== undefined) {
await reward_redemptions.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.user !== undefined) {
await reward_redemptions.setUser(
data.user,
{ transaction }
);
}
return reward_redemptions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reward_redemptions = await db.reward_redemptions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of reward_redemptions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of reward_redemptions) {
await record.destroy({transaction});
}
});
return reward_redemptions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reward_redemptions = await db.reward_redemptions.findByPk(id, options);
await reward_redemptions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await reward_redemptions.destroy({
transaction
});
return reward_redemptions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const reward_redemptions = await db.reward_redemptions.findOne(
{ where },
{ transaction },
);
if (!reward_redemptions) {
return reward_redemptions;
}
const output = reward_redemptions.get({plain: true});
output.reward_catalog_item = await reward_redemptions.getReward_catalog_item({
transaction
});
output.organization = await reward_redemptions.getOrganization({
transaction
});
output.user = await reward_redemptions.getUser({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.reward_catalog_items,
as: 'reward_catalog_item',
where: filter.reward_catalog_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.reward_catalog_item.split('|').map(term => Utils.uuid(term)) } },
{
item_name: {
[Op.or]: filter.reward_catalog_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organization',
},
{
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.fulfillment_note) {
where = {
...where,
[Op.and]: Utils.ilike(
'reward_redemptions',
'fulfillment_note',
filter.fulfillment_note,
),
};
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.coins_spentRange) {
const [start, end] = filter.coins_spentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
coins_spent: {
...where.coins_spent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
coins_spent: {
...where.coins_spent,
[Op.lte]: end,
},
};
}
}
if (filter.requested_atRange) {
const [start, end] = filter.requested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.lte]: end,
},
};
}
}
if (filter.fulfilled_atRange) {
const [start, end] = filter.fulfilled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
fulfilled_at: {
...where.fulfilled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
fulfilled_at: {
...where.fulfilled_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.fulfillment_status) {
where = {
...where,
fulfillment_status: filter.fulfillment_status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.reward_redemptions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'reward_redemptions',
'fulfillment_status',
query,
),
],
};
}
const records = await db.reward_redemptions.findAll({
attributes: [ 'id', 'fulfillment_status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['fulfillment_status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.fulfillment_status,
}));
}
};

View File

@ -0,0 +1,511 @@
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 Role_assignmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const role_assignments = await db.role_assignments.create(
{
id: data.id || undefined,
assigned_at: data.assigned_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await role_assignments.setOrganization(currentUser.organization.id || null, {
transaction,
});
await role_assignments.setUser( data.user || null, {
transaction,
});
await role_assignments.setRole( data.role || null, {
transaction,
});
return role_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 role_assignmentsData = data.map((item, index) => ({
id: item.id || undefined,
assigned_at: item.assigned_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const role_assignments = await db.role_assignments.bulkCreate(role_assignmentsData, { transaction });
// For each item created, replace relation files
return role_assignments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const role_assignments = await db.role_assignments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
updatePayload.updatedById = currentUser.id;
await role_assignments.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await role_assignments.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.user !== undefined) {
await role_assignments.setUser(
data.user,
{ transaction }
);
}
if (data.role !== undefined) {
await role_assignments.setRole(
data.role,
{ transaction }
);
}
return role_assignments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const role_assignments = await db.role_assignments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of role_assignments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of role_assignments) {
await record.destroy({transaction});
}
});
return role_assignments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const role_assignments = await db.role_assignments.findByPk(id, options);
await role_assignments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await role_assignments.destroy({
transaction
});
return role_assignments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const role_assignments = await db.role_assignments.findOne(
{ where },
{ transaction },
);
if (!role_assignments) {
return role_assignments;
}
const output = role_assignments.get({plain: true});
output.organization = await role_assignments.getOrganization({
transaction
});
output.user = await role_assignments.getUser({
transaction
});
output.role = await role_assignments.getRole({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.roles,
as: 'role',
where: filter.role ? {
[Op.or]: [
{ id: { [Op.in]: filter.role.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.role.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.assigned_atRange) {
const [start, end] = filter.assigned_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.role_assignments.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'role_assignments',
'assigned_at',
query,
),
],
};
}
const records = await db.role_assignments.findAll({
attributes: [ 'id', 'assigned_at' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['assigned_at', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.assigned_at,
}));
}
};

View File

@ -0,0 +1,496 @@
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 Role_permissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const role_permissions = await db.role_permissions.create(
{
id: data.id || undefined,
is_allowed: data.is_allowed
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await role_permissions.setRole( data.role || null, {
transaction,
});
await role_permissions.setPermission( data.permission || null, {
transaction,
});
await role_permissions.setOrganizations( data.organizations || null, {
transaction,
});
return role_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 role_permissionsData = data.map((item, index) => ({
id: item.id || undefined,
is_allowed: item.is_allowed
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const role_permissions = await db.role_permissions.bulkCreate(role_permissionsData, { transaction });
// For each item created, replace relation files
return role_permissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const role_permissions = await db.role_permissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.is_allowed !== undefined) updatePayload.is_allowed = data.is_allowed;
updatePayload.updatedById = currentUser.id;
await role_permissions.update(updatePayload, {transaction});
if (data.role !== undefined) {
await role_permissions.setRole(
data.role,
{ transaction }
);
}
if (data.permission !== undefined) {
await role_permissions.setPermission(
data.permission,
{ transaction }
);
}
if (data.organizations !== undefined) {
await role_permissions.setOrganizations(
data.organizations,
{ transaction }
);
}
return role_permissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const role_permissions = await db.role_permissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of role_permissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of role_permissions) {
await record.destroy({transaction});
}
});
return role_permissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const role_permissions = await db.role_permissions.findByPk(id, options);
await role_permissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await role_permissions.destroy({
transaction
});
return role_permissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const role_permissions = await db.role_permissions.findOne(
{ where },
{ transaction },
);
if (!role_permissions) {
return role_permissions;
}
const output = role_permissions.get({plain: true});
output.role = await role_permissions.getRole({
transaction
});
output.permission = await role_permissions.getPermission({
transaction
});
output.organizations = await role_permissions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.roles,
as: 'role',
where: filter.role ? {
[Op.or]: [
{ id: { [Op.in]: filter.role.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.role.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.permissions,
as: 'permission',
where: filter.permission ? {
[Op.or]: [
{ id: { [Op.in]: filter.permission.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.permission.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_allowed) {
where = {
...where,
is_allowed: filter.is_allowed,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.role_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'role_permissions',
'is_allowed',
query,
),
],
};
}
const records = await db.role_permissions.findAll({
attributes: [ 'id', 'is_allowed' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['is_allowed', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.is_allowed,
}));
}
};

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

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

View File

@ -0,0 +1,542 @@
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 Simulation_stepsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const simulation_steps = await db.simulation_steps.create(
{
id: data.id || undefined,
sequence_order: data.sequence_order
||
null
,
speaker: data.speaker
||
null
,
step_text: data.step_text
||
null
,
expected_response_hint: data.expected_response_hint
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await simulation_steps.setSimulation( data.simulation || null, {
transaction,
});
await simulation_steps.setOrganizations( data.organizations || null, {
transaction,
});
return simulation_steps;
}
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 simulation_stepsData = data.map((item, index) => ({
id: item.id || undefined,
sequence_order: item.sequence_order
||
null
,
speaker: item.speaker
||
null
,
step_text: item.step_text
||
null
,
expected_response_hint: item.expected_response_hint
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const simulation_steps = await db.simulation_steps.bulkCreate(simulation_stepsData, { transaction });
// For each item created, replace relation files
return simulation_steps;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const simulation_steps = await db.simulation_steps.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.sequence_order !== undefined) updatePayload.sequence_order = data.sequence_order;
if (data.speaker !== undefined) updatePayload.speaker = data.speaker;
if (data.step_text !== undefined) updatePayload.step_text = data.step_text;
if (data.expected_response_hint !== undefined) updatePayload.expected_response_hint = data.expected_response_hint;
updatePayload.updatedById = currentUser.id;
await simulation_steps.update(updatePayload, {transaction});
if (data.simulation !== undefined) {
await simulation_steps.setSimulation(
data.simulation,
{ transaction }
);
}
if (data.organizations !== undefined) {
await simulation_steps.setOrganizations(
data.organizations,
{ transaction }
);
}
return simulation_steps;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const simulation_steps = await db.simulation_steps.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of simulation_steps) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of simulation_steps) {
await record.destroy({transaction});
}
});
return simulation_steps;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const simulation_steps = await db.simulation_steps.findByPk(id, options);
await simulation_steps.update({
deletedBy: currentUser.id
}, {
transaction,
});
await simulation_steps.destroy({
transaction
});
return simulation_steps;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const simulation_steps = await db.simulation_steps.findOne(
{ where },
{ transaction },
);
if (!simulation_steps) {
return simulation_steps;
}
const output = simulation_steps.get({plain: true});
output.simulation = await simulation_steps.getSimulation({
transaction
});
output.organizations = await simulation_steps.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.simulations,
as: 'simulation',
where: filter.simulation ? {
[Op.or]: [
{ id: { [Op.in]: filter.simulation.split('|').map(term => Utils.uuid(term)) } },
{
simulation_title: {
[Op.or]: filter.simulation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.step_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'simulation_steps',
'step_text',
filter.step_text,
),
};
}
if (filter.expected_response_hint) {
where = {
...where,
[Op.and]: Utils.ilike(
'simulation_steps',
'expected_response_hint',
filter.expected_response_hint,
),
};
}
if (filter.sequence_orderRange) {
const [start, end] = filter.sequence_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.speaker) {
where = {
...where,
speaker: filter.speaker,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.simulation_steps.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'simulation_steps',
'step_text',
query,
),
],
};
}
const records = await db.simulation_steps.findAll({
attributes: [ 'id', 'step_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['step_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.step_text,
}));
}
};

View File

@ -0,0 +1,533 @@
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 SimulationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const simulations = await db.simulations.create(
{
id: data.id || undefined,
simulation_title: data.simulation_title
||
null
,
simulation_type: data.simulation_type
||
null
,
scenario_context: data.scenario_context
||
null
,
success_criteria: data.success_criteria
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await simulations.setMission( data.mission || null, {
transaction,
});
await simulations.setOrganizations( data.organizations || null, {
transaction,
});
return simulations;
}
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 simulationsData = data.map((item, index) => ({
id: item.id || undefined,
simulation_title: item.simulation_title
||
null
,
simulation_type: item.simulation_type
||
null
,
scenario_context: item.scenario_context
||
null
,
success_criteria: item.success_criteria
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const simulations = await db.simulations.bulkCreate(simulationsData, { transaction });
// For each item created, replace relation files
return simulations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const simulations = await db.simulations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.simulation_title !== undefined) updatePayload.simulation_title = data.simulation_title;
if (data.simulation_type !== undefined) updatePayload.simulation_type = data.simulation_type;
if (data.scenario_context !== undefined) updatePayload.scenario_context = data.scenario_context;
if (data.success_criteria !== undefined) updatePayload.success_criteria = data.success_criteria;
updatePayload.updatedById = currentUser.id;
await simulations.update(updatePayload, {transaction});
if (data.mission !== undefined) {
await simulations.setMission(
data.mission,
{ transaction }
);
}
if (data.organizations !== undefined) {
await simulations.setOrganizations(
data.organizations,
{ transaction }
);
}
return simulations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const simulations = await db.simulations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of simulations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of simulations) {
await record.destroy({transaction});
}
});
return simulations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const simulations = await db.simulations.findByPk(id, options);
await simulations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await simulations.destroy({
transaction
});
return simulations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const simulations = await db.simulations.findOne(
{ where },
{ transaction },
);
if (!simulations) {
return simulations;
}
const output = simulations.get({plain: true});
output.simulation_steps_simulation = await simulations.getSimulation_steps_simulation({
transaction
});
output.mission = await simulations.getMission({
transaction
});
output.organizations = await simulations.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.missions,
as: 'mission',
where: filter.mission ? {
[Op.or]: [
{ id: { [Op.in]: filter.mission.split('|').map(term => Utils.uuid(term)) } },
{
mission_title: {
[Op.or]: filter.mission.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.simulation_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'simulations',
'simulation_title',
filter.simulation_title,
),
};
}
if (filter.scenario_context) {
where = {
...where,
[Op.and]: Utils.ilike(
'simulations',
'scenario_context',
filter.scenario_context,
),
};
}
if (filter.success_criteria) {
where = {
...where,
[Op.and]: Utils.ilike(
'simulations',
'success_criteria',
filter.success_criteria,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.simulation_type) {
where = {
...where,
simulation_type: filter.simulation_type,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.simulations.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'simulations',
'simulation_title',
query,
),
],
};
}
const records = await db.simulations.findAll({
attributes: [ 'id', 'simulation_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['simulation_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.simulation_title,
}));
}
};

View File

@ -0,0 +1,544 @@
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 Survey_questionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const survey_questions = await db.survey_questions.create(
{
id: data.id || undefined,
question_type: data.question_type
||
null
,
prompt: data.prompt
||
null
,
sequence_order: data.sequence_order
||
null
,
is_required: data.is_required
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await survey_questions.setSurvey( data.survey || null, {
transaction,
});
await survey_questions.setOrganizations( data.organizations || null, {
transaction,
});
return survey_questions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const survey_questionsData = data.map((item, index) => ({
id: item.id || undefined,
question_type: item.question_type
||
null
,
prompt: item.prompt
||
null
,
sequence_order: item.sequence_order
||
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 survey_questions = await db.survey_questions.bulkCreate(survey_questionsData, { transaction });
// For each item created, replace relation files
return survey_questions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const survey_questions = await db.survey_questions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.question_type !== undefined) updatePayload.question_type = data.question_type;
if (data.prompt !== undefined) updatePayload.prompt = data.prompt;
if (data.sequence_order !== undefined) updatePayload.sequence_order = data.sequence_order;
if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
updatePayload.updatedById = currentUser.id;
await survey_questions.update(updatePayload, {transaction});
if (data.survey !== undefined) {
await survey_questions.setSurvey(
data.survey,
{ transaction }
);
}
if (data.organizations !== undefined) {
await survey_questions.setOrganizations(
data.organizations,
{ transaction }
);
}
return survey_questions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const survey_questions = await db.survey_questions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of survey_questions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of survey_questions) {
await record.destroy({transaction});
}
});
return survey_questions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const survey_questions = await db.survey_questions.findByPk(id, options);
await survey_questions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await survey_questions.destroy({
transaction
});
return survey_questions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const survey_questions = await db.survey_questions.findOne(
{ where },
{ transaction },
);
if (!survey_questions) {
return survey_questions;
}
const output = survey_questions.get({plain: true});
output.survey_response_items_survey_question = await survey_questions.getSurvey_response_items_survey_question({
transaction
});
output.survey = await survey_questions.getSurvey({
transaction
});
output.organizations = await survey_questions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.surveys,
as: 'survey',
where: filter.survey ? {
[Op.or]: [
{ id: { [Op.in]: filter.survey.split('|').map(term => Utils.uuid(term)) } },
{
survey_name: {
[Op.or]: filter.survey.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.prompt) {
where = {
...where,
[Op.and]: Utils.ilike(
'survey_questions',
'prompt',
filter.prompt,
),
};
}
if (filter.sequence_orderRange) {
const [start, end] = filter.sequence_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sequence_order: {
...where.sequence_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.question_type) {
where = {
...where,
question_type: filter.question_type,
};
}
if (filter.is_required) {
where = {
...where,
is_required: filter.is_required,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.survey_questions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'survey_questions',
'prompt',
query,
),
],
};
}
const records = await db.survey_questions.findAll({
attributes: [ 'id', 'prompt' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['prompt', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.prompt,
}));
}
};

View File

@ -0,0 +1,498 @@
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 Survey_response_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const survey_response_items = await db.survey_response_items.create(
{
id: data.id || undefined,
answer_value: data.answer_value
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await survey_response_items.setSurvey_response( data.survey_response || null, {
transaction,
});
await survey_response_items.setSurvey_question( data.survey_question || null, {
transaction,
});
await survey_response_items.setOrganizations( data.organizations || null, {
transaction,
});
return survey_response_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const survey_response_itemsData = data.map((item, index) => ({
id: item.id || undefined,
answer_value: item.answer_value
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const survey_response_items = await db.survey_response_items.bulkCreate(survey_response_itemsData, { transaction });
// For each item created, replace relation files
return survey_response_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const survey_response_items = await db.survey_response_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.answer_value !== undefined) updatePayload.answer_value = data.answer_value;
updatePayload.updatedById = currentUser.id;
await survey_response_items.update(updatePayload, {transaction});
if (data.survey_response !== undefined) {
await survey_response_items.setSurvey_response(
data.survey_response,
{ transaction }
);
}
if (data.survey_question !== undefined) {
await survey_response_items.setSurvey_question(
data.survey_question,
{ transaction }
);
}
if (data.organizations !== undefined) {
await survey_response_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return survey_response_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const survey_response_items = await db.survey_response_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of survey_response_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of survey_response_items) {
await record.destroy({transaction});
}
});
return survey_response_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const survey_response_items = await db.survey_response_items.findByPk(id, options);
await survey_response_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await survey_response_items.destroy({
transaction
});
return survey_response_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const survey_response_items = await db.survey_response_items.findOne(
{ where },
{ transaction },
);
if (!survey_response_items) {
return survey_response_items;
}
const output = survey_response_items.get({plain: true});
output.survey_response = await survey_response_items.getSurvey_response({
transaction
});
output.survey_question = await survey_response_items.getSurvey_question({
transaction
});
output.organizations = await survey_response_items.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.survey_responses,
as: 'survey_response',
where: filter.survey_response ? {
[Op.or]: [
{ id: { [Op.in]: filter.survey_response.split('|').map(term => Utils.uuid(term)) } },
{
overall_comment: {
[Op.or]: filter.survey_response.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.survey_questions,
as: 'survey_question',
where: filter.survey_question ? {
[Op.or]: [
{ id: { [Op.in]: filter.survey_question.split('|').map(term => Utils.uuid(term)) } },
{
prompt: {
[Op.or]: filter.survey_question.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.answer_value) {
where = {
...where,
[Op.and]: Utils.ilike(
'survey_response_items',
'answer_value',
filter.answer_value,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.survey_response_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'survey_response_items',
'answer_value',
query,
),
],
};
}
const records = await db.survey_response_items.findAll({
attributes: [ 'id', 'answer_value' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['answer_value', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.answer_value,
}));
}
};

View File

@ -0,0 +1,539 @@
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 Survey_responsesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const survey_responses = await db.survey_responses.create(
{
id: data.id || undefined,
submitted_at: data.submitted_at
||
null
,
overall_comment: data.overall_comment
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await survey_responses.setSurvey( data.survey || null, {
transaction,
});
await survey_responses.setOrganization(currentUser.organization.id || null, {
transaction,
});
await survey_responses.setUser( data.user || null, {
transaction,
});
return survey_responses;
}
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 survey_responsesData = data.map((item, index) => ({
id: item.id || undefined,
submitted_at: item.submitted_at
||
null
,
overall_comment: item.overall_comment
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const survey_responses = await db.survey_responses.bulkCreate(survey_responsesData, { transaction });
// For each item created, replace relation files
return survey_responses;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const survey_responses = await db.survey_responses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
if (data.overall_comment !== undefined) updatePayload.overall_comment = data.overall_comment;
updatePayload.updatedById = currentUser.id;
await survey_responses.update(updatePayload, {transaction});
if (data.survey !== undefined) {
await survey_responses.setSurvey(
data.survey,
{ transaction }
);
}
if (data.organization !== undefined) {
await survey_responses.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.user !== undefined) {
await survey_responses.setUser(
data.user,
{ transaction }
);
}
return survey_responses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const survey_responses = await db.survey_responses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of survey_responses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of survey_responses) {
await record.destroy({transaction});
}
});
return survey_responses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const survey_responses = await db.survey_responses.findByPk(id, options);
await survey_responses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await survey_responses.destroy({
transaction
});
return survey_responses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const survey_responses = await db.survey_responses.findOne(
{ where },
{ transaction },
);
if (!survey_responses) {
return survey_responses;
}
const output = survey_responses.get({plain: true});
output.survey_response_items_survey_response = await survey_responses.getSurvey_response_items_survey_response({
transaction
});
output.survey = await survey_responses.getSurvey({
transaction
});
output.organization = await survey_responses.getOrganization({
transaction
});
output.user = await survey_responses.getUser({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.surveys,
as: 'survey',
where: filter.survey ? {
[Op.or]: [
{ id: { [Op.in]: filter.survey.split('|').map(term => Utils.uuid(term)) } },
{
survey_name: {
[Op.or]: filter.survey.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organization',
},
{
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.overall_comment) {
where = {
...where,
[Op.and]: Utils.ilike(
'survey_responses',
'overall_comment',
filter.overall_comment,
),
};
}
if (filter.submitted_atRange) {
const [start, end] = filter.submitted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.survey_responses.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'survey_responses',
'overall_comment',
query,
),
],
};
}
const records = await db.survey_responses.findAll({
attributes: [ 'id', 'overall_comment' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['overall_comment', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.overall_comment,
}));
}
};

View File

@ -0,0 +1,592 @@
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 SurveysDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const surveys = await db.surveys.create(
{
id: data.id || undefined,
survey_name: data.survey_name
||
null
,
survey_type: data.survey_type
||
null
,
introduction_text: data.introduction_text
||
null
,
is_anonymous: data.is_anonymous
||
false
,
status: data.status
||
null
,
opens_at: data.opens_at
||
null
,
closes_at: data.closes_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await surveys.setOrganization(currentUser.organization.id || null, {
transaction,
});
return surveys;
}
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 surveysData = data.map((item, index) => ({
id: item.id || undefined,
survey_name: item.survey_name
||
null
,
survey_type: item.survey_type
||
null
,
introduction_text: item.introduction_text
||
null
,
is_anonymous: item.is_anonymous
||
false
,
status: item.status
||
null
,
opens_at: item.opens_at
||
null
,
closes_at: item.closes_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const surveys = await db.surveys.bulkCreate(surveysData, { transaction });
// For each item created, replace relation files
return surveys;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const surveys = await db.surveys.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.survey_name !== undefined) updatePayload.survey_name = data.survey_name;
if (data.survey_type !== undefined) updatePayload.survey_type = data.survey_type;
if (data.introduction_text !== undefined) updatePayload.introduction_text = data.introduction_text;
if (data.is_anonymous !== undefined) updatePayload.is_anonymous = data.is_anonymous;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.opens_at !== undefined) updatePayload.opens_at = data.opens_at;
if (data.closes_at !== undefined) updatePayload.closes_at = data.closes_at;
updatePayload.updatedById = currentUser.id;
await surveys.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await surveys.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
return surveys;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const surveys = await db.surveys.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of surveys) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of surveys) {
await record.destroy({transaction});
}
});
return surveys;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const surveys = await db.surveys.findByPk(id, options);
await surveys.update({
deletedBy: currentUser.id
}, {
transaction,
});
await surveys.destroy({
transaction
});
return surveys;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const surveys = await db.surveys.findOne(
{ where },
{ transaction },
);
if (!surveys) {
return surveys;
}
const output = surveys.get({plain: true});
output.survey_questions_survey = await surveys.getSurvey_questions_survey({
transaction
});
output.survey_responses_survey = await surveys.getSurvey_responses_survey({
transaction
});
output.organization = await surveys.getOrganization({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.survey_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'surveys',
'survey_name',
filter.survey_name,
),
};
}
if (filter.introduction_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'surveys',
'introduction_text',
filter.introduction_text,
),
};
}
if (filter.opens_atRange) {
const [start, end] = filter.opens_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
opens_at: {
...where.opens_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
opens_at: {
...where.opens_at,
[Op.lte]: end,
},
};
}
}
if (filter.closes_atRange) {
const [start, end] = filter.closes_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
closes_at: {
...where.closes_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
closes_at: {
...where.closes_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.survey_type) {
where = {
...where,
survey_type: filter.survey_type,
};
}
if (filter.is_anonymous) {
where = {
...where,
is_anonymous: filter.is_anonymous,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.surveys.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'surveys',
'survey_name',
query,
),
],
};
}
const records = await db.surveys.findAll({
attributes: [ 'id', 'survey_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['survey_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.survey_name,
}));
}
};

View File

@ -0,0 +1,590 @@
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 Team_membershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const team_memberships = await db.team_memberships.create(
{
id: data.id || undefined,
membership_role: data.membership_role
||
null
,
joined_at: data.joined_at
||
null
,
left_at: data.left_at
||
null
,
is_primary_team: data.is_primary_team
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await team_memberships.setTeam( data.team || null, {
transaction,
});
await team_memberships.setUser( data.user || null, {
transaction,
});
await team_memberships.setOrganizations( data.organizations || null, {
transaction,
});
return team_memberships;
}
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 team_membershipsData = data.map((item, index) => ({
id: item.id || undefined,
membership_role: item.membership_role
||
null
,
joined_at: item.joined_at
||
null
,
left_at: item.left_at
||
null
,
is_primary_team: item.is_primary_team
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const team_memberships = await db.team_memberships.bulkCreate(team_membershipsData, { transaction });
// For each item created, replace relation files
return team_memberships;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const team_memberships = await db.team_memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.membership_role !== undefined) updatePayload.membership_role = data.membership_role;
if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
if (data.left_at !== undefined) updatePayload.left_at = data.left_at;
if (data.is_primary_team !== undefined) updatePayload.is_primary_team = data.is_primary_team;
updatePayload.updatedById = currentUser.id;
await team_memberships.update(updatePayload, {transaction});
if (data.team !== undefined) {
await team_memberships.setTeam(
data.team,
{ transaction }
);
}
if (data.user !== undefined) {
await team_memberships.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await team_memberships.setOrganizations(
data.organizations,
{ transaction }
);
}
return team_memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const team_memberships = await db.team_memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of team_memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of team_memberships) {
await record.destroy({transaction});
}
});
return team_memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const team_memberships = await db.team_memberships.findByPk(id, options);
await team_memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await team_memberships.destroy({
transaction
});
return team_memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const team_memberships = await db.team_memberships.findOne(
{ where },
{ transaction },
);
if (!team_memberships) {
return team_memberships;
}
const output = team_memberships.get({plain: true});
output.team = await team_memberships.getTeam({
transaction
});
output.user = await team_memberships.getUser({
transaction
});
output.organizations = await team_memberships.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.teams,
as: 'team',
where: filter.team ? {
[Op.or]: [
{ id: { [Op.in]: filter.team.split('|').map(term => Utils.uuid(term)) } },
{
team_name: {
[Op.or]: filter.team.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.joined_atRange) {
const [start, end] = filter.joined_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.lte]: end,
},
};
}
}
if (filter.left_atRange) {
const [start, end] = filter.left_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
left_at: {
...where.left_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
left_at: {
...where.left_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.membership_role) {
where = {
...where,
membership_role: filter.membership_role,
};
}
if (filter.is_primary_team) {
where = {
...where,
is_primary_team: filter.is_primary_team,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.team_memberships.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'team_memberships',
'membership_role',
query,
),
],
};
}
const records = await db.team_memberships.findAll({
attributes: [ 'id', 'membership_role' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['membership_role', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.membership_role,
}));
}
};

517
backend/src/db/api/teams.js Normal file
View File

@ -0,0 +1,517 @@
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 TeamsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const teams = await db.teams.create(
{
id: data.id || undefined,
team_name: data.team_name
||
null
,
team_code: data.team_code
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await teams.setOrganization(currentUser.organization.id || null, {
transaction,
});
await teams.setManager( data.manager || null, {
transaction,
});
return teams;
}
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 teamsData = data.map((item, index) => ({
id: item.id || undefined,
team_name: item.team_name
||
null
,
team_code: item.team_code
||
null
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const teams = await db.teams.bulkCreate(teamsData, { transaction });
// For each item created, replace relation files
return teams;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const teams = await db.teams.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.team_name !== undefined) updatePayload.team_name = data.team_name;
if (data.team_code !== undefined) updatePayload.team_code = data.team_code;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await teams.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await teams.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.manager !== undefined) {
await teams.setManager(
data.manager,
{ transaction }
);
}
return teams;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const teams = await db.teams.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of teams) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of teams) {
await record.destroy({transaction});
}
});
return teams;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const teams = await db.teams.findByPk(id, options);
await teams.update({
deletedBy: currentUser.id
}, {
transaction,
});
await teams.destroy({
transaction
});
return teams;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const teams = await db.teams.findOne(
{ where },
{ transaction },
);
if (!teams) {
return teams;
}
const output = teams.get({plain: true});
output.team_memberships_team = await teams.getTeam_memberships_team({
transaction
});
output.challenge_participants_team = await teams.getChallenge_participants_team({
transaction
});
output.organization = await teams.getOrganization({
transaction
});
output.manager = await teams.getManager({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
{
model: db.users,
as: 'manager',
where: filter.manager ? {
[Op.or]: [
{ id: { [Op.in]: filter.manager.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.manager.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.team_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'teams',
'team_name',
filter.team_name,
),
};
}
if (filter.team_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'teams',
'team_code',
filter.team_code,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'teams',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.teams.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'teams',
'team_name',
query,
),
],
};
}
const records = await db.teams.findAll({
attributes: [ 'id', 'team_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['team_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.team_name,
}));
}
};

View File

@ -0,0 +1,572 @@
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 User_badgesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_badges = await db.user_badges.create(
{
id: data.id || undefined,
awarded_at: data.awarded_at
||
null
,
award_note: data.award_note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await user_badges.setBadge( data.badge || null, {
transaction,
});
await user_badges.setUser( data.user || null, {
transaction,
});
await user_badges.setAwarded_by( data.awarded_by || null, {
transaction,
});
await user_badges.setOrganizations( data.organizations || null, {
transaction,
});
return user_badges;
}
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 user_badgesData = data.map((item, index) => ({
id: item.id || undefined,
awarded_at: item.awarded_at
||
null
,
award_note: item.award_note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const user_badges = await db.user_badges.bulkCreate(user_badgesData, { transaction });
// For each item created, replace relation files
return user_badges;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const user_badges = await db.user_badges.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.awarded_at !== undefined) updatePayload.awarded_at = data.awarded_at;
if (data.award_note !== undefined) updatePayload.award_note = data.award_note;
updatePayload.updatedById = currentUser.id;
await user_badges.update(updatePayload, {transaction});
if (data.badge !== undefined) {
await user_badges.setBadge(
data.badge,
{ transaction }
);
}
if (data.user !== undefined) {
await user_badges.setUser(
data.user,
{ transaction }
);
}
if (data.awarded_by !== undefined) {
await user_badges.setAwarded_by(
data.awarded_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await user_badges.setOrganizations(
data.organizations,
{ transaction }
);
}
return user_badges;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_badges = await db.user_badges.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_badges) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_badges) {
await record.destroy({transaction});
}
});
return user_badges;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_badges = await db.user_badges.findByPk(id, options);
await user_badges.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_badges.destroy({
transaction
});
return user_badges;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_badges = await db.user_badges.findOne(
{ where },
{ transaction },
);
if (!user_badges) {
return user_badges;
}
const output = user_badges.get({plain: true});
output.badge = await user_badges.getBadge({
transaction
});
output.user = await user_badges.getUser({
transaction
});
output.awarded_by = await user_badges.getAwarded_by({
transaction
});
output.organizations = await user_badges.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.badges,
as: 'badge',
where: filter.badge ? {
[Op.or]: [
{ id: { [Op.in]: filter.badge.split('|').map(term => Utils.uuid(term)) } },
{
badge_name: {
[Op.or]: filter.badge.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'awarded_by',
where: filter.awarded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.awarded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.awarded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.award_note) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_badges',
'award_note',
filter.award_note,
),
};
}
if (filter.awarded_atRange) {
const [start, end] = filter.awarded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
awarded_at: {
...where.awarded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
awarded_at: {
...where.awarded_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.user_badges.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'user_badges',
'award_note',
query,
),
],
};
}
const records = await db.user_badges.findAll({
attributes: [ 'id', 'award_note' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['award_note', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.award_note,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -0,0 +1,193 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ai_content_requests = sequelize.define(
'ai_content_requests',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
request_type: {
type: DataTypes.ENUM,
values: [
"quiz",
"article",
"simulation_script",
"mission_outline",
"knowledge_refresher"
],
},
prompt_text: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"completed",
"failed"
],
},
requested_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
output_text: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ai_content_requests.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.ai_content_requests.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.ai_content_requests.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.ai_content_requests.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_content_requests.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_content_requests;
};

View File

@ -0,0 +1,167 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_events = sequelize.define(
'audit_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_name: {
type: DataTypes.TEXT,
},
entity_name: {
type: DataTypes.TEXT,
},
entity_reference: {
type: DataTypes.TEXT,
},
event_payload_json: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
ip_address: {
type: DataTypes.TEXT,
},
user_agent: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
audit_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.audit_events.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.audit_events.belongsTo(db.users, {
as: 'actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.audit_events.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_events;
};

View File

@ -0,0 +1,184 @@
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 badges = sequelize.define(
'badges',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
badge_name: {
type: DataTypes.TEXT,
},
badge_description: {
type: DataTypes.TEXT,
},
award_rule_type: {
type: DataTypes.ENUM,
values: [
"mission_completion",
"program_completion",
"level_reached",
"kpi_target",
"manual"
],
},
threshold_value: {
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,
},
);
badges.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.badges.hasMany(db.user_badges, {
as: 'user_badges_badge',
foreignKey: {
name: 'badgeId',
},
constraints: false,
});
//end loop
db.badges.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.badges.hasMany(db.file, {
as: 'badge_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.badges.getTableName(),
belongsToColumn: 'badge_images',
},
});
db.badges.belongsTo(db.users, {
as: 'createdBy',
});
db.badges.belongsTo(db.users, {
as: 'updatedBy',
});
};
return badges;
};

View File

@ -0,0 +1,183 @@
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 challenge_participants = sequelize.define(
'challenge_participants',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
participant_type: {
type: DataTypes.ENUM,
values: [
"user",
"team"
],
},
current_value: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"completed",
"disqualified"
],
},
rank_position: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
challenge_participants.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.challenge_participants.belongsTo(db.challenges, {
as: 'challenge',
foreignKey: {
name: 'challengeId',
},
constraints: false,
});
db.challenge_participants.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.challenge_participants.belongsTo(db.teams, {
as: 'team',
foreignKey: {
name: 'teamId',
},
constraints: false,
});
db.challenge_participants.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.challenge_participants.belongsTo(db.users, {
as: 'createdBy',
});
db.challenge_participants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return challenge_participants;
};

View File

@ -0,0 +1,238 @@
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 challenges = sequelize.define(
'challenges',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
challenge_name: {
type: DataTypes.TEXT,
},
challenge_type: {
type: DataTypes.ENUM,
values: [
"individual",
"team"
],
},
metric_type: {
type: DataTypes.ENUM,
values: [
"mission_completions",
"points",
"coins",
"kpi_value",
"quiz_score_average"
],
},
description: {
type: DataTypes.TEXT,
},
target_value: {
type: DataTypes.DECIMAL,
},
reward_points: {
type: DataTypes.DECIMAL,
},
reward_coins: {
type: DataTypes.DECIMAL,
},
starts_at: {
type: DataTypes.DATE,
},
ends_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"scheduled",
"active",
"completed",
"cancelled"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
challenges.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.challenges.hasMany(db.challenge_participants, {
as: 'challenge_participants_challenge',
foreignKey: {
name: 'challengeId',
},
constraints: false,
});
//end loop
db.challenges.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.challenges.belongsTo(db.users, {
as: 'created_by',
foreignKey: {
name: 'created_byId',
},
constraints: false,
});
db.challenges.belongsTo(db.users, {
as: 'createdBy',
});
db.challenges.belongsTo(db.users, {
as: 'updatedBy',
});
};
return challenges;
};

View File

@ -0,0 +1,194 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const checklist_items = sequelize.define(
'checklist_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
item_title: {
type: DataTypes.TEXT,
},
sequence_order: {
type: DataTypes.INTEGER,
},
item_type: {
type: DataTypes.ENUM,
values: [
"paperwork",
"video",
"read",
"form",
"acknowledgement",
"meeting"
],
},
instructions: {
type: DataTypes.TEXT,
},
link_url: {
type: DataTypes.TEXT,
},
is_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
checklist_items.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.checklist_items.belongsTo(db.checklists, {
as: 'checklist',
foreignKey: {
name: 'checklistId',
},
constraints: false,
});
db.checklist_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.checklist_items.hasMany(db.file, {
as: 'attachment_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.checklist_items.getTableName(),
belongsToColumn: 'attachment_files',
},
});
db.checklist_items.belongsTo(db.users, {
as: 'createdBy',
});
db.checklist_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return checklist_items;
};

View File

@ -0,0 +1,178 @@
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 checklists = sequelize.define(
'checklists',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
checklist_name: {
type: DataTypes.TEXT,
},
checklist_stage: {
type: DataTypes.ENUM,
values: [
"preboarding",
"day_one",
"week_one",
"first_30_days",
"first_60_days",
"first_90_days"
],
},
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,
},
);
checklists.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.checklists.hasMany(db.checklist_items, {
as: 'checklist_items_checklist',
foreignKey: {
name: 'checklistId',
},
constraints: false,
});
//end loop
db.checklists.belongsTo(db.programs, {
as: 'program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
db.checklists.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.checklists.belongsTo(db.users, {
as: 'createdBy',
});
db.checklists.belongsTo(db.users, {
as: 'updatedBy',
});
};
return checklists;
};

View File

@ -0,0 +1,212 @@
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 coaching_sessions = sequelize.define(
'coaching_sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
session_type: {
type: DataTypes.ENUM,
values: [
"one_on_one",
"qa_review",
"performance_review",
"training_followup"
],
},
status: {
type: DataTypes.ENUM,
values: [
"scheduled",
"completed",
"cancelled",
"needs_followup"
],
},
scheduled_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
agenda: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
action_items: {
type: DataTypes.TEXT,
},
follow_up_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
coaching_sessions.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.coaching_sessions.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.coaching_sessions.belongsTo(db.users, {
as: 'coach',
foreignKey: {
name: 'coachId',
},
constraints: false,
});
db.coaching_sessions.belongsTo(db.users, {
as: 'coachee',
foreignKey: {
name: 'coacheeId',
},
constraints: false,
});
db.coaching_sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.coaching_sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return coaching_sessions;
};

View File

@ -0,0 +1,188 @@
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 content_assets = sequelize.define(
'content_assets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
asset_title: {
type: DataTypes.TEXT,
},
asset_type: {
type: DataTypes.ENUM,
values: [
"article",
"pdf",
"image",
"video",
"link",
"template"
],
},
body: {
type: DataTypes.TEXT,
},
asset_url: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"archived"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
content_assets.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.content_assets.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.content_assets.hasMany(db.file, {
as: 'asset_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.content_assets.getTableName(),
belongsToColumn: 'asset_files',
},
});
db.content_assets.belongsTo(db.users, {
as: 'createdBy',
});
db.content_assets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return content_assets;
};

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 enrollments = sequelize.define(
'enrollments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
enrollment_status: {
type: DataTypes.ENUM,
values: [
"assigned",
"in_progress",
"completed",
"cancelled"
],
},
assigned_at: {
type: DataTypes.DATE,
},
started_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
due_at: {
type: DataTypes.DATE,
},
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.mission_attempts, {
as: 'mission_attempts_enrollment',
foreignKey: {
name: 'enrollmentId',
},
constraints: false,
});
//end loop
db.enrollments.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.enrollments.belongsTo(db.programs, {
as: 'program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
db.enrollments.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.enrollments.belongsTo(db.users, {
as: 'assigned_by',
foreignKey: {
name: 'assigned_byId',
},
constraints: false,
});
db.enrollments.belongsTo(db.users, {
as: 'createdBy',
});
db.enrollments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return enrollments;
};

View File

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

View File

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

View File

@ -0,0 +1,158 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const knowledge_gap_assessments = sequelize.define(
'knowledge_gap_assessments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
assessment_type: {
type: DataTypes.ENUM,
values: [
"refresher",
"diagnostic",
"post_training"
],
},
assessed_at: {
type: DataTypes.DATE,
},
overall_score: {
type: DataTypes.DECIMAL,
},
insights_summary: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
knowledge_gap_assessments.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.knowledge_gap_assessments.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.knowledge_gap_assessments.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.knowledge_gap_assessments.belongsTo(db.users, {
as: 'createdBy',
});
db.knowledge_gap_assessments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return knowledge_gap_assessments;
};

View File

@ -0,0 +1,197 @@
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 kpi_definitions = sequelize.define(
'kpi_definitions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
kpi_name: {
type: DataTypes.TEXT,
},
kpi_key: {
type: DataTypes.TEXT,
},
unit: {
type: DataTypes.ENUM,
values: [
"number",
"percent",
"seconds",
"minutes",
"currency"
],
},
direction: {
type: DataTypes.ENUM,
values: [
"higher_is_better",
"lower_is_better"
],
},
target_value: {
type: DataTypes.DECIMAL,
},
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,
},
);
kpi_definitions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.kpi_definitions.hasMany(db.kpi_measurements, {
as: 'kpi_measurements_kpi_definition',
foreignKey: {
name: 'kpi_definitionId',
},
constraints: false,
});
//end loop
db.kpi_definitions.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.kpi_definitions.belongsTo(db.users, {
as: 'createdBy',
});
db.kpi_definitions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return kpi_definitions;
};

View File

@ -0,0 +1,166 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const kpi_measurements = sequelize.define(
'kpi_measurements',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
measured_at: {
type: DataTypes.DATE,
},
value: {
type: DataTypes.DECIMAL,
},
source: {
type: DataTypes.ENUM,
values: [
"manual",
"import",
"integration"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
kpi_measurements.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.kpi_measurements.belongsTo(db.kpi_definitions, {
as: 'kpi_definition',
foreignKey: {
name: 'kpi_definitionId',
},
constraints: false,
});
db.kpi_measurements.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.kpi_measurements.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.kpi_measurements.belongsTo(db.users, {
as: 'createdBy',
});
db.kpi_measurements.belongsTo(db.users, {
as: 'updatedBy',
});
};
return kpi_measurements;
};

View File

@ -0,0 +1,166 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const learning_paths = sequelize.define(
'learning_paths',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
path_name: {
type: DataTypes.TEXT,
},
audience: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"archived"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
learning_paths.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.learning_paths.hasMany(db.missions, {
as: 'missions_learning_path',
foreignKey: {
name: 'learning_pathId',
},
constraints: false,
});
//end loop
db.learning_paths.belongsTo(db.programs, {
as: 'program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
db.learning_paths.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.learning_paths.belongsTo(db.users, {
as: 'createdBy',
});
db.learning_paths.belongsTo(db.users, {
as: 'updatedBy',
});
};
return learning_paths;
};

View File

@ -0,0 +1,212 @@
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 mission_attempts = sequelize.define(
'mission_attempts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
attempt_status: {
type: DataTypes.ENUM,
values: [
"not_started",
"in_progress",
"submitted",
"completed",
"failed",
"skipped"
],
},
started_at: {
type: DataTypes.DATE,
},
submitted_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
score: {
type: DataTypes.DECIMAL,
},
points_earned: {
type: DataTypes.DECIMAL,
},
coins_earned: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
mission_attempts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.mission_attempts.hasMany(db.quiz_submissions, {
as: 'quiz_submissions_mission_attempt',
foreignKey: {
name: 'mission_attemptId',
},
constraints: false,
});
//end loop
db.mission_attempts.belongsTo(db.missions, {
as: 'mission',
foreignKey: {
name: 'missionId',
},
constraints: false,
});
db.mission_attempts.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.mission_attempts.belongsTo(db.enrollments, {
as: 'enrollment',
foreignKey: {
name: 'enrollmentId',
},
constraints: false,
});
db.mission_attempts.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.mission_attempts.belongsTo(db.users, {
as: 'createdBy',
});
db.mission_attempts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return mission_attempts;
};

View File

@ -0,0 +1,265 @@
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 missions = sequelize.define(
'missions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
mission_title: {
type: DataTypes.TEXT,
},
mission_code: {
type: DataTypes.TEXT,
},
mission_type: {
type: DataTypes.ENUM,
values: [
"video",
"document",
"quiz",
"simulation",
"task",
"checklist_item"
],
},
sequence_order: {
type: DataTypes.INTEGER,
},
estimated_minutes: {
type: DataTypes.INTEGER,
},
instructions: {
type: DataTypes.TEXT,
},
video_url: {
type: DataTypes.TEXT,
},
is_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
points_awarded: {
type: DataTypes.DECIMAL,
},
coins_awarded: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"archived"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
missions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.missions.hasMany(db.mission_attempts, {
as: 'mission_attempts_mission',
foreignKey: {
name: 'missionId',
},
constraints: false,
});
db.missions.hasMany(db.quizzes, {
as: 'quizzes_mission',
foreignKey: {
name: 'missionId',
},
constraints: false,
});
db.missions.hasMany(db.simulations, {
as: 'simulations_mission',
foreignKey: {
name: 'missionId',
},
constraints: false,
});
//end loop
db.missions.belongsTo(db.learning_paths, {
as: 'learning_path',
foreignKey: {
name: 'learning_pathId',
},
constraints: false,
});
db.missions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.missions.hasMany(db.file, {
as: 'resource_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.missions.getTableName(),
belongsToColumn: 'resource_files',
},
});
db.missions.belongsTo(db.users, {
as: 'createdBy',
});
db.missions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return missions;
};

View File

@ -0,0 +1,437 @@
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 organizations = sequelize.define(
'organizations',
{
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,
},
);
organizations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.organizations.hasMany(db.users, {
as: 'users_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.role_permissions, {
as: 'role_permissions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.role_assignments, {
as: 'role_assignments_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.teams, {
as: 'teams_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.team_memberships, {
as: 'team_memberships_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.programs, {
as: 'programs_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.learning_paths, {
as: 'learning_paths_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.missions, {
as: 'missions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.checklists, {
as: 'checklists_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.checklist_items, {
as: 'checklist_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.enrollments, {
as: 'enrollments_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.mission_attempts, {
as: 'mission_attempts_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.quizzes, {
as: 'quizzes_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.quiz_questions, {
as: 'quiz_questions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.quiz_choices, {
as: 'quiz_choices_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.quiz_submissions, {
as: 'quiz_submissions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.quiz_answers, {
as: 'quiz_answers_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.simulations, {
as: 'simulations_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.simulation_steps, {
as: 'simulation_steps_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.content_assets, {
as: 'content_assets_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.ai_content_requests, {
as: 'ai_content_requests_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.knowledge_gap_assessments, {
as: 'knowledge_gap_assessments_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.badges, {
as: 'badges_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.user_badges, {
as: 'user_badges_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.point_ledger_entries, {
as: 'point_ledger_entries_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.challenges, {
as: 'challenges_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.challenge_participants, {
as: 'challenge_participants_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.reward_catalog_items, {
as: 'reward_catalog_items_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.reward_redemptions, {
as: 'reward_redemptions_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.recognition_posts, {
as: 'recognition_posts_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.coaching_sessions, {
as: 'coaching_sessions_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.kpi_definitions, {
as: 'kpi_definitions_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.kpi_measurements, {
as: 'kpi_measurements_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.qa_evaluations, {
as: 'qa_evaluations_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.qa_scorecards, {
as: 'qa_scorecards_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.surveys, {
as: 'surveys_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.survey_questions, {
as: 'survey_questions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.survey_responses, {
as: 'survey_responses_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.survey_response_items, {
as: 'survey_response_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.reports, {
as: 'reports_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.audit_events, {
as: 'audit_events_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
//end loop
db.organizations.belongsTo(db.users, {
as: 'createdBy',
});
db.organizations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return organizations;
};

View File

@ -0,0 +1,117 @@
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
db.permissions.hasMany(db.role_permissions, {
as: 'role_permissions_permission',
foreignKey: {
name: 'permissionId',
},
constraints: false,
});
//end loop
db.permissions.belongsTo(db.users, {
as: 'createdBy',
});
db.permissions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return permissions;
};

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 point_ledger_entries = sequelize.define(
'point_ledger_entries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
entry_type: {
type: DataTypes.ENUM,
values: [
"mission",
"kpi",
"challenge",
"recognition",
"manual_adjustment",
"redemption"
],
},
points_delta: {
type: DataTypes.DECIMAL,
},
coins_delta: {
type: DataTypes.DECIMAL,
},
reason: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
point_ledger_entries.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.point_ledger_entries.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.point_ledger_entries.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.point_ledger_entries.belongsTo(db.users, {
as: 'createdBy',
});
db.point_ledger_entries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return point_ledger_entries;
};

View File

@ -0,0 +1,184 @@
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 programs = sequelize.define(
'programs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
program_name: {
type: DataTypes.TEXT,
},
program_type: {
type: DataTypes.ENUM,
values: [
"preboarding",
"onboarding",
"continuous"
],
},
description: {
type: DataTypes.TEXT,
},
is_published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
published_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
programs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.programs.hasMany(db.learning_paths, {
as: 'learning_paths_program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
db.programs.hasMany(db.checklists, {
as: 'checklists_program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
db.programs.hasMany(db.enrollments, {
as: 'enrollments_program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
//end loop
db.programs.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.programs.belongsTo(db.users, {
as: 'createdBy',
});
db.programs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return programs;
};

View File

@ -0,0 +1,210 @@
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 qa_evaluations = sequelize.define(
'qa_evaluations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
channel: {
type: DataTypes.ENUM,
values: [
"call",
"chat",
"email",
"in_person"
],
},
interaction_reference: {
type: DataTypes.TEXT,
},
interaction_at: {
type: DataTypes.DATE,
},
evaluated_at: {
type: DataTypes.DATE,
},
overall_score: {
type: DataTypes.DECIMAL,
},
result: {
type: DataTypes.ENUM,
values: [
"pass",
"needs_improvement",
"fail"
],
},
summary_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
qa_evaluations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.qa_evaluations.hasMany(db.qa_scorecards, {
as: 'qa_scorecards_qa_evaluation',
foreignKey: {
name: 'qa_evaluationId',
},
constraints: false,
});
//end loop
db.qa_evaluations.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.qa_evaluations.belongsTo(db.users, {
as: 'evaluator',
foreignKey: {
name: 'evaluatorId',
},
constraints: false,
});
db.qa_evaluations.belongsTo(db.users, {
as: 'agent',
foreignKey: {
name: 'agentId',
},
constraints: false,
});
db.qa_evaluations.belongsTo(db.users, {
as: 'createdBy',
});
db.qa_evaluations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return qa_evaluations;
};

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 qa_scorecards = sequelize.define(
'qa_scorecards',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
category_name: {
type: DataTypes.TEXT,
},
category_score: {
type: DataTypes.DECIMAL,
},
max_score: {
type: DataTypes.DECIMAL,
},
comments: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
qa_scorecards.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.qa_scorecards.belongsTo(db.qa_evaluations, {
as: 'qa_evaluation',
foreignKey: {
name: 'qa_evaluationId',
},
constraints: false,
});
db.qa_scorecards.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.qa_scorecards.belongsTo(db.users, {
as: 'createdBy',
});
db.qa_scorecards.belongsTo(db.users, {
as: 'updatedBy',
});
};
return qa_scorecards;
};

View File

@ -0,0 +1,150 @@
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 quiz_answers = sequelize.define(
'quiz_answers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
answer_text: {
type: DataTypes.TEXT,
},
is_correct: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
points_earned: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
quiz_answers.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.quiz_answers.belongsTo(db.quiz_submissions, {
as: 'quiz_submission',
foreignKey: {
name: 'quiz_submissionId',
},
constraints: false,
});
db.quiz_answers.belongsTo(db.quiz_questions, {
as: 'quiz_question',
foreignKey: {
name: 'quiz_questionId',
},
constraints: false,
});
db.quiz_answers.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.quiz_answers.belongsTo(db.users, {
as: 'createdBy',
});
db.quiz_answers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return quiz_answers;
};

View File

@ -0,0 +1,142 @@
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 quiz_choices = sequelize.define(
'quiz_choices',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
choice_text: {
type: DataTypes.TEXT,
},
is_correct: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
sequence_order: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
quiz_choices.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.quiz_choices.belongsTo(db.quiz_questions, {
as: 'quiz_question',
foreignKey: {
name: 'quiz_questionId',
},
constraints: false,
});
db.quiz_choices.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.quiz_choices.belongsTo(db.users, {
as: 'createdBy',
});
db.quiz_choices.belongsTo(db.users, {
as: 'updatedBy',
});
};
return quiz_choices;
};

View File

@ -0,0 +1,177 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const quiz_questions = sequelize.define(
'quiz_questions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
question_type: {
type: DataTypes.ENUM,
values: [
"multiple_choice",
"multi_select",
"true_false",
"short_answer"
],
},
prompt: {
type: DataTypes.TEXT,
},
sequence_order: {
type: DataTypes.INTEGER,
},
points: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
quiz_questions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.quiz_questions.hasMany(db.quiz_choices, {
as: 'quiz_choices_quiz_question',
foreignKey: {
name: 'quiz_questionId',
},
constraints: false,
});
db.quiz_questions.hasMany(db.quiz_answers, {
as: 'quiz_answers_quiz_question',
foreignKey: {
name: 'quiz_questionId',
},
constraints: false,
});
//end loop
db.quiz_questions.belongsTo(db.quizzes, {
as: 'quiz',
foreignKey: {
name: 'quizId',
},
constraints: false,
});
db.quiz_questions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.quiz_questions.belongsTo(db.users, {
as: 'createdBy',
});
db.quiz_questions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return quiz_questions;
};

View File

@ -0,0 +1,166 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const quiz_submissions = sequelize.define(
'quiz_submissions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
submitted_at: {
type: DataTypes.DATE,
},
score: {
type: DataTypes.DECIMAL,
},
is_passed: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
quiz_submissions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.quiz_submissions.hasMany(db.quiz_answers, {
as: 'quiz_answers_quiz_submission',
foreignKey: {
name: 'quiz_submissionId',
},
constraints: false,
});
//end loop
db.quiz_submissions.belongsTo(db.quizzes, {
as: 'quiz',
foreignKey: {
name: 'quizId',
},
constraints: false,
});
db.quiz_submissions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.quiz_submissions.belongsTo(db.mission_attempts, {
as: 'mission_attempt',
foreignKey: {
name: 'mission_attemptId',
},
constraints: false,
});
db.quiz_submissions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.quiz_submissions.belongsTo(db.users, {
as: 'createdBy',
});
db.quiz_submissions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return quiz_submissions;
};

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 quizzes = sequelize.define(
'quizzes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
quiz_title: {
type: DataTypes.TEXT,
},
grading_method: {
type: DataTypes.ENUM,
values: [
"auto",
"manual"
],
},
passing_score: {
type: DataTypes.DECIMAL,
},
shuffle_questions: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
quizzes.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.quizzes.hasMany(db.quiz_questions, {
as: 'quiz_questions_quiz',
foreignKey: {
name: 'quizId',
},
constraints: false,
});
db.quizzes.hasMany(db.quiz_submissions, {
as: 'quiz_submissions_quiz',
foreignKey: {
name: 'quizId',
},
constraints: false,
});
//end loop
db.quizzes.belongsTo(db.missions, {
as: 'mission',
foreignKey: {
name: 'missionId',
},
constraints: false,
});
db.quizzes.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.quizzes.belongsTo(db.users, {
as: 'createdBy',
});
db.quizzes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return quizzes;
};

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 recognition_posts = sequelize.define(
'recognition_posts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
recognition_type: {
type: DataTypes.ENUM,
values: [
"kudos",
"coaching_win",
"milestone",
"values"
],
},
message: {
type: DataTypes.TEXT,
},
points_awarded: {
type: DataTypes.DECIMAL,
},
coins_awarded: {
type: DataTypes.DECIMAL,
},
posted_at: {
type: DataTypes.DATE,
},
is_public: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
recognition_posts.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.recognition_posts.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.recognition_posts.belongsTo(db.users, {
as: 'from_user',
foreignKey: {
name: 'from_userId',
},
constraints: false,
});
db.recognition_posts.belongsTo(db.users, {
as: 'to_user',
foreignKey: {
name: 'to_userId',
},
constraints: false,
});
db.recognition_posts.hasMany(db.file, {
as: 'media_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.recognition_posts.getTableName(),
belongsToColumn: 'media_images',
},
});
db.recognition_posts.belongsTo(db.users, {
as: 'createdBy',
});
db.recognition_posts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return recognition_posts;
};

View File

@ -0,0 +1,211 @@
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 reports = sequelize.define(
'reports',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
report_name: {
type: DataTypes.TEXT,
},
report_type: {
type: DataTypes.ENUM,
values: [
"completion_rates",
"attrition",
"speed_to_proficiency",
"challenge_outcomes",
"kpi_trends",
"qa_scores",
"survey_insights"
],
},
period_type: {
type: DataTypes.ENUM,
values: [
"daily",
"weekly",
"monthly",
"quarterly",
"custom"
],
},
period_start_at: {
type: DataTypes.DATE,
},
period_end_at: {
type: DataTypes.DATE,
},
filters_json: {
type: DataTypes.TEXT,
},
generated_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
reports.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.reports.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.reports.hasMany(db.file, {
as: 'export_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.reports.getTableName(),
belongsToColumn: 'export_files',
},
});
db.reports.belongsTo(db.users, {
as: 'createdBy',
});
db.reports.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reports;
};

View File

@ -0,0 +1,188 @@
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 reward_catalog_items = sequelize.define(
'reward_catalog_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
item_name: {
type: DataTypes.TEXT,
},
item_type: {
type: DataTypes.ENUM,
values: [
"gift_card",
"swag",
"perk",
"pto"
],
},
description: {
type: DataTypes.TEXT,
},
cost_coins: {
type: DataTypes.DECIMAL,
},
inventory_quantity: {
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,
},
);
reward_catalog_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.reward_catalog_items.hasMany(db.reward_redemptions, {
as: 'reward_redemptions_reward_catalog_item',
foreignKey: {
name: 'reward_catalog_itemId',
},
constraints: false,
});
//end loop
db.reward_catalog_items.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.reward_catalog_items.hasMany(db.file, {
as: 'item_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.reward_catalog_items.getTableName(),
belongsToColumn: 'item_images',
},
});
db.reward_catalog_items.belongsTo(db.users, {
as: 'createdBy',
});
db.reward_catalog_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reward_catalog_items;
};

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