Initial version

This commit is contained in:
Flatlogic Bot 2026-03-22 10:08:46 +00:00
commit 0cf5c23882
691 changed files with 241580 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>ISO13485 QMS Manager</h2>
<p>Internal ISO 13485 QMS manager for controlled documents, templates, approvals, training, and audit trails.</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 @@
# ISO13485 QMS Manager
## 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_39263
DB_USER=app_39263
DB_PASS=f532edb0-5987-410a-bbe0-c45b7be49320
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 @@
#ISO13485 QMS Manager - 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_iso13485_qms_manager;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_iso13485_qms_manager 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": "iso13485qmsmanager",
"description": "ISO13485 QMS Manager - template backend",
"scripts": {
"start": "npm run db:migrate && npm run db:seed && npm run watch",
"lint": "eslint . --ext .js",
"db:migrate": "sequelize-cli db:migrate",
"db:seed": "sequelize-cli db:seed:all",
"db:drop": "sequelize-cli db:drop",
"db:create": "sequelize-cli db:create",
"watch": "node watcher.js"
},
"dependencies": {
"@google-cloud/storage": "^5.18.2",
"axios": "^1.6.7",
"bcrypt": "5.1.1",
"chokidar": "^4.0.3",
"cors": "2.8.5",
"csv-parser": "^3.0.0",
"express": "4.18.2",
"formidable": "1.2.2",
"helmet": "4.1.1",
"json2csv": "^5.0.7",
"jsonwebtoken": "8.5.1",
"lodash": "4.17.21",
"moment": "2.30.1",
"multer": "^1.4.4",
"mysql2": "2.2.5",
"nodemailer": "6.9.9",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
"passport-jwt": "^4.0.1",
"passport-microsoft": "^0.1.0",
"pg": "8.4.1",
"pg-hstore": "2.3.4",
"sequelize": "6.35.2",
"sequelize-json-schema": "^2.1.1",
"sqlite": "4.0.15",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0",
"tedious": "^18.2.4"
},
"engines": {
"node": ">=18"
},
"private": true,
"devDependencies": {
"cross-env": "7.0.3",
"eslint": "^8.23.1",
"eslint-plugin-import": "^2.29.1",
"mocha": "8.1.3",
"node-mocks-http": "1.9.0",
"nodemon": "2.0.5",
"sequelize-cli": "6.6.2"
}
}

View File

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

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

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

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

@ -0,0 +1,79 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "f532edb0",
user_pass: "c45b7be49320",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'f532edb0-5987-410a-bbe0-c45b7be49320',
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: 'ISO13485 QMS Manager <app@flatlogic.app>',
host: 'email-smtp.us-east-1.amazonaws.com',
port: 587,
auth: {
user: process.env.EMAIL_USER || '',
pass: process.env.EMAIL_PASS,
},
tls: {
rejectUnauthorized: false
}
},
roles: {
admin: 'Administrator',
user: 'External Auditor',
},
project_uuid: 'f532edb0-5987-410a-bbe0-c45b7be49320',
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 = 'Lighthouse on calm coast';
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,571 @@
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 Approval_stepsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.create(
{
id: data.id || undefined,
step_order: data.step_order
||
null
,
step_name: data.step_name
||
null
,
step_type: data.step_type
||
null
,
assignment_rule: data.assignment_rule
||
null
,
sla_days: data.sla_days
||
null
,
required: data.required
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await approval_steps.setWorkflow( data.workflow || null, {
transaction,
});
await approval_steps.setAssignee( data.assignee || null, {
transaction,
});
return approval_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 approval_stepsData = data.map((item, index) => ({
id: item.id || undefined,
step_order: item.step_order
||
null
,
step_name: item.step_name
||
null
,
step_type: item.step_type
||
null
,
assignment_rule: item.assignment_rule
||
null
,
sla_days: item.sla_days
||
null
,
required: item.required
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const approval_steps = await db.approval_steps.bulkCreate(approval_stepsData, { transaction });
// For each item created, replace relation files
return approval_steps;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.step_order !== undefined) updatePayload.step_order = data.step_order;
if (data.step_name !== undefined) updatePayload.step_name = data.step_name;
if (data.step_type !== undefined) updatePayload.step_type = data.step_type;
if (data.assignment_rule !== undefined) updatePayload.assignment_rule = data.assignment_rule;
if (data.sla_days !== undefined) updatePayload.sla_days = data.sla_days;
if (data.required !== undefined) updatePayload.required = data.required;
updatePayload.updatedById = currentUser.id;
await approval_steps.update(updatePayload, {transaction});
if (data.workflow !== undefined) {
await approval_steps.setWorkflow(
data.workflow,
{ transaction }
);
}
if (data.assignee !== undefined) {
await approval_steps.setAssignee(
data.assignee,
{ transaction }
);
}
return approval_steps;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of approval_steps) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of approval_steps) {
await record.destroy({transaction});
}
});
return approval_steps;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.findByPk(id, options);
await approval_steps.update({
deletedBy: currentUser.id
}, {
transaction,
});
await approval_steps.destroy({
transaction
});
return approval_steps;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.findOne(
{ where },
{ transaction },
);
if (!approval_steps) {
return approval_steps;
}
const output = approval_steps.get({plain: true});
output.approval_tasks_step = await approval_steps.getApproval_tasks_step({
transaction
});
output.workflow = await approval_steps.getWorkflow({
transaction
});
output.assignee = await approval_steps.getAssignee({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.approval_workflows,
as: 'workflow',
where: filter.workflow ? {
[Op.or]: [
{ id: { [Op.in]: filter.workflow.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workflow.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assignee',
where: filter.assignee ? {
[Op.or]: [
{ id: { [Op.in]: filter.assignee.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assignee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.step_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'approval_steps',
'step_name',
filter.step_name,
),
};
}
if (filter.step_orderRange) {
const [start, end] = filter.step_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
step_order: {
...where.step_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
step_order: {
...where.step_order,
[Op.lte]: end,
},
};
}
}
if (filter.sla_daysRange) {
const [start, end] = filter.sla_daysRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sla_days: {
...where.sla_days,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sla_days: {
...where.sla_days,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.step_type) {
where = {
...where,
step_type: filter.step_type,
};
}
if (filter.assignment_rule) {
where = {
...where,
assignment_rule: filter.assignment_rule,
};
}
if (filter.required) {
where = {
...where,
required: filter.required,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.approval_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'approval_steps',
'step_name',
query,
),
],
};
}
const records = await db.approval_steps.findAll({
attributes: [ 'id', 'step_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['step_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.step_name,
}));
}
};

View File

@ -0,0 +1,648 @@
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 Approval_tasksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approval_tasks = await db.approval_tasks.create(
{
id: data.id || undefined,
subject_type: data.subject_type
||
null
,
subject_reference: data.subject_reference
||
null
,
status: data.status
||
null
,
assigned_at: data.assigned_at
||
null
,
completed_at: data.completed_at
||
null
,
decision_comment: data.decision_comment
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await approval_tasks.setWorkflow( data.workflow || null, {
transaction,
});
await approval_tasks.setStep( data.step || null, {
transaction,
});
await approval_tasks.setAssignee( data.assignee || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.approval_tasks.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: approval_tasks.id,
},
data.evidence_files,
options,
);
return approval_tasks;
}
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 approval_tasksData = data.map((item, index) => ({
id: item.id || undefined,
subject_type: item.subject_type
||
null
,
subject_reference: item.subject_reference
||
null
,
status: item.status
||
null
,
assigned_at: item.assigned_at
||
null
,
completed_at: item.completed_at
||
null
,
decision_comment: item.decision_comment
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const approval_tasks = await db.approval_tasks.bulkCreate(approval_tasksData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < approval_tasks.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.approval_tasks.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: approval_tasks[i].id,
},
data[i].evidence_files,
options,
);
}
return approval_tasks;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const approval_tasks = await db.approval_tasks.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.subject_type !== undefined) updatePayload.subject_type = data.subject_type;
if (data.subject_reference !== undefined) updatePayload.subject_reference = data.subject_reference;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.decision_comment !== undefined) updatePayload.decision_comment = data.decision_comment;
updatePayload.updatedById = currentUser.id;
await approval_tasks.update(updatePayload, {transaction});
if (data.workflow !== undefined) {
await approval_tasks.setWorkflow(
data.workflow,
{ transaction }
);
}
if (data.step !== undefined) {
await approval_tasks.setStep(
data.step,
{ transaction }
);
}
if (data.assignee !== undefined) {
await approval_tasks.setAssignee(
data.assignee,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.approval_tasks.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: approval_tasks.id,
},
data.evidence_files,
options,
);
return approval_tasks;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approval_tasks = await db.approval_tasks.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of approval_tasks) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of approval_tasks) {
await record.destroy({transaction});
}
});
return approval_tasks;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const approval_tasks = await db.approval_tasks.findByPk(id, options);
await approval_tasks.update({
deletedBy: currentUser.id
}, {
transaction,
});
await approval_tasks.destroy({
transaction
});
return approval_tasks;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const approval_tasks = await db.approval_tasks.findOne(
{ where },
{ transaction },
);
if (!approval_tasks) {
return approval_tasks;
}
const output = approval_tasks.get({plain: true});
output.workflow = await approval_tasks.getWorkflow({
transaction
});
output.step = await approval_tasks.getStep({
transaction
});
output.assignee = await approval_tasks.getAssignee({
transaction
});
output.evidence_files = await approval_tasks.getEvidence_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.approval_workflows,
as: 'workflow',
where: filter.workflow ? {
[Op.or]: [
{ id: { [Op.in]: filter.workflow.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workflow.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.approval_steps,
as: 'step',
where: filter.step ? {
[Op.or]: [
{ id: { [Op.in]: filter.step.split('|').map(term => Utils.uuid(term)) } },
{
step_name: {
[Op.or]: filter.step.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assignee',
where: filter.assignee ? {
[Op.or]: [
{ id: { [Op.in]: filter.assignee.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assignee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'evidence_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.subject_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'approval_tasks',
'subject_reference',
filter.subject_reference,
),
};
}
if (filter.decision_comment) {
where = {
...where,
[Op.and]: Utils.ilike(
'approval_tasks',
'decision_comment',
filter.decision_comment,
),
};
}
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.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.subject_type) {
where = {
...where,
subject_type: filter.subject_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.approval_tasks.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(
'approval_tasks',
'subject_reference',
query,
),
],
};
}
const records = await db.approval_tasks.findAll({
attributes: [ 'id', 'subject_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['subject_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.subject_reference,
}));
}
};

View File

@ -0,0 +1,512 @@
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 Approval_workflowsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approval_workflows = await db.approval_workflows.create(
{
id: data.id || undefined,
name: data.name
||
null
,
applies_to: data.applies_to
||
null
,
requires_esignature: data.requires_esignature
||
false
,
requires_two_factor: data.requires_two_factor
||
false
,
min_approvals: data.min_approvals
||
null
,
instructions: data.instructions
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return approval_workflows;
}
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 approval_workflowsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
applies_to: item.applies_to
||
null
,
requires_esignature: item.requires_esignature
||
false
,
requires_two_factor: item.requires_two_factor
||
false
,
min_approvals: item.min_approvals
||
null
,
instructions: item.instructions
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const approval_workflows = await db.approval_workflows.bulkCreate(approval_workflowsData, { transaction });
// For each item created, replace relation files
return approval_workflows;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const approval_workflows = await db.approval_workflows.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.applies_to !== undefined) updatePayload.applies_to = data.applies_to;
if (data.requires_esignature !== undefined) updatePayload.requires_esignature = data.requires_esignature;
if (data.requires_two_factor !== undefined) updatePayload.requires_two_factor = data.requires_two_factor;
if (data.min_approvals !== undefined) updatePayload.min_approvals = data.min_approvals;
if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await approval_workflows.update(updatePayload, {transaction});
return approval_workflows;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approval_workflows = await db.approval_workflows.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of approval_workflows) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of approval_workflows) {
await record.destroy({transaction});
}
});
return approval_workflows;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const approval_workflows = await db.approval_workflows.findByPk(id, options);
await approval_workflows.update({
deletedBy: currentUser.id
}, {
transaction,
});
await approval_workflows.destroy({
transaction
});
return approval_workflows;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const approval_workflows = await db.approval_workflows.findOne(
{ where },
{ transaction },
);
if (!approval_workflows) {
return approval_workflows;
}
const output = approval_workflows.get({plain: true});
output.approval_steps_workflow = await approval_workflows.getApproval_steps_workflow({
transaction
});
output.approval_tasks_workflow = await approval_workflows.getApproval_tasks_workflow({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'approval_workflows',
'name',
filter.name,
),
};
}
if (filter.instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'approval_workflows',
'instructions',
filter.instructions,
),
};
}
if (filter.min_approvalsRange) {
const [start, end] = filter.min_approvalsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_approvals: {
...where.min_approvals,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_approvals: {
...where.min_approvals,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.applies_to) {
where = {
...where,
applies_to: filter.applies_to,
};
}
if (filter.requires_esignature) {
where = {
...where,
requires_esignature: filter.requires_esignature,
};
}
if (filter.requires_two_factor) {
where = {
...where,
requires_two_factor: filter.requires_two_factor,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.approval_workflows.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(
'approval_workflows',
'name',
query,
),
],
};
}
const records = await db.approval_workflows.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,672 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Audit_findingsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_findings = await db.audit_findings.create(
{
id: data.id || undefined,
finding_number: data.finding_number
||
null
,
severity: data.severity
||
null
,
status: data.status
||
null
,
description: data.description
||
null
,
objective_evidence: data.objective_evidence
||
null
,
due_at: data.due_at
||
null
,
closed_at: data.closed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audit_findings.setAudit( data.audit || null, {
transaction,
});
await audit_findings.setOwner( data.owner || null, {
transaction,
});
await audit_findings.setRelated_capa( data.related_capa || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.audit_findings.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: audit_findings.id,
},
data.evidence_files,
options,
);
return audit_findings;
}
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_findingsData = data.map((item, index) => ({
id: item.id || undefined,
finding_number: item.finding_number
||
null
,
severity: item.severity
||
null
,
status: item.status
||
null
,
description: item.description
||
null
,
objective_evidence: item.objective_evidence
||
null
,
due_at: item.due_at
||
null
,
closed_at: item.closed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const audit_findings = await db.audit_findings.bulkCreate(audit_findingsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < audit_findings.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.audit_findings.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: audit_findings[i].id,
},
data[i].evidence_files,
options,
);
}
return audit_findings;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_findings = await db.audit_findings.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.finding_number !== undefined) updatePayload.finding_number = data.finding_number;
if (data.severity !== undefined) updatePayload.severity = data.severity;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.objective_evidence !== undefined) updatePayload.objective_evidence = data.objective_evidence;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
updatePayload.updatedById = currentUser.id;
await audit_findings.update(updatePayload, {transaction});
if (data.audit !== undefined) {
await audit_findings.setAudit(
data.audit,
{ transaction }
);
}
if (data.owner !== undefined) {
await audit_findings.setOwner(
data.owner,
{ transaction }
);
}
if (data.related_capa !== undefined) {
await audit_findings.setRelated_capa(
data.related_capa,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.audit_findings.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: audit_findings.id,
},
data.evidence_files,
options,
);
return audit_findings;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_findings = await db.audit_findings.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of audit_findings) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of audit_findings) {
await record.destroy({transaction});
}
});
return audit_findings;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_findings = await db.audit_findings.findByPk(id, options);
await audit_findings.update({
deletedBy: currentUser.id
}, {
transaction,
});
await audit_findings.destroy({
transaction
});
return audit_findings;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const audit_findings = await db.audit_findings.findOne(
{ where },
{ transaction },
);
if (!audit_findings) {
return audit_findings;
}
const output = audit_findings.get({plain: true});
output.audit = await audit_findings.getAudit({
transaction
});
output.owner = await audit_findings.getOwner({
transaction
});
output.evidence_files = await audit_findings.getEvidence_files({
transaction
});
output.related_capa = await audit_findings.getRelated_capa({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.audits,
as: 'audit',
where: filter.audit ? {
[Op.or]: [
{ id: { [Op.in]: filter.audit.split('|').map(term => Utils.uuid(term)) } },
{
audit_number: {
[Op.or]: filter.audit.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.capas,
as: 'related_capa',
where: filter.related_capa ? {
[Op.or]: [
{ id: { [Op.in]: filter.related_capa.split('|').map(term => Utils.uuid(term)) } },
{
capa_number: {
[Op.or]: filter.related_capa.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'evidence_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.finding_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_findings',
'finding_number',
filter.finding_number,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_findings',
'description',
filter.description,
),
};
}
if (filter.objective_evidence) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_findings',
'objective_evidence',
filter.objective_evidence,
),
};
}
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.closed_atRange) {
const [start, end] = filter.closed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.severity) {
where = {
...where,
severity: filter.severity,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.audit_findings.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'audit_findings',
'finding_number',
query,
),
],
};
}
const records = await db.audit_findings.findAll({
attributes: [ 'id', 'finding_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['finding_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.finding_number,
}));
}
};

View File

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

View File

@ -0,0 +1,699 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class AuditsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audits = await db.audits.create(
{
id: data.id || undefined,
audit_number: data.audit_number
||
null
,
audit_type: data.audit_type
||
null
,
status: data.status
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
scope: data.scope
||
null
,
summary: data.summary
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audits.setLead_auditor( data.lead_auditor || null, {
transaction,
});
await audits.setSupplier( data.supplier || null, {
transaction,
});
await audits.setMapped_clauses(data.mapped_clauses || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.audits.getTableName(),
belongsToColumn: 'audit_files',
belongsToId: audits.id,
},
data.audit_files,
options,
);
return audits;
}
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 auditsData = data.map((item, index) => ({
id: item.id || undefined,
audit_number: item.audit_number
||
null
,
audit_type: item.audit_type
||
null
,
status: item.status
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
scope: item.scope
||
null
,
summary: item.summary
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const audits = await db.audits.bulkCreate(auditsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < audits.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.audits.getTableName(),
belongsToColumn: 'audit_files',
belongsToId: audits[i].id,
},
data[i].audit_files,
options,
);
}
return audits;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audits = await db.audits.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.audit_number !== undefined) updatePayload.audit_number = data.audit_number;
if (data.audit_type !== undefined) updatePayload.audit_type = data.audit_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.scope !== undefined) updatePayload.scope = data.scope;
if (data.summary !== undefined) updatePayload.summary = data.summary;
updatePayload.updatedById = currentUser.id;
await audits.update(updatePayload, {transaction});
if (data.lead_auditor !== undefined) {
await audits.setLead_auditor(
data.lead_auditor,
{ transaction }
);
}
if (data.supplier !== undefined) {
await audits.setSupplier(
data.supplier,
{ transaction }
);
}
if (data.mapped_clauses !== undefined) {
await audits.setMapped_clauses(data.mapped_clauses, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.audits.getTableName(),
belongsToColumn: 'audit_files',
belongsToId: audits.id,
},
data.audit_files,
options,
);
return audits;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audits = await db.audits.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of audits) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of audits) {
await record.destroy({transaction});
}
});
return audits;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audits = await db.audits.findByPk(id, options);
await audits.update({
deletedBy: currentUser.id
}, {
transaction,
});
await audits.destroy({
transaction
});
return audits;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const audits = await db.audits.findOne(
{ where },
{ transaction },
);
if (!audits) {
return audits;
}
const output = audits.get({plain: true});
output.audit_findings_audit = await audits.getAudit_findings_audit({
transaction
});
output.lead_auditor = await audits.getLead_auditor({
transaction
});
output.supplier = await audits.getSupplier({
transaction
});
output.audit_files = await audits.getAudit_files({
transaction
});
output.mapped_clauses = await audits.getMapped_clauses({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'lead_auditor',
where: filter.lead_auditor ? {
[Op.or]: [
{ id: { [Op.in]: filter.lead_auditor.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.lead_auditor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.suppliers,
as: 'supplier',
where: filter.supplier ? {
[Op.or]: [
{ id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
{
supplier_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.clauses,
as: 'mapped_clauses',
required: false,
},
{
model: db.file,
as: 'audit_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.audit_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'audits',
'audit_number',
filter.audit_number,
),
};
}
if (filter.scope) {
where = {
...where,
[Op.and]: Utils.ilike(
'audits',
'scope',
filter.scope,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'audits',
'summary',
filter.summary,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_atRange) {
const [start, end] = filter.start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.lte]: end,
},
};
}
}
if (filter.end_atRange) {
const [start, end] = filter.end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.audit_type) {
where = {
...where,
audit_type: filter.audit_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.mapped_clauses) {
const searchTerms = filter.mapped_clauses.split('|');
include = [
{
model: db.clauses,
as: 'mapped_clauses_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
clause_code: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.audits.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(
'audits',
'audit_number',
query,
),
],
};
}
const records = await db.audits.findAll({
attributes: [ 'id', 'audit_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['audit_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.audit_number,
}));
}
};

View File

@ -0,0 +1,728 @@
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 BatchesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const batches = await db.batches.create(
{
id: data.id || undefined,
batch_number: data.batch_number
||
null
,
status: data.status
||
null
,
manufacture_start_at: data.manufacture_start_at
||
null
,
manufacture_end_at: data.manufacture_end_at
||
null
,
quantity_planned: data.quantity_planned
||
null
,
quantity_produced: data.quantity_produced
||
null
,
quantity_released: data.quantity_released
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await batches.setProduct( data.product || null, {
transaction,
});
await batches.setBmr_document( data.bmr_document || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.batches.getTableName(),
belongsToColumn: 'batch_record_files',
belongsToId: batches.id,
},
data.batch_record_files,
options,
);
return batches;
}
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 batchesData = data.map((item, index) => ({
id: item.id || undefined,
batch_number: item.batch_number
||
null
,
status: item.status
||
null
,
manufacture_start_at: item.manufacture_start_at
||
null
,
manufacture_end_at: item.manufacture_end_at
||
null
,
quantity_planned: item.quantity_planned
||
null
,
quantity_produced: item.quantity_produced
||
null
,
quantity_released: item.quantity_released
||
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 batches = await db.batches.bulkCreate(batchesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < batches.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.batches.getTableName(),
belongsToColumn: 'batch_record_files',
belongsToId: batches[i].id,
},
data[i].batch_record_files,
options,
);
}
return batches;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const batches = await db.batches.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.batch_number !== undefined) updatePayload.batch_number = data.batch_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.manufacture_start_at !== undefined) updatePayload.manufacture_start_at = data.manufacture_start_at;
if (data.manufacture_end_at !== undefined) updatePayload.manufacture_end_at = data.manufacture_end_at;
if (data.quantity_planned !== undefined) updatePayload.quantity_planned = data.quantity_planned;
if (data.quantity_produced !== undefined) updatePayload.quantity_produced = data.quantity_produced;
if (data.quantity_released !== undefined) updatePayload.quantity_released = data.quantity_released;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await batches.update(updatePayload, {transaction});
if (data.product !== undefined) {
await batches.setProduct(
data.product,
{ transaction }
);
}
if (data.bmr_document !== undefined) {
await batches.setBmr_document(
data.bmr_document,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.batches.getTableName(),
belongsToColumn: 'batch_record_files',
belongsToId: batches.id,
},
data.batch_record_files,
options,
);
return batches;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const batches = await db.batches.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of batches) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of batches) {
await record.destroy({transaction});
}
});
return batches;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const batches = await db.batches.findByPk(id, options);
await batches.update({
deletedBy: currentUser.id
}, {
transaction,
});
await batches.destroy({
transaction
});
return batches;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const batches = await db.batches.findOne(
{ where },
{ transaction },
);
if (!batches) {
return batches;
}
const output = batches.get({plain: true});
output.certificates_of_analysis_batch = await batches.getCertificates_of_analysis_batch({
transaction
});
output.nonconformances_batch = await batches.getNonconformances_batch({
transaction
});
output.product = await batches.getProduct({
transaction
});
output.bmr_document = await batches.getBmr_document({
transaction
});
output.batch_record_files = await batches.getBatch_record_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.documents,
as: 'bmr_document',
where: filter.bmr_document ? {
[Op.or]: [
{ id: { [Op.in]: filter.bmr_document.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.bmr_document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'batch_record_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.batch_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'batches',
'batch_number',
filter.batch_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'batches',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
manufacture_start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
manufacture_end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.manufacture_start_atRange) {
const [start, end] = filter.manufacture_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
manufacture_start_at: {
...where.manufacture_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
manufacture_start_at: {
...where.manufacture_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.manufacture_end_atRange) {
const [start, end] = filter.manufacture_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
manufacture_end_at: {
...where.manufacture_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
manufacture_end_at: {
...where.manufacture_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.quantity_plannedRange) {
const [start, end] = filter.quantity_plannedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_planned: {
...where.quantity_planned,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_planned: {
...where.quantity_planned,
[Op.lte]: end,
},
};
}
}
if (filter.quantity_producedRange) {
const [start, end] = filter.quantity_producedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_produced: {
...where.quantity_produced,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_produced: {
...where.quantity_produced,
[Op.lte]: end,
},
};
}
}
if (filter.quantity_releasedRange) {
const [start, end] = filter.quantity_releasedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_released: {
...where.quantity_released,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_released: {
...where.quantity_released,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.batches.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(
'batches',
'batch_number',
query,
),
],
};
}
const records = await db.batches.findAll({
attributes: [ 'id', 'batch_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['batch_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.batch_number,
}));
}
};

724
backend/src/db/api/capas.js Normal file
View File

@ -0,0 +1,724 @@
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 CapasDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const capas = await db.capas.create(
{
id: data.id || undefined,
capa_number: data.capa_number
||
null
,
source: data.source
||
null
,
status: data.status
||
null
,
problem_statement: data.problem_statement
||
null
,
root_cause: data.root_cause
||
null
,
corrective_actions: data.corrective_actions
||
null
,
preventive_actions: data.preventive_actions
||
null
,
opened_at: data.opened_at
||
null
,
due_at: data.due_at
||
null
,
closed_at: data.closed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await capas.setOwner( data.owner || null, {
transaction,
});
await capas.setRelated_document( data.related_document || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.capas.getTableName(),
belongsToColumn: 'capa_files',
belongsToId: capas.id,
},
data.capa_files,
options,
);
return capas;
}
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 capasData = data.map((item, index) => ({
id: item.id || undefined,
capa_number: item.capa_number
||
null
,
source: item.source
||
null
,
status: item.status
||
null
,
problem_statement: item.problem_statement
||
null
,
root_cause: item.root_cause
||
null
,
corrective_actions: item.corrective_actions
||
null
,
preventive_actions: item.preventive_actions
||
null
,
opened_at: item.opened_at
||
null
,
due_at: item.due_at
||
null
,
closed_at: item.closed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const capas = await db.capas.bulkCreate(capasData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < capas.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.capas.getTableName(),
belongsToColumn: 'capa_files',
belongsToId: capas[i].id,
},
data[i].capa_files,
options,
);
}
return capas;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const capas = await db.capas.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.capa_number !== undefined) updatePayload.capa_number = data.capa_number;
if (data.source !== undefined) updatePayload.source = data.source;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.problem_statement !== undefined) updatePayload.problem_statement = data.problem_statement;
if (data.root_cause !== undefined) updatePayload.root_cause = data.root_cause;
if (data.corrective_actions !== undefined) updatePayload.corrective_actions = data.corrective_actions;
if (data.preventive_actions !== undefined) updatePayload.preventive_actions = data.preventive_actions;
if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
updatePayload.updatedById = currentUser.id;
await capas.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await capas.setOwner(
data.owner,
{ transaction }
);
}
if (data.related_document !== undefined) {
await capas.setRelated_document(
data.related_document,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.capas.getTableName(),
belongsToColumn: 'capa_files',
belongsToId: capas.id,
},
data.capa_files,
options,
);
return capas;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const capas = await db.capas.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of capas) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of capas) {
await record.destroy({transaction});
}
});
return capas;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const capas = await db.capas.findByPk(id, options);
await capas.update({
deletedBy: currentUser.id
}, {
transaction,
});
await capas.destroy({
transaction
});
return capas;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const capas = await db.capas.findOne(
{ where },
{ transaction },
);
if (!capas) {
return capas;
}
const output = capas.get({plain: true});
output.audit_findings_related_capa = await capas.getAudit_findings_related_capa({
transaction
});
output.owner = await capas.getOwner({
transaction
});
output.related_document = await capas.getRelated_document({
transaction
});
output.capa_files = await capas.getCapa_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.documents,
as: 'related_document',
where: filter.related_document ? {
[Op.or]: [
{ id: { [Op.in]: filter.related_document.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.related_document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'capa_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.capa_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'capas',
'capa_number',
filter.capa_number,
),
};
}
if (filter.problem_statement) {
where = {
...where,
[Op.and]: Utils.ilike(
'capas',
'problem_statement',
filter.problem_statement,
),
};
}
if (filter.root_cause) {
where = {
...where,
[Op.and]: Utils.ilike(
'capas',
'root_cause',
filter.root_cause,
),
};
}
if (filter.corrective_actions) {
where = {
...where,
[Op.and]: Utils.ilike(
'capas',
'corrective_actions',
filter.corrective_actions,
),
};
}
if (filter.preventive_actions) {
where = {
...where,
[Op.and]: Utils.ilike(
'capas',
'preventive_actions',
filter.preventive_actions,
),
};
}
if (filter.opened_atRange) {
const [start, end] = filter.opened_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
opened_at: {
...where.opened_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.closed_atRange) {
const [start, end] = filter.closed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[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.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.capas.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(
'capas',
'capa_number',
query,
),
],
};
}
const records = await db.capas.findAll({
attributes: [ 'id', 'capa_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['capa_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.capa_number,
}));
}
};

View File

@ -0,0 +1,646 @@
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 Certificates_of_analysisDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const certificates_of_analysis = await db.certificates_of_analysis.create(
{
id: data.id || undefined,
coa_number: data.coa_number
||
null
,
status: data.status
||
null
,
issued_at: data.issued_at
||
null
,
expires_at: data.expires_at
||
null
,
summary: data.summary
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await certificates_of_analysis.setBatch( data.batch || null, {
transaction,
});
await certificates_of_analysis.setSupplier( data.supplier || null, {
transaction,
});
await certificates_of_analysis.setIssued_by( data.issued_by || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.certificates_of_analysis.getTableName(),
belongsToColumn: 'coa_files',
belongsToId: certificates_of_analysis.id,
},
data.coa_files,
options,
);
return certificates_of_analysis;
}
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 certificates_of_analysisData = data.map((item, index) => ({
id: item.id || undefined,
coa_number: item.coa_number
||
null
,
status: item.status
||
null
,
issued_at: item.issued_at
||
null
,
expires_at: item.expires_at
||
null
,
summary: item.summary
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const certificates_of_analysis = await db.certificates_of_analysis.bulkCreate(certificates_of_analysisData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < certificates_of_analysis.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.certificates_of_analysis.getTableName(),
belongsToColumn: 'coa_files',
belongsToId: certificates_of_analysis[i].id,
},
data[i].coa_files,
options,
);
}
return certificates_of_analysis;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const certificates_of_analysis = await db.certificates_of_analysis.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.coa_number !== undefined) updatePayload.coa_number = data.coa_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.summary !== undefined) updatePayload.summary = data.summary;
updatePayload.updatedById = currentUser.id;
await certificates_of_analysis.update(updatePayload, {transaction});
if (data.batch !== undefined) {
await certificates_of_analysis.setBatch(
data.batch,
{ transaction }
);
}
if (data.supplier !== undefined) {
await certificates_of_analysis.setSupplier(
data.supplier,
{ transaction }
);
}
if (data.issued_by !== undefined) {
await certificates_of_analysis.setIssued_by(
data.issued_by,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.certificates_of_analysis.getTableName(),
belongsToColumn: 'coa_files',
belongsToId: certificates_of_analysis.id,
},
data.coa_files,
options,
);
return certificates_of_analysis;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const certificates_of_analysis = await db.certificates_of_analysis.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of certificates_of_analysis) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of certificates_of_analysis) {
await record.destroy({transaction});
}
});
return certificates_of_analysis;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const certificates_of_analysis = await db.certificates_of_analysis.findByPk(id, options);
await certificates_of_analysis.update({
deletedBy: currentUser.id
}, {
transaction,
});
await certificates_of_analysis.destroy({
transaction
});
return certificates_of_analysis;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const certificates_of_analysis = await db.certificates_of_analysis.findOne(
{ where },
{ transaction },
);
if (!certificates_of_analysis) {
return certificates_of_analysis;
}
const output = certificates_of_analysis.get({plain: true});
output.batch = await certificates_of_analysis.getBatch({
transaction
});
output.supplier = await certificates_of_analysis.getSupplier({
transaction
});
output.coa_files = await certificates_of_analysis.getCoa_files({
transaction
});
output.issued_by = await certificates_of_analysis.getIssued_by({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.batches,
as: 'batch',
where: filter.batch ? {
[Op.or]: [
{ id: { [Op.in]: filter.batch.split('|').map(term => Utils.uuid(term)) } },
{
batch_number: {
[Op.or]: filter.batch.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.suppliers,
as: 'supplier',
where: filter.supplier ? {
[Op.or]: [
{ id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
{
supplier_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'issued_by',
where: filter.issued_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.issued_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.issued_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'coa_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.coa_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'certificates_of_analysis',
'coa_number',
filter.coa_number,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'certificates_of_analysis',
'summary',
filter.summary,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
issued_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
expires_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.lte]: end,
},
};
}
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.certificates_of_analysis.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(
'certificates_of_analysis',
'coa_number',
query,
),
],
};
}
const records = await db.certificates_of_analysis.findAll({
attributes: [ 'id', 'coa_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['coa_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.coa_number,
}));
}
};

View File

@ -0,0 +1,753 @@
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 Change_requestsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const change_requests = await db.change_requests.create(
{
id: data.id || undefined,
change_number: data.change_number
||
null
,
change_type: data.change_type
||
null
,
status: data.status
||
null
,
reason_for_change: data.reason_for_change
||
null
,
impact_assessment: data.impact_assessment
||
null
,
requires_validation: data.requires_validation
||
false
,
requires_regulatory_notification: data.requires_regulatory_notification
||
false
,
requested_at: data.requested_at
||
null
,
due_at: data.due_at
||
null
,
closed_at: data.closed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await change_requests.setRequester( data.requester || null, {
transaction,
});
await change_requests.setDocument( data.document || null, {
transaction,
});
await change_requests.setAssigned_to( data.assigned_to || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.change_requests.getTableName(),
belongsToColumn: 'supporting_files',
belongsToId: change_requests.id,
},
data.supporting_files,
options,
);
return change_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 change_requestsData = data.map((item, index) => ({
id: item.id || undefined,
change_number: item.change_number
||
null
,
change_type: item.change_type
||
null
,
status: item.status
||
null
,
reason_for_change: item.reason_for_change
||
null
,
impact_assessment: item.impact_assessment
||
null
,
requires_validation: item.requires_validation
||
false
,
requires_regulatory_notification: item.requires_regulatory_notification
||
false
,
requested_at: item.requested_at
||
null
,
due_at: item.due_at
||
null
,
closed_at: item.closed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const change_requests = await db.change_requests.bulkCreate(change_requestsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < change_requests.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.change_requests.getTableName(),
belongsToColumn: 'supporting_files',
belongsToId: change_requests[i].id,
},
data[i].supporting_files,
options,
);
}
return change_requests;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const change_requests = await db.change_requests.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.change_number !== undefined) updatePayload.change_number = data.change_number;
if (data.change_type !== undefined) updatePayload.change_type = data.change_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.reason_for_change !== undefined) updatePayload.reason_for_change = data.reason_for_change;
if (data.impact_assessment !== undefined) updatePayload.impact_assessment = data.impact_assessment;
if (data.requires_validation !== undefined) updatePayload.requires_validation = data.requires_validation;
if (data.requires_regulatory_notification !== undefined) updatePayload.requires_regulatory_notification = data.requires_regulatory_notification;
if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
updatePayload.updatedById = currentUser.id;
await change_requests.update(updatePayload, {transaction});
if (data.requester !== undefined) {
await change_requests.setRequester(
data.requester,
{ transaction }
);
}
if (data.document !== undefined) {
await change_requests.setDocument(
data.document,
{ transaction }
);
}
if (data.assigned_to !== undefined) {
await change_requests.setAssigned_to(
data.assigned_to,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.change_requests.getTableName(),
belongsToColumn: 'supporting_files',
belongsToId: change_requests.id,
},
data.supporting_files,
options,
);
return change_requests;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const change_requests = await db.change_requests.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of change_requests) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of change_requests) {
await record.destroy({transaction});
}
});
return change_requests;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const change_requests = await db.change_requests.findByPk(id, options);
await change_requests.update({
deletedBy: currentUser.id
}, {
transaction,
});
await change_requests.destroy({
transaction
});
return change_requests;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const change_requests = await db.change_requests.findOne(
{ where },
{ transaction },
);
if (!change_requests) {
return change_requests;
}
const output = change_requests.get({plain: true});
output.requester = await change_requests.getRequester({
transaction
});
output.document = await change_requests.getDocument({
transaction
});
output.supporting_files = await change_requests.getSupporting_files({
transaction
});
output.assigned_to = await change_requests.getAssigned_to({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'requester',
where: filter.requester ? {
[Op.or]: [
{ id: { [Op.in]: filter.requester.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requester.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.documents,
as: 'document',
where: filter.document ? {
[Op.or]: [
{ id: { [Op.in]: filter.document.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assigned_to',
where: filter.assigned_to ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_to.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assigned_to.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'supporting_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.change_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'change_requests',
'change_number',
filter.change_number,
),
};
}
if (filter.reason_for_change) {
where = {
...where,
[Op.and]: Utils.ilike(
'change_requests',
'reason_for_change',
filter.reason_for_change,
),
};
}
if (filter.impact_assessment) {
where = {
...where,
[Op.and]: Utils.ilike(
'change_requests',
'impact_assessment',
filter.impact_assessment,
),
};
}
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.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.closed_atRange) {
const [start, end] = filter.closed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.change_type) {
where = {
...where,
change_type: filter.change_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.requires_validation) {
where = {
...where,
requires_validation: filter.requires_validation,
};
}
if (filter.requires_regulatory_notification) {
where = {
...where,
requires_regulatory_notification: filter.requires_regulatory_notification,
};
}
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.change_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'change_requests',
'change_number',
query,
),
],
};
}
const records = await db.change_requests.findAll({
attributes: [ 'id', 'change_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['change_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.change_number,
}));
}
};

View File

@ -0,0 +1,488 @@
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 ClausesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const clauses = await db.clauses.create(
{
id: data.id || undefined,
clause_code: data.clause_code
||
null
,
title: data.title
||
null
,
text_excerpt: data.text_excerpt
||
null
,
guidance_notes: data.guidance_notes
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await clauses.setStandard( data.standard || null, {
transaction,
});
return clauses;
}
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 clausesData = data.map((item, index) => ({
id: item.id || undefined,
clause_code: item.clause_code
||
null
,
title: item.title
||
null
,
text_excerpt: item.text_excerpt
||
null
,
guidance_notes: item.guidance_notes
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const clauses = await db.clauses.bulkCreate(clausesData, { transaction });
// For each item created, replace relation files
return clauses;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const clauses = await db.clauses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.clause_code !== undefined) updatePayload.clause_code = data.clause_code;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.text_excerpt !== undefined) updatePayload.text_excerpt = data.text_excerpt;
if (data.guidance_notes !== undefined) updatePayload.guidance_notes = data.guidance_notes;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await clauses.update(updatePayload, {transaction});
if (data.standard !== undefined) {
await clauses.setStandard(
data.standard,
{ transaction }
);
}
return clauses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const clauses = await db.clauses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of clauses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of clauses) {
await record.destroy({transaction});
}
});
return clauses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const clauses = await db.clauses.findByPk(id, options);
await clauses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await clauses.destroy({
transaction
});
return clauses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const clauses = await db.clauses.findOne(
{ where },
{ transaction },
);
if (!clauses) {
return clauses;
}
const output = clauses.get({plain: true});
output.standard = await clauses.getStandard({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.standards,
as: 'standard',
where: filter.standard ? {
[Op.or]: [
{ id: { [Op.in]: filter.standard.split('|').map(term => Utils.uuid(term)) } },
{
short_name: {
[Op.or]: filter.standard.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.clause_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'clauses',
'clause_code',
filter.clause_code,
),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'clauses',
'title',
filter.title,
),
};
}
if (filter.text_excerpt) {
where = {
...where,
[Op.and]: Utils.ilike(
'clauses',
'text_excerpt',
filter.text_excerpt,
),
};
}
if (filter.guidance_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'clauses',
'guidance_notes',
filter.guidance_notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.clauses.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(
'clauses',
'clause_code',
query,
),
],
};
}
const records = await db.clauses.findAll({
attributes: [ 'id', 'clause_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['clause_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.clause_code,
}));
}
};

View File

@ -0,0 +1,705 @@
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 ComplaintsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const complaints = await db.complaints.create(
{
id: data.id || undefined,
complaint_number: data.complaint_number
||
null
,
status: data.status
||
null
,
reporter_name: data.reporter_name
||
null
,
reporter_contact: data.reporter_contact
||
null
,
complaint_description: data.complaint_description
||
null
,
serious_injury_or_death: data.serious_injury_or_death
||
false
,
malfunction: data.malfunction
||
false
,
reportable_to_authority: data.reportable_to_authority
||
false
,
received_at: data.received_at
||
null
,
closed_at: data.closed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await complaints.setProduct( data.product || null, {
transaction,
});
await complaints.setOwner( data.owner || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.complaints.getTableName(),
belongsToColumn: 'attachments',
belongsToId: complaints.id,
},
data.attachments,
options,
);
return complaints;
}
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 complaintsData = data.map((item, index) => ({
id: item.id || undefined,
complaint_number: item.complaint_number
||
null
,
status: item.status
||
null
,
reporter_name: item.reporter_name
||
null
,
reporter_contact: item.reporter_contact
||
null
,
complaint_description: item.complaint_description
||
null
,
serious_injury_or_death: item.serious_injury_or_death
||
false
,
malfunction: item.malfunction
||
false
,
reportable_to_authority: item.reportable_to_authority
||
false
,
received_at: item.received_at
||
null
,
closed_at: item.closed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const complaints = await db.complaints.bulkCreate(complaintsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < complaints.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.complaints.getTableName(),
belongsToColumn: 'attachments',
belongsToId: complaints[i].id,
},
data[i].attachments,
options,
);
}
return complaints;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const complaints = await db.complaints.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.complaint_number !== undefined) updatePayload.complaint_number = data.complaint_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.reporter_name !== undefined) updatePayload.reporter_name = data.reporter_name;
if (data.reporter_contact !== undefined) updatePayload.reporter_contact = data.reporter_contact;
if (data.complaint_description !== undefined) updatePayload.complaint_description = data.complaint_description;
if (data.serious_injury_or_death !== undefined) updatePayload.serious_injury_or_death = data.serious_injury_or_death;
if (data.malfunction !== undefined) updatePayload.malfunction = data.malfunction;
if (data.reportable_to_authority !== undefined) updatePayload.reportable_to_authority = data.reportable_to_authority;
if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
updatePayload.updatedById = currentUser.id;
await complaints.update(updatePayload, {transaction});
if (data.product !== undefined) {
await complaints.setProduct(
data.product,
{ transaction }
);
}
if (data.owner !== undefined) {
await complaints.setOwner(
data.owner,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.complaints.getTableName(),
belongsToColumn: 'attachments',
belongsToId: complaints.id,
},
data.attachments,
options,
);
return complaints;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const complaints = await db.complaints.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of complaints) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of complaints) {
await record.destroy({transaction});
}
});
return complaints;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const complaints = await db.complaints.findByPk(id, options);
await complaints.update({
deletedBy: currentUser.id
}, {
transaction,
});
await complaints.destroy({
transaction
});
return complaints;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const complaints = await db.complaints.findOne(
{ where },
{ transaction },
);
if (!complaints) {
return complaints;
}
const output = complaints.get({plain: true});
output.product = await complaints.getProduct({
transaction
});
output.owner = await complaints.getOwner({
transaction
});
output.attachments = await complaints.getAttachments({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.complaint_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'complaints',
'complaint_number',
filter.complaint_number,
),
};
}
if (filter.reporter_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'complaints',
'reporter_name',
filter.reporter_name,
),
};
}
if (filter.reporter_contact) {
where = {
...where,
[Op.and]: Utils.ilike(
'complaints',
'reporter_contact',
filter.reporter_contact,
),
};
}
if (filter.complaint_description) {
where = {
...where,
[Op.and]: Utils.ilike(
'complaints',
'complaint_description',
filter.complaint_description,
),
};
}
if (filter.received_atRange) {
const [start, end] = filter.received_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
received_at: {
...where.received_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
received_at: {
...where.received_at,
[Op.lte]: end,
},
};
}
}
if (filter.closed_atRange) {
const [start, end] = filter.closed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.serious_injury_or_death) {
where = {
...where,
serious_injury_or_death: filter.serious_injury_or_death,
};
}
if (filter.malfunction) {
where = {
...where,
malfunction: filter.malfunction,
};
}
if (filter.reportable_to_authority) {
where = {
...where,
reportable_to_authority: filter.reportable_to_authority,
};
}
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.complaints.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(
'complaints',
'complaint_number',
query,
),
],
};
}
const records = await db.complaints.findAll({
attributes: [ 'id', 'complaint_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['complaint_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.complaint_number,
}));
}
};

View File

@ -0,0 +1,541 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Device_master_recordsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const device_master_records = await db.device_master_records.create(
{
id: data.id || undefined,
dmr_number: data.dmr_number
||
null
,
title: data.title
||
null
,
status: data.status
||
null
,
effective_at: data.effective_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await device_master_records.setProduct( data.product || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.device_master_records.getTableName(),
belongsToColumn: 'dmr_files',
belongsToId: device_master_records.id,
},
data.dmr_files,
options,
);
return device_master_records;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const device_master_recordsData = data.map((item, index) => ({
id: item.id || undefined,
dmr_number: item.dmr_number
||
null
,
title: item.title
||
null
,
status: item.status
||
null
,
effective_at: item.effective_at
||
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 device_master_records = await db.device_master_records.bulkCreate(device_master_recordsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < device_master_records.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.device_master_records.getTableName(),
belongsToColumn: 'dmr_files',
belongsToId: device_master_records[i].id,
},
data[i].dmr_files,
options,
);
}
return device_master_records;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const device_master_records = await db.device_master_records.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.dmr_number !== undefined) updatePayload.dmr_number = data.dmr_number;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.effective_at !== undefined) updatePayload.effective_at = data.effective_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await device_master_records.update(updatePayload, {transaction});
if (data.product !== undefined) {
await device_master_records.setProduct(
data.product,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.device_master_records.getTableName(),
belongsToColumn: 'dmr_files',
belongsToId: device_master_records.id,
},
data.dmr_files,
options,
);
return device_master_records;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const device_master_records = await db.device_master_records.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of device_master_records) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of device_master_records) {
await record.destroy({transaction});
}
});
return device_master_records;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const device_master_records = await db.device_master_records.findByPk(id, options);
await device_master_records.update({
deletedBy: currentUser.id
}, {
transaction,
});
await device_master_records.destroy({
transaction
});
return device_master_records;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const device_master_records = await db.device_master_records.findOne(
{ where },
{ transaction },
);
if (!device_master_records) {
return device_master_records;
}
const output = device_master_records.get({plain: true});
output.product = await device_master_records.getProduct({
transaction
});
output.dmr_files = await device_master_records.getDmr_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'dmr_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.dmr_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'device_master_records',
'dmr_number',
filter.dmr_number,
),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'device_master_records',
'title',
filter.title,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'device_master_records',
'notes',
filter.notes,
),
};
}
if (filter.effective_atRange) {
const [start, end] = filter.effective_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_at: {
...where.effective_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_at: {
...where.effective_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.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.device_master_records.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'device_master_records',
'dmr_number',
query,
),
],
};
}
const records = await db.device_master_records.findAll({
attributes: [ 'id', 'dmr_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['dmr_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.dmr_number,
}));
}
};

View File

@ -0,0 +1,616 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Document_templatesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_templates = await db.document_templates.create(
{
id: data.id || undefined,
template_name: data.template_name
||
null
,
template_code: data.template_code
||
null
,
template_family: data.template_family
||
null
,
purpose: data.purpose
||
null
,
template_body: data.template_body
||
null
,
format: data.format
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await document_templates.setDocument_type( data.document_type || null, {
transaction,
});
await document_templates.setMapped_clauses(data.mapped_clauses || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.document_templates.getTableName(),
belongsToColumn: 'template_files',
belongsToId: document_templates.id,
},
data.template_files,
options,
);
return document_templates;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const document_templatesData = data.map((item, index) => ({
id: item.id || undefined,
template_name: item.template_name
||
null
,
template_code: item.template_code
||
null
,
template_family: item.template_family
||
null
,
purpose: item.purpose
||
null
,
template_body: item.template_body
||
null
,
format: item.format
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const document_templates = await db.document_templates.bulkCreate(document_templatesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < document_templates.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.document_templates.getTableName(),
belongsToColumn: 'template_files',
belongsToId: document_templates[i].id,
},
data[i].template_files,
options,
);
}
return document_templates;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_templates = await db.document_templates.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.template_name !== undefined) updatePayload.template_name = data.template_name;
if (data.template_code !== undefined) updatePayload.template_code = data.template_code;
if (data.template_family !== undefined) updatePayload.template_family = data.template_family;
if (data.purpose !== undefined) updatePayload.purpose = data.purpose;
if (data.template_body !== undefined) updatePayload.template_body = data.template_body;
if (data.format !== undefined) updatePayload.format = data.format;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await document_templates.update(updatePayload, {transaction});
if (data.document_type !== undefined) {
await document_templates.setDocument_type(
data.document_type,
{ transaction }
);
}
if (data.mapped_clauses !== undefined) {
await document_templates.setMapped_clauses(data.mapped_clauses, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.document_templates.getTableName(),
belongsToColumn: 'template_files',
belongsToId: document_templates.id,
},
data.template_files,
options,
);
return document_templates;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_templates = await db.document_templates.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of document_templates) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of document_templates) {
await record.destroy({transaction});
}
});
return document_templates;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_templates = await db.document_templates.findByPk(id, options);
await document_templates.update({
deletedBy: currentUser.id
}, {
transaction,
});
await document_templates.destroy({
transaction
});
return document_templates;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const document_templates = await db.document_templates.findOne(
{ where },
{ transaction },
);
if (!document_templates) {
return document_templates;
}
const output = document_templates.get({plain: true});
output.documents_template = await document_templates.getDocuments_template({
transaction
});
output.document_type = await document_templates.getDocument_type({
transaction
});
output.template_files = await document_templates.getTemplate_files({
transaction
});
output.mapped_clauses = await document_templates.getMapped_clauses({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.document_types,
as: 'document_type',
where: filter.document_type ? {
[Op.or]: [
{ id: { [Op.in]: filter.document_type.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.document_type.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.clauses,
as: 'mapped_clauses',
required: false,
},
{
model: db.file,
as: 'template_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.template_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_templates',
'template_name',
filter.template_name,
),
};
}
if (filter.template_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_templates',
'template_code',
filter.template_code,
),
};
}
if (filter.purpose) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_templates',
'purpose',
filter.purpose,
),
};
}
if (filter.template_body) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_templates',
'template_body',
filter.template_body,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.template_family) {
where = {
...where,
template_family: filter.template_family,
};
}
if (filter.format) {
where = {
...where,
format: filter.format,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.mapped_clauses) {
const searchTerms = filter.mapped_clauses.split('|');
include = [
{
model: db.clauses,
as: 'mapped_clauses_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
clause_code: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.document_templates.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'document_templates',
'template_name',
query,
),
],
};
}
const records = await db.document_templates.findAll({
attributes: [ 'id', 'template_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['template_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.template_name,
}));
}
};

View File

@ -0,0 +1,455 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Document_typesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_types = await db.document_types.create(
{
id: data.id || undefined,
name: data.name
||
null
,
code: data.code
||
null
,
description: data.description
||
null
,
category: data.category
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return document_types;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const document_typesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
code: item.code
||
null
,
description: item.description
||
null
,
category: item.category
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const document_types = await db.document_types.bulkCreate(document_typesData, { transaction });
// For each item created, replace relation files
return document_types;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_types = await db.document_types.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await document_types.update(updatePayload, {transaction});
return document_types;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_types = await db.document_types.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of document_types) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of document_types) {
await record.destroy({transaction});
}
});
return document_types;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_types = await db.document_types.findByPk(id, options);
await document_types.update({
deletedBy: currentUser.id
}, {
transaction,
});
await document_types.destroy({
transaction
});
return document_types;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const document_types = await db.document_types.findOne(
{ where },
{ transaction },
);
if (!document_types) {
return document_types;
}
const output = document_types.get({plain: true});
output.document_templates_document_type = await document_types.getDocument_templates_document_type({
transaction
});
output.documents_document_type = await document_types.getDocuments_document_type({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_types',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_types',
'code',
filter.code,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_types',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.document_types.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'document_types',
'name',
query,
),
],
};
}
const records = await db.document_types.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,694 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Document_versionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_versions = await db.document_versions.create(
{
id: data.id || undefined,
revision: data.revision
||
null
,
version_status: data.version_status
||
null
,
submitted_at: data.submitted_at
||
null
,
approved_at: data.approved_at
||
null
,
effective_at: data.effective_at
||
null
,
change_summary: data.change_summary
||
null
,
version_content: data.version_content
||
null
,
hash_checksum: data.hash_checksum
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await document_versions.setDocument( data.document || null, {
transaction,
});
await document_versions.setAuthor( data.author || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.document_versions.getTableName(),
belongsToColumn: 'version_files',
belongsToId: document_versions.id,
},
data.version_files,
options,
);
return document_versions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const document_versionsData = data.map((item, index) => ({
id: item.id || undefined,
revision: item.revision
||
null
,
version_status: item.version_status
||
null
,
submitted_at: item.submitted_at
||
null
,
approved_at: item.approved_at
||
null
,
effective_at: item.effective_at
||
null
,
change_summary: item.change_summary
||
null
,
version_content: item.version_content
||
null
,
hash_checksum: item.hash_checksum
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const document_versions = await db.document_versions.bulkCreate(document_versionsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < document_versions.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.document_versions.getTableName(),
belongsToColumn: 'version_files',
belongsToId: document_versions[i].id,
},
data[i].version_files,
options,
);
}
return document_versions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_versions = await db.document_versions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.revision !== undefined) updatePayload.revision = data.revision;
if (data.version_status !== undefined) updatePayload.version_status = data.version_status;
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
if (data.effective_at !== undefined) updatePayload.effective_at = data.effective_at;
if (data.change_summary !== undefined) updatePayload.change_summary = data.change_summary;
if (data.version_content !== undefined) updatePayload.version_content = data.version_content;
if (data.hash_checksum !== undefined) updatePayload.hash_checksum = data.hash_checksum;
updatePayload.updatedById = currentUser.id;
await document_versions.update(updatePayload, {transaction});
if (data.document !== undefined) {
await document_versions.setDocument(
data.document,
{ transaction }
);
}
if (data.author !== undefined) {
await document_versions.setAuthor(
data.author,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.document_versions.getTableName(),
belongsToColumn: 'version_files',
belongsToId: document_versions.id,
},
data.version_files,
options,
);
return document_versions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_versions = await db.document_versions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of document_versions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of document_versions) {
await record.destroy({transaction});
}
});
return document_versions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_versions = await db.document_versions.findByPk(id, options);
await document_versions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await document_versions.destroy({
transaction
});
return document_versions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const document_versions = await db.document_versions.findOne(
{ where },
{ transaction },
);
if (!document_versions) {
return document_versions;
}
const output = document_versions.get({plain: true});
output.document = await document_versions.getDocument({
transaction
});
output.author = await document_versions.getAuthor({
transaction
});
output.version_files = await document_versions.getVersion_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.documents,
as: 'document',
where: filter.document ? {
[Op.or]: [
{ id: { [Op.in]: filter.document.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'author',
where: filter.author ? {
[Op.or]: [
{ id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'version_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.revision) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_versions',
'revision',
filter.revision,
),
};
}
if (filter.change_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_versions',
'change_summary',
filter.change_summary,
),
};
}
if (filter.version_content) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_versions',
'version_content',
filter.version_content,
),
};
}
if (filter.hash_checksum) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_versions',
'hash_checksum',
filter.hash_checksum,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
submitted_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
effective_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
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.approved_atRange) {
const [start, end] = filter.approved_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
approved_at: {
...where.approved_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
approved_at: {
...where.approved_at,
[Op.lte]: end,
},
};
}
}
if (filter.effective_atRange) {
const [start, end] = filter.effective_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_at: {
...where.effective_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_at: {
...where.effective_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.version_status) {
where = {
...where,
version_status: filter.version_status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.document_versions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'document_versions',
'revision',
query,
),
],
};
}
const records = await db.document_versions.findAll({
attributes: [ 'id', 'revision' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['revision', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.revision,
}));
}
};

View File

@ -0,0 +1,861 @@
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 DocumentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const documents = await db.documents.create(
{
id: data.id || undefined,
title: data.title
||
null
,
document_number: data.document_number
||
null
,
current_revision: data.current_revision
||
null
,
lifecycle_status: data.lifecycle_status
||
null
,
control_level: data.control_level
||
null
,
confidentiality: data.confidentiality
||
null
,
effective_date: data.effective_date
||
null
,
next_review_date: data.next_review_date
||
null
,
summary: data.summary
||
null
,
content: data.content
||
null
,
training_required: data.training_required
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await documents.setDocument_type( data.document_type || null, {
transaction,
});
await documents.setTemplate( data.template || null, {
transaction,
});
await documents.setOwner( data.owner || null, {
transaction,
});
await documents.setApprover( data.approver || null, {
transaction,
});
await documents.setMapped_clauses(data.mapped_clauses || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.documents.getTableName(),
belongsToColumn: 'attachments',
belongsToId: documents.id,
},
data.attachments,
options,
);
return documents;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const documentsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
document_number: item.document_number
||
null
,
current_revision: item.current_revision
||
null
,
lifecycle_status: item.lifecycle_status
||
null
,
control_level: item.control_level
||
null
,
confidentiality: item.confidentiality
||
null
,
effective_date: item.effective_date
||
null
,
next_review_date: item.next_review_date
||
null
,
summary: item.summary
||
null
,
content: item.content
||
null
,
training_required: item.training_required
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const documents = await db.documents.bulkCreate(documentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < documents.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.documents.getTableName(),
belongsToColumn: 'attachments',
belongsToId: documents[i].id,
},
data[i].attachments,
options,
);
}
return documents;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const documents = await db.documents.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
if (data.current_revision !== undefined) updatePayload.current_revision = data.current_revision;
if (data.lifecycle_status !== undefined) updatePayload.lifecycle_status = data.lifecycle_status;
if (data.control_level !== undefined) updatePayload.control_level = data.control_level;
if (data.confidentiality !== undefined) updatePayload.confidentiality = data.confidentiality;
if (data.effective_date !== undefined) updatePayload.effective_date = data.effective_date;
if (data.next_review_date !== undefined) updatePayload.next_review_date = data.next_review_date;
if (data.summary !== undefined) updatePayload.summary = data.summary;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.training_required !== undefined) updatePayload.training_required = data.training_required;
updatePayload.updatedById = currentUser.id;
await documents.update(updatePayload, {transaction});
if (data.document_type !== undefined) {
await documents.setDocument_type(
data.document_type,
{ transaction }
);
}
if (data.template !== undefined) {
await documents.setTemplate(
data.template,
{ transaction }
);
}
if (data.owner !== undefined) {
await documents.setOwner(
data.owner,
{ transaction }
);
}
if (data.approver !== undefined) {
await documents.setApprover(
data.approver,
{ transaction }
);
}
if (data.mapped_clauses !== undefined) {
await documents.setMapped_clauses(data.mapped_clauses, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.documents.getTableName(),
belongsToColumn: 'attachments',
belongsToId: documents.id,
},
data.attachments,
options,
);
return documents;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const documents = await db.documents.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of documents) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of documents) {
await record.destroy({transaction});
}
});
return documents;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const documents = await db.documents.findByPk(id, options);
await documents.update({
deletedBy: currentUser.id
}, {
transaction,
});
await documents.destroy({
transaction
});
return documents;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const documents = await db.documents.findOne(
{ where },
{ transaction },
);
if (!documents) {
return documents;
}
const output = documents.get({plain: true});
output.document_versions_document = await documents.getDocument_versions_document({
transaction
});
output.change_requests_document = await documents.getChange_requests_document({
transaction
});
output.training_assignments_document = await documents.getTraining_assignments_document({
transaction
});
output.batches_bmr_document = await documents.getBatches_bmr_document({
transaction
});
output.capas_related_document = await documents.getCapas_related_document({
transaction
});
output.document_type = await documents.getDocument_type({
transaction
});
output.template = await documents.getTemplate({
transaction
});
output.owner = await documents.getOwner({
transaction
});
output.approver = await documents.getApprover({
transaction
});
output.attachments = await documents.getAttachments({
transaction
});
output.mapped_clauses = await documents.getMapped_clauses({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.document_types,
as: 'document_type',
where: filter.document_type ? {
[Op.or]: [
{ id: { [Op.in]: filter.document_type.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.document_type.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.document_templates,
as: 'template',
where: filter.template ? {
[Op.or]: [
{ id: { [Op.in]: filter.template.split('|').map(term => Utils.uuid(term)) } },
{
template_name: {
[Op.or]: filter.template.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'approver',
where: filter.approver ? {
[Op.or]: [
{ id: { [Op.in]: filter.approver.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.approver.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.clauses,
as: 'mapped_clauses',
required: false,
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'title',
filter.title,
),
};
}
if (filter.document_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'document_number',
filter.document_number,
),
};
}
if (filter.current_revision) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'current_revision',
filter.current_revision,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'summary',
filter.summary,
),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'content',
filter.content,
),
};
}
if (filter.effective_dateRange) {
const [start, end] = filter.effective_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_date: {
...where.effective_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_date: {
...where.effective_date,
[Op.lte]: end,
},
};
}
}
if (filter.next_review_dateRange) {
const [start, end] = filter.next_review_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
next_review_date: {
...where.next_review_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
next_review_date: {
...where.next_review_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.lifecycle_status) {
where = {
...where,
lifecycle_status: filter.lifecycle_status,
};
}
if (filter.control_level) {
where = {
...where,
control_level: filter.control_level,
};
}
if (filter.confidentiality) {
where = {
...where,
confidentiality: filter.confidentiality,
};
}
if (filter.training_required) {
where = {
...where,
training_required: filter.training_required,
};
}
if (filter.mapped_clauses) {
const searchTerms = filter.mapped_clauses.split('|');
include = [
{
model: db.clauses,
as: 'mapped_clauses_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
clause_code: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.documents.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'documents',
'title',
query,
),
],
};
}
const records = await db.documents.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,609 @@
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 Esignature_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const esignature_events = await db.esignature_events.create(
{
id: data.id || undefined,
action: data.action
||
null
,
subject_type: data.subject_type
||
null
,
subject_reference: data.subject_reference
||
null
,
signed_at: data.signed_at
||
null
,
meaning_of_signature: data.meaning_of_signature
||
null
,
authentication_method: data.authentication_method
||
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 esignature_events.setUser( data.user || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.esignature_events.getTableName(),
belongsToColumn: 'signature_artifacts',
belongsToId: esignature_events.id,
},
data.signature_artifacts,
options,
);
return esignature_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 esignature_eventsData = data.map((item, index) => ({
id: item.id || undefined,
action: item.action
||
null
,
subject_type: item.subject_type
||
null
,
subject_reference: item.subject_reference
||
null
,
signed_at: item.signed_at
||
null
,
meaning_of_signature: item.meaning_of_signature
||
null
,
authentication_method: item.authentication_method
||
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 esignature_events = await db.esignature_events.bulkCreate(esignature_eventsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < esignature_events.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.esignature_events.getTableName(),
belongsToColumn: 'signature_artifacts',
belongsToId: esignature_events[i].id,
},
data[i].signature_artifacts,
options,
);
}
return esignature_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const esignature_events = await db.esignature_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.action !== undefined) updatePayload.action = data.action;
if (data.subject_type !== undefined) updatePayload.subject_type = data.subject_type;
if (data.subject_reference !== undefined) updatePayload.subject_reference = data.subject_reference;
if (data.signed_at !== undefined) updatePayload.signed_at = data.signed_at;
if (data.meaning_of_signature !== undefined) updatePayload.meaning_of_signature = data.meaning_of_signature;
if (data.authentication_method !== undefined) updatePayload.authentication_method = data.authentication_method;
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 esignature_events.update(updatePayload, {transaction});
if (data.user !== undefined) {
await esignature_events.setUser(
data.user,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.esignature_events.getTableName(),
belongsToColumn: 'signature_artifacts',
belongsToId: esignature_events.id,
},
data.signature_artifacts,
options,
);
return esignature_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const esignature_events = await db.esignature_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of esignature_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of esignature_events) {
await record.destroy({transaction});
}
});
return esignature_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const esignature_events = await db.esignature_events.findByPk(id, options);
await esignature_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await esignature_events.destroy({
transaction
});
return esignature_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const esignature_events = await db.esignature_events.findOne(
{ where },
{ transaction },
);
if (!esignature_events) {
return esignature_events;
}
const output = esignature_events.get({plain: true});
output.user = await esignature_events.getUser({
transaction
});
output.signature_artifacts = await esignature_events.getSignature_artifacts({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'signature_artifacts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.subject_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'esignature_events',
'subject_reference',
filter.subject_reference,
),
};
}
if (filter.meaning_of_signature) {
where = {
...where,
[Op.and]: Utils.ilike(
'esignature_events',
'meaning_of_signature',
filter.meaning_of_signature,
),
};
}
if (filter.authentication_method) {
where = {
...where,
[Op.and]: Utils.ilike(
'esignature_events',
'authentication_method',
filter.authentication_method,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'esignature_events',
'ip_address',
filter.ip_address,
),
};
}
if (filter.user_agent) {
where = {
...where,
[Op.and]: Utils.ilike(
'esignature_events',
'user_agent',
filter.user_agent,
),
};
}
if (filter.signed_atRange) {
const [start, end] = filter.signed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
signed_at: {
...where.signed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
signed_at: {
...where.signed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.action) {
where = {
...where,
action: filter.action,
};
}
if (filter.subject_type) {
where = {
...where,
subject_type: filter.subject_type,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.esignature_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'esignature_events',
'subject_reference',
query,
),
],
};
}
const records = await db.esignature_events.findAll({
attributes: [ 'id', 'subject_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['subject_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.subject_reference,
}));
}
};

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,596 @@
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 Management_reviewsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const management_reviews = await db.management_reviews.create(
{
id: data.id || undefined,
review_title: data.review_title
||
null
,
status: data.status
||
null
,
meeting_start_at: data.meeting_start_at
||
null
,
meeting_end_at: data.meeting_end_at
||
null
,
agenda: data.agenda
||
null
,
minutes: data.minutes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await management_reviews.setChairperson( data.chairperson || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.management_reviews.getTableName(),
belongsToColumn: 'attachments',
belongsToId: management_reviews.id,
},
data.attachments,
options,
);
return management_reviews;
}
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 management_reviewsData = data.map((item, index) => ({
id: item.id || undefined,
review_title: item.review_title
||
null
,
status: item.status
||
null
,
meeting_start_at: item.meeting_start_at
||
null
,
meeting_end_at: item.meeting_end_at
||
null
,
agenda: item.agenda
||
null
,
minutes: item.minutes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const management_reviews = await db.management_reviews.bulkCreate(management_reviewsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < management_reviews.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.management_reviews.getTableName(),
belongsToColumn: 'attachments',
belongsToId: management_reviews[i].id,
},
data[i].attachments,
options,
);
}
return management_reviews;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const management_reviews = await db.management_reviews.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.review_title !== undefined) updatePayload.review_title = data.review_title;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.meeting_start_at !== undefined) updatePayload.meeting_start_at = data.meeting_start_at;
if (data.meeting_end_at !== undefined) updatePayload.meeting_end_at = data.meeting_end_at;
if (data.agenda !== undefined) updatePayload.agenda = data.agenda;
if (data.minutes !== undefined) updatePayload.minutes = data.minutes;
updatePayload.updatedById = currentUser.id;
await management_reviews.update(updatePayload, {transaction});
if (data.chairperson !== undefined) {
await management_reviews.setChairperson(
data.chairperson,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.management_reviews.getTableName(),
belongsToColumn: 'attachments',
belongsToId: management_reviews.id,
},
data.attachments,
options,
);
return management_reviews;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const management_reviews = await db.management_reviews.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of management_reviews) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of management_reviews) {
await record.destroy({transaction});
}
});
return management_reviews;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const management_reviews = await db.management_reviews.findByPk(id, options);
await management_reviews.update({
deletedBy: currentUser.id
}, {
transaction,
});
await management_reviews.destroy({
transaction
});
return management_reviews;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const management_reviews = await db.management_reviews.findOne(
{ where },
{ transaction },
);
if (!management_reviews) {
return management_reviews;
}
const output = management_reviews.get({plain: true});
output.chairperson = await management_reviews.getChairperson({
transaction
});
output.attachments = await management_reviews.getAttachments({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'chairperson',
where: filter.chairperson ? {
[Op.or]: [
{ id: { [Op.in]: filter.chairperson.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.chairperson.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.review_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'management_reviews',
'review_title',
filter.review_title,
),
};
}
if (filter.agenda) {
where = {
...where,
[Op.and]: Utils.ilike(
'management_reviews',
'agenda',
filter.agenda,
),
};
}
if (filter.minutes) {
where = {
...where,
[Op.and]: Utils.ilike(
'management_reviews',
'minutes',
filter.minutes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
meeting_start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
meeting_end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.meeting_start_atRange) {
const [start, end] = filter.meeting_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
meeting_start_at: {
...where.meeting_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
meeting_start_at: {
...where.meeting_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.meeting_end_atRange) {
const [start, end] = filter.meeting_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
meeting_end_at: {
...where.meeting_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
meeting_end_at: {
...where.meeting_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.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.management_reviews.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(
'management_reviews',
'review_title',
query,
),
],
};
}
const records = await db.management_reviews.findAll({
attributes: [ 'id', 'review_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['review_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.review_title,
}));
}
};

View File

@ -0,0 +1,705 @@
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 NonconformancesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const nonconformances = await db.nonconformances.create(
{
id: data.id || undefined,
nc_number: data.nc_number
||
null
,
status: data.status
||
null
,
nonconformance_type: data.nonconformance_type
||
null
,
description: data.description
||
null
,
disposition: data.disposition
||
null
,
detected_at: data.detected_at
||
null
,
closed_at: data.closed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await nonconformances.setProduct( data.product || null, {
transaction,
});
await nonconformances.setBatch( data.batch || null, {
transaction,
});
await nonconformances.setSupplier( data.supplier || null, {
transaction,
});
await nonconformances.setOwner( data.owner || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.nonconformances.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: nonconformances.id,
},
data.evidence_files,
options,
);
return nonconformances;
}
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 nonconformancesData = data.map((item, index) => ({
id: item.id || undefined,
nc_number: item.nc_number
||
null
,
status: item.status
||
null
,
nonconformance_type: item.nonconformance_type
||
null
,
description: item.description
||
null
,
disposition: item.disposition
||
null
,
detected_at: item.detected_at
||
null
,
closed_at: item.closed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const nonconformances = await db.nonconformances.bulkCreate(nonconformancesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < nonconformances.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.nonconformances.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: nonconformances[i].id,
},
data[i].evidence_files,
options,
);
}
return nonconformances;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const nonconformances = await db.nonconformances.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.nc_number !== undefined) updatePayload.nc_number = data.nc_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.nonconformance_type !== undefined) updatePayload.nonconformance_type = data.nonconformance_type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.disposition !== undefined) updatePayload.disposition = data.disposition;
if (data.detected_at !== undefined) updatePayload.detected_at = data.detected_at;
if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
updatePayload.updatedById = currentUser.id;
await nonconformances.update(updatePayload, {transaction});
if (data.product !== undefined) {
await nonconformances.setProduct(
data.product,
{ transaction }
);
}
if (data.batch !== undefined) {
await nonconformances.setBatch(
data.batch,
{ transaction }
);
}
if (data.supplier !== undefined) {
await nonconformances.setSupplier(
data.supplier,
{ transaction }
);
}
if (data.owner !== undefined) {
await nonconformances.setOwner(
data.owner,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.nonconformances.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: nonconformances.id,
},
data.evidence_files,
options,
);
return nonconformances;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const nonconformances = await db.nonconformances.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of nonconformances) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of nonconformances) {
await record.destroy({transaction});
}
});
return nonconformances;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const nonconformances = await db.nonconformances.findByPk(id, options);
await nonconformances.update({
deletedBy: currentUser.id
}, {
transaction,
});
await nonconformances.destroy({
transaction
});
return nonconformances;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const nonconformances = await db.nonconformances.findOne(
{ where },
{ transaction },
);
if (!nonconformances) {
return nonconformances;
}
const output = nonconformances.get({plain: true});
output.product = await nonconformances.getProduct({
transaction
});
output.batch = await nonconformances.getBatch({
transaction
});
output.supplier = await nonconformances.getSupplier({
transaction
});
output.owner = await nonconformances.getOwner({
transaction
});
output.evidence_files = await nonconformances.getEvidence_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.batches,
as: 'batch',
where: filter.batch ? {
[Op.or]: [
{ id: { [Op.in]: filter.batch.split('|').map(term => Utils.uuid(term)) } },
{
batch_number: {
[Op.or]: filter.batch.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.suppliers,
as: 'supplier',
where: filter.supplier ? {
[Op.or]: [
{ id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
{
supplier_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'evidence_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.nc_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'nonconformances',
'nc_number',
filter.nc_number,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'nonconformances',
'description',
filter.description,
),
};
}
if (filter.detected_atRange) {
const [start, end] = filter.detected_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
detected_at: {
...where.detected_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
detected_at: {
...where.detected_at,
[Op.lte]: end,
},
};
}
}
if (filter.closed_atRange) {
const [start, end] = filter.closed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.nonconformance_type) {
where = {
...where,
nonconformance_type: filter.nonconformance_type,
};
}
if (filter.disposition) {
where = {
...where,
disposition: filter.disposition,
};
}
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.nonconformances.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(
'nonconformances',
'nc_number',
query,
),
],
};
}
const records = await db.nonconformances.findAll({
attributes: [ 'id', 'nc_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['nc_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.nc_number,
}));
}
};

View File

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

View File

@ -0,0 +1,537 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ProductsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const products = await db.products.create(
{
id: data.id || undefined,
product_name: data.product_name
||
null
,
product_code: data.product_code
||
null
,
intended_use: data.intended_use
||
null
,
risk_classification: data.risk_classification
||
null
,
udi_di: data.udi_di
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'product_files',
belongsToId: products.id,
},
data.product_files,
options,
);
return products;
}
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 productsData = data.map((item, index) => ({
id: item.id || undefined,
product_name: item.product_name
||
null
,
product_code: item.product_code
||
null
,
intended_use: item.intended_use
||
null
,
risk_classification: item.risk_classification
||
null
,
udi_di: item.udi_di
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const products = await db.products.bulkCreate(productsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < products.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'product_files',
belongsToId: products[i].id,
},
data[i].product_files,
options,
);
}
return products;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.product_name !== undefined) updatePayload.product_name = data.product_name;
if (data.product_code !== undefined) updatePayload.product_code = data.product_code;
if (data.intended_use !== undefined) updatePayload.intended_use = data.intended_use;
if (data.risk_classification !== undefined) updatePayload.risk_classification = data.risk_classification;
if (data.udi_di !== undefined) updatePayload.udi_di = data.udi_di;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await products.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'product_files',
belongsToId: products.id,
},
data.product_files,
options,
);
return products;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of products) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of products) {
await record.destroy({transaction});
}
});
return products;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findByPk(id, options);
await products.update({
deletedBy: currentUser.id
}, {
transaction,
});
await products.destroy({
transaction
});
return products;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findOne(
{ where },
{ transaction },
);
if (!products) {
return products;
}
const output = products.get({plain: true});
output.batches_product = await products.getBatches_product({
transaction
});
output.device_master_records_product = await products.getDevice_master_records_product({
transaction
});
output.risk_assessments_product = await products.getRisk_assessments_product({
transaction
});
output.nonconformances_product = await products.getNonconformances_product({
transaction
});
output.complaints_product = await products.getComplaints_product({
transaction
});
output.regulatory_submissions_product = await products.getRegulatory_submissions_product({
transaction
});
output.product_files = await products.getProduct_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.file,
as: 'product_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.product_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'product_name',
filter.product_name,
),
};
}
if (filter.product_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'product_code',
filter.product_code,
),
};
}
if (filter.intended_use) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'intended_use',
filter.intended_use,
),
};
}
if (filter.udi_di) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'udi_di',
filter.udi_di,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.risk_classification) {
where = {
...where,
risk_classification: filter.risk_classification,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.products.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(
'products',
'product_name',
query,
),
],
};
}
const records = await db.products.findAll({
attributes: [ 'id', 'product_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['product_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.product_name,
}));
}
};

View File

@ -0,0 +1,668 @@
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 Regulatory_submissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const regulatory_submissions = await db.regulatory_submissions.create(
{
id: data.id || undefined,
submission_name: data.submission_name
||
null
,
jurisdiction: data.jurisdiction
||
null
,
submission_type: data.submission_type
||
null
,
status: data.status
||
null
,
planned_submission_at: data.planned_submission_at
||
null
,
submitted_at: data.submitted_at
||
null
,
decision_at: data.decision_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await regulatory_submissions.setProduct( data.product || null, {
transaction,
});
await regulatory_submissions.setOwner( data.owner || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.regulatory_submissions.getTableName(),
belongsToColumn: 'submission_files',
belongsToId: regulatory_submissions.id,
},
data.submission_files,
options,
);
return regulatory_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 regulatory_submissionsData = data.map((item, index) => ({
id: item.id || undefined,
submission_name: item.submission_name
||
null
,
jurisdiction: item.jurisdiction
||
null
,
submission_type: item.submission_type
||
null
,
status: item.status
||
null
,
planned_submission_at: item.planned_submission_at
||
null
,
submitted_at: item.submitted_at
||
null
,
decision_at: item.decision_at
||
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 regulatory_submissions = await db.regulatory_submissions.bulkCreate(regulatory_submissionsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < regulatory_submissions.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.regulatory_submissions.getTableName(),
belongsToColumn: 'submission_files',
belongsToId: regulatory_submissions[i].id,
},
data[i].submission_files,
options,
);
}
return regulatory_submissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const regulatory_submissions = await db.regulatory_submissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.submission_name !== undefined) updatePayload.submission_name = data.submission_name;
if (data.jurisdiction !== undefined) updatePayload.jurisdiction = data.jurisdiction;
if (data.submission_type !== undefined) updatePayload.submission_type = data.submission_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.planned_submission_at !== undefined) updatePayload.planned_submission_at = data.planned_submission_at;
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
if (data.decision_at !== undefined) updatePayload.decision_at = data.decision_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await regulatory_submissions.update(updatePayload, {transaction});
if (data.product !== undefined) {
await regulatory_submissions.setProduct(
data.product,
{ transaction }
);
}
if (data.owner !== undefined) {
await regulatory_submissions.setOwner(
data.owner,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.regulatory_submissions.getTableName(),
belongsToColumn: 'submission_files',
belongsToId: regulatory_submissions.id,
},
data.submission_files,
options,
);
return regulatory_submissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const regulatory_submissions = await db.regulatory_submissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of regulatory_submissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of regulatory_submissions) {
await record.destroy({transaction});
}
});
return regulatory_submissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const regulatory_submissions = await db.regulatory_submissions.findByPk(id, options);
await regulatory_submissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await regulatory_submissions.destroy({
transaction
});
return regulatory_submissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const regulatory_submissions = await db.regulatory_submissions.findOne(
{ where },
{ transaction },
);
if (!regulatory_submissions) {
return regulatory_submissions;
}
const output = regulatory_submissions.get({plain: true});
output.product = await regulatory_submissions.getProduct({
transaction
});
output.owner = await regulatory_submissions.getOwner({
transaction
});
output.submission_files = await regulatory_submissions.getSubmission_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'submission_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.submission_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'regulatory_submissions',
'submission_name',
filter.submission_name,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'regulatory_submissions',
'notes',
filter.notes,
),
};
}
if (filter.planned_submission_atRange) {
const [start, end] = filter.planned_submission_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
planned_submission_at: {
...where.planned_submission_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
planned_submission_at: {
...where.planned_submission_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.decision_atRange) {
const [start, end] = filter.decision_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
decision_at: {
...where.decision_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
decision_at: {
...where.decision_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.jurisdiction) {
where = {
...where,
jurisdiction: filter.jurisdiction,
};
}
if (filter.submission_type) {
where = {
...where,
submission_type: filter.submission_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.regulatory_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'regulatory_submissions',
'submission_name',
query,
),
],
};
}
const records = await db.regulatory_submissions.findAll({
attributes: [ 'id', 'submission_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['submission_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.submission_name,
}));
}
};

View File

@ -0,0 +1,639 @@
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 Risk_assessmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const risk_assessments = await db.risk_assessments.create(
{
id: data.id || undefined,
risk_file_name: data.risk_file_name
||
null
,
risk_file_code: data.risk_file_code
||
null
,
methodology: data.methodology
||
null
,
status: data.status
||
null
,
created_on: data.created_on
||
null
,
review_due_at: data.review_due_at
||
null
,
scope: data.scope
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await risk_assessments.setProduct( data.product || null, {
transaction,
});
await risk_assessments.setOwner( data.owner || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.risk_assessments.getTableName(),
belongsToColumn: 'risk_files',
belongsToId: risk_assessments.id,
},
data.risk_files,
options,
);
return risk_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 risk_assessmentsData = data.map((item, index) => ({
id: item.id || undefined,
risk_file_name: item.risk_file_name
||
null
,
risk_file_code: item.risk_file_code
||
null
,
methodology: item.methodology
||
null
,
status: item.status
||
null
,
created_on: item.created_on
||
null
,
review_due_at: item.review_due_at
||
null
,
scope: item.scope
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const risk_assessments = await db.risk_assessments.bulkCreate(risk_assessmentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < risk_assessments.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.risk_assessments.getTableName(),
belongsToColumn: 'risk_files',
belongsToId: risk_assessments[i].id,
},
data[i].risk_files,
options,
);
}
return risk_assessments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const risk_assessments = await db.risk_assessments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.risk_file_name !== undefined) updatePayload.risk_file_name = data.risk_file_name;
if (data.risk_file_code !== undefined) updatePayload.risk_file_code = data.risk_file_code;
if (data.methodology !== undefined) updatePayload.methodology = data.methodology;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
if (data.review_due_at !== undefined) updatePayload.review_due_at = data.review_due_at;
if (data.scope !== undefined) updatePayload.scope = data.scope;
updatePayload.updatedById = currentUser.id;
await risk_assessments.update(updatePayload, {transaction});
if (data.product !== undefined) {
await risk_assessments.setProduct(
data.product,
{ transaction }
);
}
if (data.owner !== undefined) {
await risk_assessments.setOwner(
data.owner,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.risk_assessments.getTableName(),
belongsToColumn: 'risk_files',
belongsToId: risk_assessments.id,
},
data.risk_files,
options,
);
return risk_assessments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const risk_assessments = await db.risk_assessments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of risk_assessments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of risk_assessments) {
await record.destroy({transaction});
}
});
return risk_assessments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const risk_assessments = await db.risk_assessments.findByPk(id, options);
await risk_assessments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await risk_assessments.destroy({
transaction
});
return risk_assessments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const risk_assessments = await db.risk_assessments.findOne(
{ where },
{ transaction },
);
if (!risk_assessments) {
return risk_assessments;
}
const output = risk_assessments.get({plain: true});
output.risk_items_risk_assessment = await risk_assessments.getRisk_items_risk_assessment({
transaction
});
output.product = await risk_assessments.getProduct({
transaction
});
output.owner = await risk_assessments.getOwner({
transaction
});
output.risk_files = await risk_assessments.getRisk_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'risk_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.risk_file_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'risk_assessments',
'risk_file_name',
filter.risk_file_name,
),
};
}
if (filter.risk_file_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'risk_assessments',
'risk_file_code',
filter.risk_file_code,
),
};
}
if (filter.scope) {
where = {
...where,
[Op.and]: Utils.ilike(
'risk_assessments',
'scope',
filter.scope,
),
};
}
if (filter.created_onRange) {
const [start, end] = filter.created_onRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_on: {
...where.created_on,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_on: {
...where.created_on,
[Op.lte]: end,
},
};
}
}
if (filter.review_due_atRange) {
const [start, end] = filter.review_due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
review_due_at: {
...where.review_due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
review_due_at: {
...where.review_due_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.methodology) {
where = {
...where,
methodology: filter.methodology,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.risk_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'risk_assessments',
'risk_file_name',
query,
),
],
};
}
const records = await db.risk_assessments.findAll({
attributes: [ 'id', 'risk_file_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['risk_file_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.risk_file_name,
}));
}
};

View File

@ -0,0 +1,652 @@
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 Risk_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const risk_items = await db.risk_items.create(
{
id: data.id || undefined,
hazard_id: data.hazard_id
||
null
,
hazard_description: data.hazard_description
||
null
,
sequence_of_events: data.sequence_of_events
||
null
,
severity: data.severity
||
null
,
occurrence: data.occurrence
||
null
,
detectability: data.detectability
||
null
,
risk_level_initial: data.risk_level_initial
||
null
,
risk_controls: data.risk_controls
||
null
,
risk_level_residual: data.risk_level_residual
||
null
,
verification_of_controls: data.verification_of_controls
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await risk_items.setRisk_assessment( data.risk_assessment || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.risk_items.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: risk_items.id,
},
data.evidence_files,
options,
);
return risk_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 risk_itemsData = data.map((item, index) => ({
id: item.id || undefined,
hazard_id: item.hazard_id
||
null
,
hazard_description: item.hazard_description
||
null
,
sequence_of_events: item.sequence_of_events
||
null
,
severity: item.severity
||
null
,
occurrence: item.occurrence
||
null
,
detectability: item.detectability
||
null
,
risk_level_initial: item.risk_level_initial
||
null
,
risk_controls: item.risk_controls
||
null
,
risk_level_residual: item.risk_level_residual
||
null
,
verification_of_controls: item.verification_of_controls
||
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 risk_items = await db.risk_items.bulkCreate(risk_itemsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < risk_items.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.risk_items.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: risk_items[i].id,
},
data[i].evidence_files,
options,
);
}
return risk_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const risk_items = await db.risk_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.hazard_id !== undefined) updatePayload.hazard_id = data.hazard_id;
if (data.hazard_description !== undefined) updatePayload.hazard_description = data.hazard_description;
if (data.sequence_of_events !== undefined) updatePayload.sequence_of_events = data.sequence_of_events;
if (data.severity !== undefined) updatePayload.severity = data.severity;
if (data.occurrence !== undefined) updatePayload.occurrence = data.occurrence;
if (data.detectability !== undefined) updatePayload.detectability = data.detectability;
if (data.risk_level_initial !== undefined) updatePayload.risk_level_initial = data.risk_level_initial;
if (data.risk_controls !== undefined) updatePayload.risk_controls = data.risk_controls;
if (data.risk_level_residual !== undefined) updatePayload.risk_level_residual = data.risk_level_residual;
if (data.verification_of_controls !== undefined) updatePayload.verification_of_controls = data.verification_of_controls;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await risk_items.update(updatePayload, {transaction});
if (data.risk_assessment !== undefined) {
await risk_items.setRisk_assessment(
data.risk_assessment,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.risk_items.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: risk_items.id,
},
data.evidence_files,
options,
);
return risk_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const risk_items = await db.risk_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of risk_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of risk_items) {
await record.destroy({transaction});
}
});
return risk_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const risk_items = await db.risk_items.findByPk(id, options);
await risk_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await risk_items.destroy({
transaction
});
return risk_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const risk_items = await db.risk_items.findOne(
{ where },
{ transaction },
);
if (!risk_items) {
return risk_items;
}
const output = risk_items.get({plain: true});
output.risk_assessment = await risk_items.getRisk_assessment({
transaction
});
output.evidence_files = await risk_items.getEvidence_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.risk_assessments,
as: 'risk_assessment',
where: filter.risk_assessment ? {
[Op.or]: [
{ id: { [Op.in]: filter.risk_assessment.split('|').map(term => Utils.uuid(term)) } },
{
risk_file_name: {
[Op.or]: filter.risk_assessment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'evidence_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.hazard_id) {
where = {
...where,
[Op.and]: Utils.ilike(
'risk_items',
'hazard_id',
filter.hazard_id,
),
};
}
if (filter.hazard_description) {
where = {
...where,
[Op.and]: Utils.ilike(
'risk_items',
'hazard_description',
filter.hazard_description,
),
};
}
if (filter.sequence_of_events) {
where = {
...where,
[Op.and]: Utils.ilike(
'risk_items',
'sequence_of_events',
filter.sequence_of_events,
),
};
}
if (filter.risk_controls) {
where = {
...where,
[Op.and]: Utils.ilike(
'risk_items',
'risk_controls',
filter.risk_controls,
),
};
}
if (filter.verification_of_controls) {
where = {
...where,
[Op.and]: Utils.ilike(
'risk_items',
'verification_of_controls',
filter.verification_of_controls,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.severity) {
where = {
...where,
severity: filter.severity,
};
}
if (filter.occurrence) {
where = {
...where,
occurrence: filter.occurrence,
};
}
if (filter.detectability) {
where = {
...where,
detectability: filter.detectability,
};
}
if (filter.risk_level_initial) {
where = {
...where,
risk_level_initial: filter.risk_level_initial,
};
}
if (filter.risk_level_residual) {
where = {
...where,
risk_level_residual: filter.risk_level_residual,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.risk_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'risk_items',
'hazard_id',
query,
),
],
};
}
const records = await db.risk_items.findAll({
attributes: [ 'id', 'hazard_id' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['hazard_id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.hazard_id,
}));
}
};

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

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

View File

@ -0,0 +1,479 @@
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 StandardsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const standards = await db.standards.create(
{
id: data.id || undefined,
name: data.name
||
null
,
short_name: data.short_name
||
null
,
version: data.version
||
null
,
publisher: data.publisher
||
null
,
scope_notes: data.scope_notes
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return standards;
}
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 standardsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
short_name: item.short_name
||
null
,
version: item.version
||
null
,
publisher: item.publisher
||
null
,
scope_notes: item.scope_notes
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const standards = await db.standards.bulkCreate(standardsData, { transaction });
// For each item created, replace relation files
return standards;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const standards = await db.standards.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.short_name !== undefined) updatePayload.short_name = data.short_name;
if (data.version !== undefined) updatePayload.version = data.version;
if (data.publisher !== undefined) updatePayload.publisher = data.publisher;
if (data.scope_notes !== undefined) updatePayload.scope_notes = data.scope_notes;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await standards.update(updatePayload, {transaction});
return standards;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const standards = await db.standards.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of standards) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of standards) {
await record.destroy({transaction});
}
});
return standards;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const standards = await db.standards.findByPk(id, options);
await standards.update({
deletedBy: currentUser.id
}, {
transaction,
});
await standards.destroy({
transaction
});
return standards;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const standards = await db.standards.findOne(
{ where },
{ transaction },
);
if (!standards) {
return standards;
}
const output = standards.get({plain: true});
output.clauses_standard = await standards.getClauses_standard({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'standards',
'name',
filter.name,
),
};
}
if (filter.short_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'standards',
'short_name',
filter.short_name,
),
};
}
if (filter.version) {
where = {
...where,
[Op.and]: Utils.ilike(
'standards',
'version',
filter.version,
),
};
}
if (filter.publisher) {
where = {
...where,
[Op.and]: Utils.ilike(
'standards',
'publisher',
filter.publisher,
),
};
}
if (filter.scope_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'standards',
'scope_notes',
filter.scope_notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.standards.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(
'standards',
'short_name',
query,
),
],
};
}
const records = await db.standards.findAll({
attributes: [ 'id', 'short_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['short_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.short_name,
}));
}
};

View File

@ -0,0 +1,685 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class SuppliersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.create(
{
id: data.id || undefined,
supplier_name: data.supplier_name
||
null
,
supplier_code: data.supplier_code
||
null
,
supplier_type: data.supplier_type
||
null
,
contact_name: data.contact_name
||
null
,
contact_email: data.contact_email
||
null
,
contact_phone: data.contact_phone
||
null
,
address: data.address
||
null
,
qualification_status: data.qualification_status
||
null
,
last_audit_at: data.last_audit_at
||
null
,
next_audit_at: data.next_audit_at
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.suppliers.getTableName(),
belongsToColumn: 'supplier_files',
belongsToId: suppliers.id,
},
data.supplier_files,
options,
);
return suppliers;
}
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 suppliersData = data.map((item, index) => ({
id: item.id || undefined,
supplier_name: item.supplier_name
||
null
,
supplier_code: item.supplier_code
||
null
,
supplier_type: item.supplier_type
||
null
,
contact_name: item.contact_name
||
null
,
contact_email: item.contact_email
||
null
,
contact_phone: item.contact_phone
||
null
,
address: item.address
||
null
,
qualification_status: item.qualification_status
||
null
,
last_audit_at: item.last_audit_at
||
null
,
next_audit_at: item.next_audit_at
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const suppliers = await db.suppliers.bulkCreate(suppliersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < suppliers.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.suppliers.getTableName(),
belongsToColumn: 'supplier_files',
belongsToId: suppliers[i].id,
},
data[i].supplier_files,
options,
);
}
return suppliers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.supplier_name !== undefined) updatePayload.supplier_name = data.supplier_name;
if (data.supplier_code !== undefined) updatePayload.supplier_code = data.supplier_code;
if (data.supplier_type !== undefined) updatePayload.supplier_type = data.supplier_type;
if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.qualification_status !== undefined) updatePayload.qualification_status = data.qualification_status;
if (data.last_audit_at !== undefined) updatePayload.last_audit_at = data.last_audit_at;
if (data.next_audit_at !== undefined) updatePayload.next_audit_at = data.next_audit_at;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await suppliers.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.suppliers.getTableName(),
belongsToColumn: 'supplier_files',
belongsToId: suppliers.id,
},
data.supplier_files,
options,
);
return suppliers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of suppliers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of suppliers) {
await record.destroy({transaction});
}
});
return suppliers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findByPk(id, options);
await suppliers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await suppliers.destroy({
transaction
});
return suppliers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findOne(
{ where },
{ transaction },
);
if (!suppliers) {
return suppliers;
}
const output = suppliers.get({plain: true});
output.certificates_of_analysis_supplier = await suppliers.getCertificates_of_analysis_supplier({
transaction
});
output.nonconformances_supplier = await suppliers.getNonconformances_supplier({
transaction
});
output.audits_supplier = await suppliers.getAudits_supplier({
transaction
});
output.supplier_files = await suppliers.getSupplier_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.file,
as: 'supplier_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.supplier_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'supplier_name',
filter.supplier_name,
),
};
}
if (filter.supplier_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'supplier_code',
filter.supplier_code,
),
};
}
if (filter.contact_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'contact_name',
filter.contact_name,
),
};
}
if (filter.contact_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'contact_email',
filter.contact_email,
),
};
}
if (filter.contact_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'contact_phone',
filter.contact_phone,
),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'address',
filter.address,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
last_audit_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
next_audit_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.last_audit_atRange) {
const [start, end] = filter.last_audit_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_audit_at: {
...where.last_audit_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_audit_at: {
...where.last_audit_at,
[Op.lte]: end,
},
};
}
}
if (filter.next_audit_atRange) {
const [start, end] = filter.next_audit_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
next_audit_at: {
...where.next_audit_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
next_audit_at: {
...where.next_audit_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.supplier_type) {
where = {
...where,
supplier_type: filter.supplier_type,
};
}
if (filter.qualification_status) {
where = {
...where,
qualification_status: filter.qualification_status,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.suppliers.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(
'suppliers',
'supplier_name',
query,
),
],
};
}
const records = await db.suppliers.findAll({
attributes: [ 'id', 'supplier_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['supplier_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.supplier_name,
}));
}
};

View File

@ -0,0 +1,696 @@
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 Training_assignmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const training_assignments = await db.training_assignments.create(
{
id: data.id || undefined,
status: data.status
||
null
,
assigned_at: data.assigned_at
||
null
,
due_at: data.due_at
||
null
,
completed_at: data.completed_at
||
null
,
score: data.score
||
null
,
trainer_notes: data.trainer_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await training_assignments.setUser( data.user || null, {
transaction,
});
await training_assignments.setCourse( data.course || null, {
transaction,
});
await training_assignments.setDocument( data.document || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.training_assignments.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: training_assignments.id,
},
data.evidence_files,
options,
);
return training_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 training_assignmentsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
assigned_at: item.assigned_at
||
null
,
due_at: item.due_at
||
null
,
completed_at: item.completed_at
||
null
,
score: item.score
||
null
,
trainer_notes: item.trainer_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const training_assignments = await db.training_assignments.bulkCreate(training_assignmentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < training_assignments.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.training_assignments.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: training_assignments[i].id,
},
data[i].evidence_files,
options,
);
}
return training_assignments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const training_assignments = await db.training_assignments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.score !== undefined) updatePayload.score = data.score;
if (data.trainer_notes !== undefined) updatePayload.trainer_notes = data.trainer_notes;
updatePayload.updatedById = currentUser.id;
await training_assignments.update(updatePayload, {transaction});
if (data.user !== undefined) {
await training_assignments.setUser(
data.user,
{ transaction }
);
}
if (data.course !== undefined) {
await training_assignments.setCourse(
data.course,
{ transaction }
);
}
if (data.document !== undefined) {
await training_assignments.setDocument(
data.document,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.training_assignments.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: training_assignments.id,
},
data.evidence_files,
options,
);
return training_assignments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const training_assignments = await db.training_assignments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of training_assignments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of training_assignments) {
await record.destroy({transaction});
}
});
return training_assignments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const training_assignments = await db.training_assignments.findByPk(id, options);
await training_assignments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await training_assignments.destroy({
transaction
});
return training_assignments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const training_assignments = await db.training_assignments.findOne(
{ where },
{ transaction },
);
if (!training_assignments) {
return training_assignments;
}
const output = training_assignments.get({plain: true});
output.user = await training_assignments.getUser({
transaction
});
output.course = await training_assignments.getCourse({
transaction
});
output.document = await training_assignments.getDocument({
transaction
});
output.evidence_files = await training_assignments.getEvidence_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.training_courses,
as: 'course',
where: filter.course ? {
[Op.or]: [
{ id: { [Op.in]: filter.course.split('|').map(term => Utils.uuid(term)) } },
{
course_name: {
[Op.or]: filter.course.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.documents,
as: 'document',
where: filter.document ? {
[Op.or]: [
{ id: { [Op.in]: filter.document.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'evidence_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.trainer_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'training_assignments',
'trainer_notes',
filter.trainer_notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
assigned_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
due_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.assigned_atRange) {
const [start, end] = filter.assigned_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.lte]: end,
},
};
}
}
if (filter.due_atRange) {
const [start, end] = filter.due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.training_assignments.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'training_assignments',
'status',
query,
),
],
};
}
const records = await db.training_assignments.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,530 @@
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 Training_coursesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const training_courses = await db.training_courses.create(
{
id: data.id || undefined,
course_name: data.course_name
||
null
,
course_code: data.course_code
||
null
,
description: data.description
||
null
,
delivery_method: data.delivery_method
||
null
,
duration_hours: data.duration_hours
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.training_courses.getTableName(),
belongsToColumn: 'course_materials',
belongsToId: training_courses.id,
},
data.course_materials,
options,
);
return training_courses;
}
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 training_coursesData = data.map((item, index) => ({
id: item.id || undefined,
course_name: item.course_name
||
null
,
course_code: item.course_code
||
null
,
description: item.description
||
null
,
delivery_method: item.delivery_method
||
null
,
duration_hours: item.duration_hours
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const training_courses = await db.training_courses.bulkCreate(training_coursesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < training_courses.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.training_courses.getTableName(),
belongsToColumn: 'course_materials',
belongsToId: training_courses[i].id,
},
data[i].course_materials,
options,
);
}
return training_courses;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const training_courses = await db.training_courses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.course_name !== undefined) updatePayload.course_name = data.course_name;
if (data.course_code !== undefined) updatePayload.course_code = data.course_code;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.delivery_method !== undefined) updatePayload.delivery_method = data.delivery_method;
if (data.duration_hours !== undefined) updatePayload.duration_hours = data.duration_hours;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await training_courses.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.training_courses.getTableName(),
belongsToColumn: 'course_materials',
belongsToId: training_courses.id,
},
data.course_materials,
options,
);
return training_courses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const training_courses = await db.training_courses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of training_courses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of training_courses) {
await record.destroy({transaction});
}
});
return training_courses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const training_courses = await db.training_courses.findByPk(id, options);
await training_courses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await training_courses.destroy({
transaction
});
return training_courses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const training_courses = await db.training_courses.findOne(
{ where },
{ transaction },
);
if (!training_courses) {
return training_courses;
}
const output = training_courses.get({plain: true});
output.training_assignments_course = await training_courses.getTraining_assignments_course({
transaction
});
output.course_materials = await training_courses.getCourse_materials({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.file,
as: 'course_materials',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.course_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'training_courses',
'course_name',
filter.course_name,
),
};
}
if (filter.course_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'training_courses',
'course_code',
filter.course_code,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'training_courses',
'description',
filter.description,
),
};
}
if (filter.duration_hoursRange) {
const [start, end] = filter.duration_hoursRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_hours: {
...where.duration_hours,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_hours: {
...where.duration_hours,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.delivery_method) {
where = {
...where,
delivery_method: filter.delivery_method,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.training_courses.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(
'training_courses',
'course_name',
query,
),
],
};
}
const records = await db.training_courses.findAll({
attributes: [ 'id', 'course_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['course_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.course_name,
}));
}
};

1031
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_iso13485_qms_manager',
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,191 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const approval_steps = sequelize.define(
'approval_steps',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
step_order: {
type: DataTypes.INTEGER,
},
step_name: {
type: DataTypes.TEXT,
},
step_type: {
type: DataTypes.ENUM,
values: [
"review",
"approval",
"quality_review",
"regulatory_review"
],
},
assignment_rule: {
type: DataTypes.ENUM,
values: [
"specific_user",
"document_owner",
"approver_role",
"department",
"any_approver"
],
},
sla_days: {
type: DataTypes.INTEGER,
},
required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
approval_steps.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.approval_steps.hasMany(db.approval_tasks, {
as: 'approval_tasks_step',
foreignKey: {
name: 'stepId',
},
constraints: false,
});
//end loop
db.approval_steps.belongsTo(db.approval_workflows, {
as: 'workflow',
foreignKey: {
name: 'workflowId',
},
constraints: false,
});
db.approval_steps.belongsTo(db.users, {
as: 'assignee',
foreignKey: {
name: 'assigneeId',
},
constraints: false,
});
db.approval_steps.belongsTo(db.users, {
as: 'createdBy',
});
db.approval_steps.belongsTo(db.users, {
as: 'updatedBy',
});
};
return approval_steps;
};

View File

@ -0,0 +1,213 @@
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 approval_tasks = sequelize.define(
'approval_tasks',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
subject_type: {
type: DataTypes.ENUM,
values: [
"document",
"document_version",
"change_request",
"training_assignment",
"record_batch",
"risk_assessment",
"capa",
"nonconformance",
"audit"
],
},
subject_reference: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"in_progress",
"approved",
"rejected",
"cancelled"
],
},
assigned_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
decision_comment: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
approval_tasks.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.approval_tasks.belongsTo(db.approval_workflows, {
as: 'workflow',
foreignKey: {
name: 'workflowId',
},
constraints: false,
});
db.approval_tasks.belongsTo(db.approval_steps, {
as: 'step',
foreignKey: {
name: 'stepId',
},
constraints: false,
});
db.approval_tasks.belongsTo(db.users, {
as: 'assignee',
foreignKey: {
name: 'assigneeId',
},
constraints: false,
});
db.approval_tasks.hasMany(db.file, {
as: 'evidence_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.approval_tasks.getTableName(),
belongsToColumn: 'evidence_files',
},
});
db.approval_tasks.belongsTo(db.users, {
as: 'createdBy',
});
db.approval_tasks.belongsTo(db.users, {
as: 'updatedBy',
});
};
return approval_tasks;
};

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 approval_workflows = sequelize.define(
'approval_workflows',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
applies_to: {
type: DataTypes.ENUM,
values: [
"document",
"document_version",
"change_request",
"training_assignment",
"record_batch",
"risk_assessment",
"capa",
"nonconformance",
"audit"
],
},
requires_esignature: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
requires_two_factor: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
min_approvals: {
type: DataTypes.INTEGER,
},
instructions: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
approval_workflows.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.approval_workflows.hasMany(db.approval_steps, {
as: 'approval_steps_workflow',
foreignKey: {
name: 'workflowId',
},
constraints: false,
});
db.approval_workflows.hasMany(db.approval_tasks, {
as: 'approval_tasks_workflow',
foreignKey: {
name: 'workflowId',
},
constraints: false,
});
//end loop
db.approval_workflows.belongsTo(db.users, {
as: 'createdBy',
});
db.approval_workflows.belongsTo(db.users, {
as: 'updatedBy',
});
};
return approval_workflows;
};

View File

@ -0,0 +1,205 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_findings = sequelize.define(
'audit_findings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
finding_number: {
type: DataTypes.TEXT,
},
severity: {
type: DataTypes.ENUM,
values: [
"observation",
"minor",
"major",
"critical"
],
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"action_required",
"in_progress",
"verified",
"closed"
],
},
description: {
type: DataTypes.TEXT,
},
objective_evidence: {
type: DataTypes.TEXT,
},
due_at: {
type: DataTypes.DATE,
},
closed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
audit_findings.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_findings.belongsTo(db.audits, {
as: 'audit',
foreignKey: {
name: 'auditId',
},
constraints: false,
});
db.audit_findings.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.audit_findings.belongsTo(db.capas, {
as: 'related_capa',
foreignKey: {
name: 'related_capaId',
},
constraints: false,
});
db.audit_findings.hasMany(db.file, {
as: 'evidence_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.audit_findings.getTableName(),
belongsToColumn: 'evidence_files',
},
});
db.audit_findings.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_findings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_findings;
};

View File

@ -0,0 +1,254 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_logs = sequelize.define(
'audit_logs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_at: {
type: DataTypes.DATE,
},
event_type: {
type: DataTypes.ENUM,
values: [
"create",
"update",
"delete",
"view",
"export",
"login",
"logout",
"approve",
"reject",
"esign",
"assign",
"upload",
"download"
],
},
subject_type: {
type: DataTypes.ENUM,
values: [
"document",
"document_version",
"document_template",
"change_request",
"training_assignment",
"risk_assessment",
"risk_item",
"capa",
"nonconformance",
"complaint",
"audit",
"audit_finding",
"management_review",
"regulatory_submission",
"supplier",
"product",
"batch",
"coa",
"dmr",
"user",
"other"
],
},
subject_reference: {
type: DataTypes.TEXT,
},
details: {
type: DataTypes.TEXT,
},
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_logs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.audit_logs.belongsTo(db.users, {
as: 'actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.audit_logs.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_logs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_logs;
};

View File

@ -0,0 +1,229 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audits = sequelize.define(
'audits',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
audit_number: {
type: DataTypes.TEXT,
},
audit_type: {
type: DataTypes.ENUM,
values: [
"internal",
"supplier",
"notified_body",
"regulatory",
"certification",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"planned",
"in_progress",
"report_issued",
"closed",
"cancelled"
],
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
scope: {
type: DataTypes.TEXT,
},
summary: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
audits.associate = (db) => {
db.audits.belongsToMany(db.clauses, {
as: 'mapped_clauses',
foreignKey: {
name: 'audits_mapped_clausesId',
},
constraints: false,
through: 'auditsMapped_clausesClauses',
});
db.audits.belongsToMany(db.clauses, {
as: 'mapped_clauses_filter',
foreignKey: {
name: 'audits_mapped_clausesId',
},
constraints: false,
through: 'auditsMapped_clausesClauses',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.audits.hasMany(db.audit_findings, {
as: 'audit_findings_audit',
foreignKey: {
name: 'auditId',
},
constraints: false,
});
//end loop
db.audits.belongsTo(db.users, {
as: 'lead_auditor',
foreignKey: {
name: 'lead_auditorId',
},
constraints: false,
});
db.audits.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.audits.hasMany(db.file, {
as: 'audit_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.audits.getTableName(),
belongsToColumn: 'audit_files',
},
});
db.audits.belongsTo(db.users, {
as: 'createdBy',
});
db.audits.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audits;
};

View File

@ -0,0 +1,208 @@
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 batches = sequelize.define(
'batches',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
batch_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"planned",
"in_process",
"quarantined",
"released",
"rejected",
"closed"
],
},
manufacture_start_at: {
type: DataTypes.DATE,
},
manufacture_end_at: {
type: DataTypes.DATE,
},
quantity_planned: {
type: DataTypes.DECIMAL,
},
quantity_produced: {
type: DataTypes.DECIMAL,
},
quantity_released: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
batches.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.batches.hasMany(db.certificates_of_analysis, {
as: 'certificates_of_analysis_batch',
foreignKey: {
name: 'batchId',
},
constraints: false,
});
db.batches.hasMany(db.nonconformances, {
as: 'nonconformances_batch',
foreignKey: {
name: 'batchId',
},
constraints: false,
});
//end loop
db.batches.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.batches.belongsTo(db.documents, {
as: 'bmr_document',
foreignKey: {
name: 'bmr_documentId',
},
constraints: false,
});
db.batches.hasMany(db.file, {
as: 'batch_record_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.batches.getTableName(),
belongsToColumn: 'batch_record_files',
},
});
db.batches.belongsTo(db.users, {
as: 'createdBy',
});
db.batches.belongsTo(db.users, {
as: 'updatedBy',
});
};
return batches;
};

View File

@ -0,0 +1,250 @@
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 capas = sequelize.define(
'capas',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
capa_number: {
type: DataTypes.TEXT,
},
source: {
type: DataTypes.ENUM,
values: [
"complaint",
"audit",
"nonconformance",
"process_monitoring",
"supplier",
"management_review",
"risk_management",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"open",
"containment",
"investigation",
"action_plan",
"implementation",
"effectiveness_check",
"closed",
"rejected"
],
},
problem_statement: {
type: DataTypes.TEXT,
},
root_cause: {
type: DataTypes.TEXT,
},
corrective_actions: {
type: DataTypes.TEXT,
},
preventive_actions: {
type: DataTypes.TEXT,
},
opened_at: {
type: DataTypes.DATE,
},
due_at: {
type: DataTypes.DATE,
},
closed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
capas.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.capas.hasMany(db.audit_findings, {
as: 'audit_findings_related_capa',
foreignKey: {
name: 'related_capaId',
},
constraints: false,
});
//end loop
db.capas.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.capas.belongsTo(db.documents, {
as: 'related_document',
foreignKey: {
name: 'related_documentId',
},
constraints: false,
});
db.capas.hasMany(db.file, {
as: 'capa_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.capas.getTableName(),
belongsToColumn: 'capa_files',
},
});
db.capas.belongsTo(db.users, {
as: 'createdBy',
});
db.capas.belongsTo(db.users, {
as: 'updatedBy',
});
};
return capas;
};

View File

@ -0,0 +1,173 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const certificates_of_analysis = sequelize.define(
'certificates_of_analysis',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
coa_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"issued",
"superseded",
"void"
],
},
issued_at: {
type: DataTypes.DATE,
},
expires_at: {
type: DataTypes.DATE,
},
summary: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
certificates_of_analysis.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.certificates_of_analysis.belongsTo(db.batches, {
as: 'batch',
foreignKey: {
name: 'batchId',
},
constraints: false,
});
db.certificates_of_analysis.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.certificates_of_analysis.belongsTo(db.users, {
as: 'issued_by',
foreignKey: {
name: 'issued_byId',
},
constraints: false,
});
db.certificates_of_analysis.hasMany(db.file, {
as: 'coa_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.certificates_of_analysis.getTableName(),
belongsToColumn: 'coa_files',
},
});
db.certificates_of_analysis.belongsTo(db.users, {
as: 'createdBy',
});
db.certificates_of_analysis.belongsTo(db.users, {
as: 'updatedBy',
});
};
return certificates_of_analysis;
};

View File

@ -0,0 +1,244 @@
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 change_requests = sequelize.define(
'change_requests',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
change_number: {
type: DataTypes.TEXT,
},
change_type: {
type: DataTypes.ENUM,
values: [
"document_change",
"process_change",
"form_change",
"software_change",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"submitted",
"in_assessment",
"approved",
"implemented",
"verified",
"closed",
"rejected"
],
},
reason_for_change: {
type: DataTypes.TEXT,
},
impact_assessment: {
type: DataTypes.TEXT,
},
requires_validation: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
requires_regulatory_notification: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
requested_at: {
type: DataTypes.DATE,
},
due_at: {
type: DataTypes.DATE,
},
closed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
change_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.change_requests.belongsTo(db.users, {
as: 'requester',
foreignKey: {
name: 'requesterId',
},
constraints: false,
});
db.change_requests.belongsTo(db.documents, {
as: 'document',
foreignKey: {
name: 'documentId',
},
constraints: false,
});
db.change_requests.belongsTo(db.users, {
as: 'assigned_to',
foreignKey: {
name: 'assigned_toId',
},
constraints: false,
});
db.change_requests.hasMany(db.file, {
as: 'supporting_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.change_requests.getTableName(),
belongsToColumn: 'supporting_files',
},
});
db.change_requests.belongsTo(db.users, {
as: 'createdBy',
});
db.change_requests.belongsTo(db.users, {
as: 'updatedBy',
});
};
return change_requests;
};

View File

@ -0,0 +1,135 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const clauses = sequelize.define(
'clauses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
clause_code: {
type: DataTypes.TEXT,
},
title: {
type: DataTypes.TEXT,
},
text_excerpt: {
type: DataTypes.TEXT,
},
guidance_notes: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
clauses.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.clauses.belongsTo(db.standards, {
as: 'standard',
foreignKey: {
name: 'standardId',
},
constraints: false,
});
db.clauses.belongsTo(db.users, {
as: 'createdBy',
});
db.clauses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return clauses;
};

View File

@ -0,0 +1,215 @@
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 complaints = sequelize.define(
'complaints',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
complaint_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"new",
"triaged",
"under_investigation",
"reportable",
"closed",
"rejected"
],
},
reporter_name: {
type: DataTypes.TEXT,
},
reporter_contact: {
type: DataTypes.TEXT,
},
complaint_description: {
type: DataTypes.TEXT,
},
serious_injury_or_death: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
malfunction: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
reportable_to_authority: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
received_at: {
type: DataTypes.DATE,
},
closed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
complaints.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.complaints.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.complaints.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.complaints.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.complaints.getTableName(),
belongsToColumn: 'attachments',
},
});
db.complaints.belongsTo(db.users, {
as: 'createdBy',
});
db.complaints.belongsTo(db.users, {
as: 'updatedBy',
});
};
return complaints;
};

View File

@ -0,0 +1,160 @@
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 device_master_records = sequelize.define(
'device_master_records',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
dmr_number: {
type: DataTypes.TEXT,
},
title: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"approved",
"effective",
"superseded",
"archived"
],
},
effective_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
device_master_records.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.device_master_records.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.device_master_records.hasMany(db.file, {
as: 'dmr_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.device_master_records.getTableName(),
belongsToColumn: 'dmr_files',
},
});
db.device_master_records.belongsTo(db.users, {
as: 'createdBy',
});
db.device_master_records.belongsTo(db.users, {
as: 'updatedBy',
});
};
return device_master_records;
};

View File

@ -0,0 +1,224 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const document_templates = sequelize.define(
'document_templates',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
template_name: {
type: DataTypes.TEXT,
},
template_code: {
type: DataTypes.TEXT,
},
template_family: {
type: DataTypes.ENUM,
values: [
"sop",
"bmr",
"coa",
"doc",
"risk_file",
"other"
],
},
purpose: {
type: DataTypes.TEXT,
},
template_body: {
type: DataTypes.TEXT,
},
format: {
type: DataTypes.ENUM,
values: [
"html",
"docx",
"xlsx",
"pdf",
"mixed"
],
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
document_templates.associate = (db) => {
db.document_templates.belongsToMany(db.clauses, {
as: 'mapped_clauses',
foreignKey: {
name: 'document_templates_mapped_clausesId',
},
constraints: false,
through: 'document_templatesMapped_clausesClauses',
});
db.document_templates.belongsToMany(db.clauses, {
as: 'mapped_clauses_filter',
foreignKey: {
name: 'document_templates_mapped_clausesId',
},
constraints: false,
through: 'document_templatesMapped_clausesClauses',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.document_templates.hasMany(db.documents, {
as: 'documents_template',
foreignKey: {
name: 'templateId',
},
constraints: false,
});
//end loop
db.document_templates.belongsTo(db.document_types, {
as: 'document_type',
foreignKey: {
name: 'document_typeId',
},
constraints: false,
});
db.document_templates.hasMany(db.file, {
as: 'template_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.document_templates.getTableName(),
belongsToColumn: 'template_files',
},
});
db.document_templates.belongsTo(db.users, {
as: 'createdBy',
});
db.document_templates.belongsTo(db.users, {
as: 'updatedBy',
});
};
return document_templates;
};

View File

@ -0,0 +1,164 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const document_types = sequelize.define(
'document_types',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
category: {
type: DataTypes.ENUM,
values: [
"procedure",
"record",
"form",
"template",
"report",
"other"
],
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
document_types.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.document_types.hasMany(db.document_templates, {
as: 'document_templates_document_type',
foreignKey: {
name: 'document_typeId',
},
constraints: false,
});
db.document_types.hasMany(db.documents, {
as: 'documents_document_type',
foreignKey: {
name: 'document_typeId',
},
constraints: false,
});
//end loop
db.document_types.belongsTo(db.users, {
as: 'createdBy',
});
db.document_types.belongsTo(db.users, {
as: 'updatedBy',
});
};
return document_types;
};

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 document_versions = sequelize.define(
'document_versions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
revision: {
type: DataTypes.TEXT,
},
version_status: {
type: DataTypes.ENUM,
values: [
"draft",
"in_review",
"approved",
"effective",
"superseded",
"obsolete"
],
},
submitted_at: {
type: DataTypes.DATE,
},
approved_at: {
type: DataTypes.DATE,
},
effective_at: {
type: DataTypes.DATE,
},
change_summary: {
type: DataTypes.TEXT,
},
version_content: {
type: DataTypes.TEXT,
},
hash_checksum: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
document_versions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.document_versions.belongsTo(db.documents, {
as: 'document',
foreignKey: {
name: 'documentId',
},
constraints: false,
});
db.document_versions.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.document_versions.hasMany(db.file, {
as: 'version_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.document_versions.getTableName(),
belongsToColumn: 'version_files',
},
});
db.document_versions.belongsTo(db.users, {
as: 'createdBy',
});
db.document_versions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return document_versions;
};

View File

@ -0,0 +1,317 @@
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 documents = sequelize.define(
'documents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
document_number: {
type: DataTypes.TEXT,
},
current_revision: {
type: DataTypes.TEXT,
},
lifecycle_status: {
type: DataTypes.ENUM,
values: [
"draft",
"in_review",
"approved",
"effective",
"superseded",
"obsolete",
"archived"
],
},
control_level: {
type: DataTypes.ENUM,
values: [
"controlled",
"uncontrolled"
],
},
confidentiality: {
type: DataTypes.ENUM,
values: [
"public_internal",
"restricted",
"confidential",
"highly_confidential"
],
},
effective_date: {
type: DataTypes.DATE,
},
next_review_date: {
type: DataTypes.DATE,
},
summary: {
type: DataTypes.TEXT,
},
content: {
type: DataTypes.TEXT,
},
training_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
documents.associate = (db) => {
db.documents.belongsToMany(db.clauses, {
as: 'mapped_clauses',
foreignKey: {
name: 'documents_mapped_clausesId',
},
constraints: false,
through: 'documentsMapped_clausesClauses',
});
db.documents.belongsToMany(db.clauses, {
as: 'mapped_clauses_filter',
foreignKey: {
name: 'documents_mapped_clausesId',
},
constraints: false,
through: 'documentsMapped_clausesClauses',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.documents.hasMany(db.document_versions, {
as: 'document_versions_document',
foreignKey: {
name: 'documentId',
},
constraints: false,
});
db.documents.hasMany(db.change_requests, {
as: 'change_requests_document',
foreignKey: {
name: 'documentId',
},
constraints: false,
});
db.documents.hasMany(db.training_assignments, {
as: 'training_assignments_document',
foreignKey: {
name: 'documentId',
},
constraints: false,
});
db.documents.hasMany(db.batches, {
as: 'batches_bmr_document',
foreignKey: {
name: 'bmr_documentId',
},
constraints: false,
});
db.documents.hasMany(db.capas, {
as: 'capas_related_document',
foreignKey: {
name: 'related_documentId',
},
constraints: false,
});
//end loop
db.documents.belongsTo(db.document_types, {
as: 'document_type',
foreignKey: {
name: 'document_typeId',
},
constraints: false,
});
db.documents.belongsTo(db.document_templates, {
as: 'template',
foreignKey: {
name: 'templateId',
},
constraints: false,
});
db.documents.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.documents.belongsTo(db.users, {
as: 'approver',
foreignKey: {
name: 'approverId',
},
constraints: false,
});
db.documents.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.documents.getTableName(),
belongsToColumn: 'attachments',
},
});
db.documents.belongsTo(db.users, {
as: 'createdBy',
});
db.documents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return documents;
};

View File

@ -0,0 +1,208 @@
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 esignature_events = sequelize.define(
'esignature_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
action: {
type: DataTypes.ENUM,
values: [
"sign",
"approve",
"reject",
"acknowledge"
],
},
subject_type: {
type: DataTypes.ENUM,
values: [
"document",
"document_version",
"change_request",
"training_assignment",
"record_batch",
"risk_assessment",
"capa",
"nonconformance",
"audit"
],
},
subject_reference: {
type: DataTypes.TEXT,
},
signed_at: {
type: DataTypes.DATE,
},
meaning_of_signature: {
type: DataTypes.TEXT,
},
authentication_method: {
type: DataTypes.TEXT,
},
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,
},
);
esignature_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.esignature_events.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.esignature_events.hasMany(db.file, {
as: 'signature_artifacts',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.esignature_events.getTableName(),
belongsToColumn: 'signature_artifacts',
},
});
db.esignature_events.belongsTo(db.users, {
as: 'createdBy',
});
db.esignature_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return esignature_events;
};

View File

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

View File

@ -0,0 +1,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,164 @@
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 management_reviews = sequelize.define(
'management_reviews',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
review_title: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"scheduled",
"in_progress",
"completed",
"archived"
],
},
meeting_start_at: {
type: DataTypes.DATE,
},
meeting_end_at: {
type: DataTypes.DATE,
},
agenda: {
type: DataTypes.TEXT,
},
minutes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
management_reviews.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.management_reviews.belongsTo(db.users, {
as: 'chairperson',
foreignKey: {
name: 'chairpersonId',
},
constraints: false,
});
db.management_reviews.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.management_reviews.getTableName(),
belongsToColumn: 'attachments',
},
});
db.management_reviews.belongsTo(db.users, {
as: 'createdBy',
});
db.management_reviews.belongsTo(db.users, {
as: 'updatedBy',
});
};
return management_reviews;
};

View File

@ -0,0 +1,240 @@
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 nonconformances = sequelize.define(
'nonconformances',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
nc_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"contained",
"dispositioned",
"closed",
"rejected"
],
},
nonconformance_type: {
type: DataTypes.ENUM,
values: [
"product",
"process",
"documentation",
"supplier",
"training",
"other"
],
},
description: {
type: DataTypes.TEXT,
},
disposition: {
type: DataTypes.ENUM,
values: [
"use_as_is",
"rework",
"repair",
"scrap",
"return_to_supplier",
"other"
],
},
detected_at: {
type: DataTypes.DATE,
},
closed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
nonconformances.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.nonconformances.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.batches, {
as: 'batch',
foreignKey: {
name: 'batchId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.nonconformances.hasMany(db.file, {
as: 'evidence_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.nonconformances.getTableName(),
belongsToColumn: 'evidence_files',
},
});
db.nonconformances.belongsTo(db.users, {
as: 'createdBy',
});
db.nonconformances.belongsTo(db.users, {
as: 'updatedBy',
});
};
return nonconformances;
};

View File

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

View File

@ -0,0 +1,219 @@
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 products = sequelize.define(
'products',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
product_name: {
type: DataTypes.TEXT,
},
product_code: {
type: DataTypes.TEXT,
},
intended_use: {
type: DataTypes.TEXT,
},
risk_classification: {
type: DataTypes.ENUM,
values: [
"eu_class_i",
"eu_class_iia",
"eu_class_iib",
"eu_class_iii",
"us_class_i",
"us_class_ii",
"us_class_iii",
"other"
],
},
udi_di: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
products.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.products.hasMany(db.batches, {
as: 'batches_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.device_master_records, {
as: 'device_master_records_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.risk_assessments, {
as: 'risk_assessments_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.nonconformances, {
as: 'nonconformances_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.complaints, {
as: 'complaints_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.regulatory_submissions, {
as: 'regulatory_submissions_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
//end loop
db.products.hasMany(db.file, {
as: 'product_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.products.getTableName(),
belongsToColumn: 'product_files',
},
});
db.products.belongsTo(db.users, {
as: 'createdBy',
});
db.products.belongsTo(db.users, {
as: 'updatedBy',
});
};
return products;
};

View File

@ -0,0 +1,243 @@
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 regulatory_submissions = sequelize.define(
'regulatory_submissions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
submission_name: {
type: DataTypes.TEXT,
},
jurisdiction: {
type: DataTypes.ENUM,
values: [
"eu_mdr",
"us_fda",
"uk_mhra",
"other"
],
},
submission_type: {
type: DataTypes.ENUM,
values: [
"technical_documentation",
"cer",
"pms_report",
"psur",
"vigilance",
"510k",
"pma",
"de_novo",
"registration_listing",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"in_review",
"submitted",
"questions_received",
"accepted",
"rejected",
"closed"
],
},
planned_submission_at: {
type: DataTypes.DATE,
},
submitted_at: {
type: DataTypes.DATE,
},
decision_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
regulatory_submissions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.regulatory_submissions.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.regulatory_submissions.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.regulatory_submissions.hasMany(db.file, {
as: 'submission_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.regulatory_submissions.getTableName(),
belongsToColumn: 'submission_files',
},
});
db.regulatory_submissions.belongsTo(db.users, {
as: 'createdBy',
});
db.regulatory_submissions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return regulatory_submissions;
};

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 risk_assessments = sequelize.define(
'risk_assessments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
risk_file_name: {
type: DataTypes.TEXT,
},
risk_file_code: {
type: DataTypes.TEXT,
},
methodology: {
type: DataTypes.ENUM,
values: [
"iso_14971",
"fmea",
"fta",
"hazop",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"in_review",
"approved",
"effective",
"superseded",
"archived"
],
},
created_on: {
type: DataTypes.DATE,
},
review_due_at: {
type: DataTypes.DATE,
},
scope: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
risk_assessments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.risk_assessments.hasMany(db.risk_items, {
as: 'risk_items_risk_assessment',
foreignKey: {
name: 'risk_assessmentId',
},
constraints: false,
});
//end loop
db.risk_assessments.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.risk_assessments.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.risk_assessments.hasMany(db.file, {
as: 'risk_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.risk_assessments.getTableName(),
belongsToColumn: 'risk_files',
},
});
db.risk_assessments.belongsTo(db.users, {
as: 'createdBy',
});
db.risk_assessments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return risk_assessments;
};

View File

@ -0,0 +1,283 @@
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 risk_items = sequelize.define(
'risk_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
hazard_id: {
type: DataTypes.TEXT,
},
hazard_description: {
type: DataTypes.TEXT,
},
sequence_of_events: {
type: DataTypes.TEXT,
},
severity: {
type: DataTypes.ENUM,
values: [
"negligible",
"minor",
"serious",
"critical",
"catastrophic"
],
},
occurrence: {
type: DataTypes.ENUM,
values: [
"remote",
"unlikely",
"possible",
"likely",
"frequent"
],
},
detectability: {
type: DataTypes.ENUM,
values: [
"high",
"medium",
"low",
"unknown"
],
},
risk_level_initial: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high",
"unacceptable"
],
},
risk_controls: {
type: DataTypes.TEXT,
},
risk_level_residual: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high",
"unacceptable"
],
},
verification_of_controls: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"mitigating",
"verified",
"accepted",
"closed"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
risk_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.risk_items.belongsTo(db.risk_assessments, {
as: 'risk_assessment',
foreignKey: {
name: 'risk_assessmentId',
},
constraints: false,
});
db.risk_items.hasMany(db.file, {
as: 'evidence_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.risk_items.getTableName(),
belongsToColumn: 'evidence_files',
},
});
db.risk_items.belongsTo(db.users, {
as: 'createdBy',
});
db.risk_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return risk_items;
};

View File

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

View File

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

View File

@ -0,0 +1,239 @@
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 suppliers = sequelize.define(
'suppliers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
supplier_name: {
type: DataTypes.TEXT,
},
supplier_code: {
type: DataTypes.TEXT,
},
supplier_type: {
type: DataTypes.ENUM,
values: [
"manufacturer",
"critical_supplier",
"service_provider",
"distributor",
"laboratory",
"other"
],
},
contact_name: {
type: DataTypes.TEXT,
},
contact_email: {
type: DataTypes.TEXT,
},
contact_phone: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
qualification_status: {
type: DataTypes.ENUM,
values: [
"prospect",
"qualified",
"conditionally_qualified",
"disqualified"
],
},
last_audit_at: {
type: DataTypes.DATE,
},
next_audit_at: {
type: DataTypes.DATE,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
suppliers.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.suppliers.hasMany(db.certificates_of_analysis, {
as: 'certificates_of_analysis_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.suppliers.hasMany(db.nonconformances, {
as: 'nonconformances_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.suppliers.hasMany(db.audits, {
as: 'audits_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
//end loop
db.suppliers.hasMany(db.file, {
as: 'supplier_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.suppliers.getTableName(),
belongsToColumn: 'supplier_files',
},
});
db.suppliers.belongsTo(db.users, {
as: 'createdBy',
});
db.suppliers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return suppliers;
};

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 training_assignments = sequelize.define(
'training_assignments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"assigned",
"in_progress",
"completed",
"overdue",
"waived"
],
},
assigned_at: {
type: DataTypes.DATE,
},
due_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
score: {
type: DataTypes.DECIMAL,
},
trainer_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
training_assignments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.training_assignments.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.training_assignments.belongsTo(db.training_courses, {
as: 'course',
foreignKey: {
name: 'courseId',
},
constraints: false,
});
db.training_assignments.belongsTo(db.documents, {
as: 'document',
foreignKey: {
name: 'documentId',
},
constraints: false,
});
db.training_assignments.hasMany(db.file, {
as: 'evidence_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.training_assignments.getTableName(),
belongsToColumn: 'evidence_files',
},
});
db.training_assignments.belongsTo(db.users, {
as: 'createdBy',
});
db.training_assignments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return training_assignments;
};

View File

@ -0,0 +1,170 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const training_courses = sequelize.define(
'training_courses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
course_name: {
type: DataTypes.TEXT,
},
course_code: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
delivery_method: {
type: DataTypes.ENUM,
values: [
"read_and_understand",
"classroom",
"webinar",
"elearning",
"on_the_job"
],
},
duration_hours: {
type: DataTypes.DECIMAL,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
training_courses.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.training_courses.hasMany(db.training_assignments, {
as: 'training_assignments_course',
foreignKey: {
name: 'courseId',
},
constraints: false,
});
//end loop
db.training_courses.hasMany(db.file, {
as: 'course_materials',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.training_courses.getTableName(),
belongsToColumn: 'course_materials',
},
});
db.training_courses.belongsTo(db.users, {
as: 'createdBy',
});
db.training_courses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return training_courses;
};

View File

@ -0,0 +1,406 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const users = sequelize.define(
'users',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
firstName: {
type: DataTypes.TEXT,
},
lastName: {
type: DataTypes.TEXT,
},
phoneNumber: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
disabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
password: {
type: DataTypes.TEXT,
},
emailVerified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
emailVerificationToken: {
type: DataTypes.TEXT,
},
emailVerificationTokenExpiresAt: {
type: DataTypes.DATE,
},
passwordResetToken: {
type: DataTypes.TEXT,
},
passwordResetTokenExpiresAt: {
type: DataTypes.DATE,
},
provider: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
users.associate = (db) => {
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions_filter',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.users.hasMany(db.documents, {
as: 'documents_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.documents, {
as: 'documents_approver',
foreignKey: {
name: 'approverId',
},
constraints: false,
});
db.users.hasMany(db.document_versions, {
as: 'document_versions_author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.users.hasMany(db.change_requests, {
as: 'change_requests_requester',
foreignKey: {
name: 'requesterId',
},
constraints: false,
});
db.users.hasMany(db.change_requests, {
as: 'change_requests_assigned_to',
foreignKey: {
name: 'assigned_toId',
},
constraints: false,
});
db.users.hasMany(db.approval_steps, {
as: 'approval_steps_assignee',
foreignKey: {
name: 'assigneeId',
},
constraints: false,
});
db.users.hasMany(db.approval_tasks, {
as: 'approval_tasks_assignee',
foreignKey: {
name: 'assigneeId',
},
constraints: false,
});
db.users.hasMany(db.esignature_events, {
as: 'esignature_events_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.training_assignments, {
as: 'training_assignments_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.certificates_of_analysis, {
as: 'certificates_of_analysis_issued_by',
foreignKey: {
name: 'issued_byId',
},
constraints: false,
});
db.users.hasMany(db.risk_assessments, {
as: 'risk_assessments_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.capas, {
as: 'capas_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.nonconformances, {
as: 'nonconformances_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.complaints, {
as: 'complaints_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.audits, {
as: 'audits_lead_auditor',
foreignKey: {
name: 'lead_auditorId',
},
constraints: false,
});
db.users.hasMany(db.audit_findings, {
as: 'audit_findings_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.management_reviews, {
as: 'management_reviews_chairperson',
foreignKey: {
name: 'chairpersonId',
},
constraints: false,
});
db.users.hasMany(db.regulatory_submissions, {
as: 'regulatory_submissions_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.audit_logs, {
as: 'audit_logs_actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

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

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

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

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

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

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

@ -0,0 +1,248 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const document_typesRoutes = require('./routes/document_types');
const standardsRoutes = require('./routes/standards');
const clausesRoutes = require('./routes/clauses');
const document_templatesRoutes = require('./routes/document_templates');
const documentsRoutes = require('./routes/documents');
const document_versionsRoutes = require('./routes/document_versions');
const change_requestsRoutes = require('./routes/change_requests');
const approval_workflowsRoutes = require('./routes/approval_workflows');
const approval_stepsRoutes = require('./routes/approval_steps');
const approval_tasksRoutes = require('./routes/approval_tasks');
const esignature_eventsRoutes = require('./routes/esignature_events');
const training_coursesRoutes = require('./routes/training_courses');
const training_assignmentsRoutes = require('./routes/training_assignments');
const productsRoutes = require('./routes/products');
const suppliersRoutes = require('./routes/suppliers');
const batchesRoutes = require('./routes/batches');
const certificates_of_analysisRoutes = require('./routes/certificates_of_analysis');
const device_master_recordsRoutes = require('./routes/device_master_records');
const risk_assessmentsRoutes = require('./routes/risk_assessments');
const risk_itemsRoutes = require('./routes/risk_items');
const capasRoutes = require('./routes/capas');
const nonconformancesRoutes = require('./routes/nonconformances');
const complaintsRoutes = require('./routes/complaints');
const auditsRoutes = require('./routes/audits');
const audit_findingsRoutes = require('./routes/audit_findings');
const management_reviewsRoutes = require('./routes/management_reviews');
const regulatory_submissionsRoutes = require('./routes/regulatory_submissions');
const audit_logsRoutes = require('./routes/audit_logs');
const getBaseUrl = (url) => {
if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url;
};
const options = {
definition: {
openapi: "3.0.0",
info: {
version: "1.0.0",
title: "ISO13485 QMS Manager",
description: "ISO13485 QMS Manager Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
},
servers: [
{
url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
description: "Development server",
}
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
},
responses: {
UnauthorizedError: {
description: "Access token is missing or invalid"
}
}
},
security: [{
bearerAuth: []
}]
},
apis: ["./src/routes/*.js"],
};
const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
next()
}, swaggerUI.serve, swaggerUI.setup(specs))
app.use(cors({origin: true}));
require('./auth/auth');
app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');
app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);
app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);
app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);
app.use('/api/document_types', passport.authenticate('jwt', {session: false}), document_typesRoutes);
app.use('/api/standards', passport.authenticate('jwt', {session: false}), standardsRoutes);
app.use('/api/clauses', passport.authenticate('jwt', {session: false}), clausesRoutes);
app.use('/api/document_templates', passport.authenticate('jwt', {session: false}), document_templatesRoutes);
app.use('/api/documents', passport.authenticate('jwt', {session: false}), documentsRoutes);
app.use('/api/document_versions', passport.authenticate('jwt', {session: false}), document_versionsRoutes);
app.use('/api/change_requests', passport.authenticate('jwt', {session: false}), change_requestsRoutes);
app.use('/api/approval_workflows', passport.authenticate('jwt', {session: false}), approval_workflowsRoutes);
app.use('/api/approval_steps', passport.authenticate('jwt', {session: false}), approval_stepsRoutes);
app.use('/api/approval_tasks', passport.authenticate('jwt', {session: false}), approval_tasksRoutes);
app.use('/api/esignature_events', passport.authenticate('jwt', {session: false}), esignature_eventsRoutes);
app.use('/api/training_courses', passport.authenticate('jwt', {session: false}), training_coursesRoutes);
app.use('/api/training_assignments', passport.authenticate('jwt', {session: false}), training_assignmentsRoutes);
app.use('/api/products', passport.authenticate('jwt', {session: false}), productsRoutes);
app.use('/api/suppliers', passport.authenticate('jwt', {session: false}), suppliersRoutes);
app.use('/api/batches', passport.authenticate('jwt', {session: false}), batchesRoutes);
app.use('/api/certificates_of_analysis', passport.authenticate('jwt', {session: false}), certificates_of_analysisRoutes);
app.use('/api/device_master_records', passport.authenticate('jwt', {session: false}), device_master_recordsRoutes);
app.use('/api/risk_assessments', passport.authenticate('jwt', {session: false}), risk_assessmentsRoutes);
app.use('/api/risk_items', passport.authenticate('jwt', {session: false}), risk_itemsRoutes);
app.use('/api/capas', passport.authenticate('jwt', {session: false}), capasRoutes);
app.use('/api/nonconformances', passport.authenticate('jwt', {session: false}), nonconformancesRoutes);
app.use('/api/complaints', passport.authenticate('jwt', {session: false}), complaintsRoutes);
app.use('/api/audits', passport.authenticate('jwt', {session: false}), auditsRoutes);
app.use('/api/audit_findings', passport.authenticate('jwt', {session: false}), audit_findingsRoutes);
app.use('/api/management_reviews', passport.authenticate('jwt', {session: false}), management_reviewsRoutes);
app.use('/api/regulatory_submissions', passport.authenticate('jwt', {session: false}), regulatory_submissionsRoutes);
app.use('/api/audit_logs', passport.authenticate('jwt', {session: false}), audit_logsRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
module.exports = app;

View File

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

View File

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

View File

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

View File

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

View File

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

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