Initial version

This commit is contained in:
Flatlogic Bot 2026-03-23 23:26:02 +00:00
commit 818e291fc2
676 changed files with 261203 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>Manufacturing ERP</h2>
<p>Enterprise multi-company Manufacturing ERP for production, materials, machines, QA and inventory with audit-ready traceability.</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 @@
# Manufacturing ERP
## 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_39283
DB_USER=app_39283
DB_PASS=f3da502d-3f8c-447a-9b2b-0efcd31fe165
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 @@
#Manufacturing ERP - 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_manufacturing_erp;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_manufacturing_erp 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": "manufacturingerp",
"description": "Manufacturing ERP - template backend",
"scripts": {
"start": "npm run db:migrate && npm run db:seed && npm run watch",
"lint": "eslint . --ext .js",
"db:migrate": "sequelize-cli db:migrate",
"db:seed": "sequelize-cli db:seed:all",
"db:drop": "sequelize-cli db:drop",
"db:create": "sequelize-cli db:create",
"watch": "node watcher.js"
},
"dependencies": {
"@google-cloud/storage": "^5.18.2",
"axios": "^1.6.7",
"bcrypt": "5.1.1",
"chokidar": "^4.0.3",
"cors": "2.8.5",
"csv-parser": "^3.0.0",
"express": "4.18.2",
"formidable": "1.2.2",
"helmet": "4.1.1",
"json2csv": "^5.0.7",
"jsonwebtoken": "8.5.1",
"lodash": "4.17.21",
"moment": "2.30.1",
"multer": "^1.4.4",
"mysql2": "2.2.5",
"nodemailer": "6.9.9",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
"passport-jwt": "^4.0.1",
"passport-microsoft": "^0.1.0",
"pg": "8.4.1",
"pg-hstore": "2.3.4",
"sequelize": "6.35.2",
"sequelize-json-schema": "^2.1.1",
"sqlite": "4.0.15",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0",
"tedious": "^18.2.4"
},
"engines": {
"node": ">=18"
},
"private": true,
"devDependencies": {
"cross-env": "7.0.3",
"eslint": "^8.23.1",
"eslint-plugin-import": "^2.29.1",
"mocha": "8.1.3",
"node-mocks-http": "1.9.0",
"nodemon": "2.0.5",
"sequelize-cli": "6.6.2"
}
}

View File

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

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

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

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

@ -0,0 +1,81 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "f3da502d",
user_pass: "0efcd31fe165",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'f3da502d-3f8c-447a-9b2b-0efcd31fe165',
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: 'Manufacturing ERP <app@flatlogic.app>',
host: 'email-smtp.us-east-1.amazonaws.com',
port: 587,
auth: {
user: process.env.EMAIL_USER || '',
pass: process.env.EMAIL_PASS,
},
tls: {
rejectUnauthorized: false
}
},
roles: {
super_admin: 'Super Administrator',
admin: 'Administrator',
user: 'Inventory Controller',
},
project_uuid: 'f3da502d-3f8c-447a-9b2b-0efcd31fe165',
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 = 'interlocking gears abstract';
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,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 Audit_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.create(
{
id: data.id || undefined,
entity_type: data.entity_type
||
null
,
entity_reference: data.entity_reference
||
null
,
action: data.action
||
null
,
event_at: data.event_at
||
null
,
details: data.details
||
null
,
ip_address: data.ip_address
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audit_events.setCompany( data.company || null, {
transaction,
});
await audit_events.setPlant( data.plant || null, {
transaction,
});
await audit_events.setActor_user( data.actor_user || null, {
transaction,
});
await audit_events.setOrganizations( data.organizations || null, {
transaction,
});
return audit_events;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const audit_eventsData = data.map((item, index) => ({
id: item.id || undefined,
entity_type: item.entity_type
||
null
,
entity_reference: item.entity_reference
||
null
,
action: item.action
||
null
,
event_at: item.event_at
||
null
,
details: item.details
||
null
,
ip_address: item.ip_address
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const audit_events = await db.audit_events.bulkCreate(audit_eventsData, { transaction });
// For each item created, replace relation files
return audit_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const audit_events = await db.audit_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.entity_type !== undefined) updatePayload.entity_type = data.entity_type;
if (data.entity_reference !== undefined) updatePayload.entity_reference = data.entity_reference;
if (data.action !== undefined) updatePayload.action = data.action;
if (data.event_at !== undefined) updatePayload.event_at = data.event_at;
if (data.details !== undefined) updatePayload.details = data.details;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
updatePayload.updatedById = currentUser.id;
await audit_events.update(updatePayload, {transaction});
if (data.company !== undefined) {
await audit_events.setCompany(
data.company,
{ transaction }
);
}
if (data.plant !== undefined) {
await audit_events.setPlant(
data.plant,
{ transaction }
);
}
if (data.actor_user !== undefined) {
await audit_events.setActor_user(
data.actor_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await audit_events.setOrganizations(
data.organizations,
{ transaction }
);
}
return audit_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of audit_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of audit_events) {
await record.destroy({transaction});
}
});
return audit_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findByPk(id, options);
await audit_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await audit_events.destroy({
transaction
});
return audit_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findOne(
{ where },
{ transaction },
);
if (!audit_events) {
return audit_events;
}
const output = audit_events.get({plain: true});
output.company = await audit_events.getCompany({
transaction
});
output.plant = await audit_events.getPlant({
transaction
});
output.actor_user = await audit_events.getActor_user({
transaction
});
output.organizations = await audit_events.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.companies,
as: 'company',
where: filter.company ? {
[Op.or]: [
{ id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.plants,
as: 'plant',
where: filter.plant ? {
[Op.or]: [
{ id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'actor_user',
where: filter.actor_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.actor_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.actor_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.entity_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'entity_reference',
filter.entity_reference,
),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'details',
filter.details,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'ip_address',
filter.ip_address,
),
};
}
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.entity_type) {
where = {
...where,
entity_type: filter.entity_type,
};
}
if (filter.action) {
where = {
...where,
action: filter.action,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.audit_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'audit_events',
'entity_reference',
query,
),
],
};
}
const records = await db.audit_events.findAll({
attributes: [ 'id', 'entity_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['entity_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.entity_reference,
}));
}
};

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 Bom_linesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bom_lines = await db.bom_lines.create(
{
id: data.id || undefined,
quantity_per: data.quantity_per
||
null
,
uom: data.uom
||
null
,
scrap_factor: data.scrap_factor
||
null
,
issue_method: data.issue_method
||
null
,
line_number: data.line_number
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await bom_lines.setBom( data.bom || null, {
transaction,
});
await bom_lines.setComponent_item( data.component_item || null, {
transaction,
});
await bom_lines.setOrganizations( data.organizations || null, {
transaction,
});
return bom_lines;
}
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 bom_linesData = data.map((item, index) => ({
id: item.id || undefined,
quantity_per: item.quantity_per
||
null
,
uom: item.uom
||
null
,
scrap_factor: item.scrap_factor
||
null
,
issue_method: item.issue_method
||
null
,
line_number: item.line_number
||
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 bom_lines = await db.bom_lines.bulkCreate(bom_linesData, { transaction });
// For each item created, replace relation files
return bom_lines;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const bom_lines = await db.bom_lines.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.quantity_per !== undefined) updatePayload.quantity_per = data.quantity_per;
if (data.uom !== undefined) updatePayload.uom = data.uom;
if (data.scrap_factor !== undefined) updatePayload.scrap_factor = data.scrap_factor;
if (data.issue_method !== undefined) updatePayload.issue_method = data.issue_method;
if (data.line_number !== undefined) updatePayload.line_number = data.line_number;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await bom_lines.update(updatePayload, {transaction});
if (data.bom !== undefined) {
await bom_lines.setBom(
data.bom,
{ transaction }
);
}
if (data.component_item !== undefined) {
await bom_lines.setComponent_item(
data.component_item,
{ transaction }
);
}
if (data.organizations !== undefined) {
await bom_lines.setOrganizations(
data.organizations,
{ transaction }
);
}
return bom_lines;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bom_lines = await db.bom_lines.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of bom_lines) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of bom_lines) {
await record.destroy({transaction});
}
});
return bom_lines;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const bom_lines = await db.bom_lines.findByPk(id, options);
await bom_lines.update({
deletedBy: currentUser.id
}, {
transaction,
});
await bom_lines.destroy({
transaction
});
return bom_lines;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const bom_lines = await db.bom_lines.findOne(
{ where },
{ transaction },
);
if (!bom_lines) {
return bom_lines;
}
const output = bom_lines.get({plain: true});
output.bom = await bom_lines.getBom({
transaction
});
output.component_item = await bom_lines.getComponent_item({
transaction
});
output.organizations = await bom_lines.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.boms,
as: 'bom',
where: filter.bom ? {
[Op.or]: [
{ id: { [Op.in]: filter.bom.split('|').map(term => Utils.uuid(term)) } },
{
revision: {
[Op.or]: filter.bom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.items,
as: 'component_item',
where: filter.component_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.component_item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.component_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.uom) {
where = {
...where,
[Op.and]: Utils.ilike(
'bom_lines',
'uom',
filter.uom,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'bom_lines',
'notes',
filter.notes,
),
};
}
if (filter.quantity_perRange) {
const [start, end] = filter.quantity_perRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_per: {
...where.quantity_per,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_per: {
...where.quantity_per,
[Op.lte]: end,
},
};
}
}
if (filter.scrap_factorRange) {
const [start, end] = filter.scrap_factorRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scrap_factor: {
...where.scrap_factor,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scrap_factor: {
...where.scrap_factor,
[Op.lte]: end,
},
};
}
}
if (filter.line_numberRange) {
const [start, end] = filter.line_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
line_number: {
...where.line_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
line_number: {
...where.line_number,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.issue_method) {
where = {
...where,
issue_method: filter.issue_method,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.bom_lines.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'bom_lines',
'notes',
query,
),
],
};
}
const records = await db.bom_lines.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};

610
backend/src/db/api/boms.js Normal file
View File

@ -0,0 +1,610 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class BomsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const boms = await db.boms.create(
{
id: data.id || undefined,
revision: data.revision
||
null
,
status: data.status
||
null
,
effective_from: data.effective_from
||
null
,
effective_to: data.effective_to
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await boms.setCompany( data.company || null, {
transaction,
});
await boms.setParent_item( data.parent_item || null, {
transaction,
});
await boms.setOrganizations( data.organizations || null, {
transaction,
});
return boms;
}
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 bomsData = data.map((item, index) => ({
id: item.id || undefined,
revision: item.revision
||
null
,
status: item.status
||
null
,
effective_from: item.effective_from
||
null
,
effective_to: item.effective_to
||
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 boms = await db.boms.bulkCreate(bomsData, { transaction });
// For each item created, replace relation files
return boms;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const boms = await db.boms.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.revision !== undefined) updatePayload.revision = data.revision;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.effective_from !== undefined) updatePayload.effective_from = data.effective_from;
if (data.effective_to !== undefined) updatePayload.effective_to = data.effective_to;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await boms.update(updatePayload, {transaction});
if (data.company !== undefined) {
await boms.setCompany(
data.company,
{ transaction }
);
}
if (data.parent_item !== undefined) {
await boms.setParent_item(
data.parent_item,
{ transaction }
);
}
if (data.organizations !== undefined) {
await boms.setOrganizations(
data.organizations,
{ transaction }
);
}
return boms;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const boms = await db.boms.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of boms) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of boms) {
await record.destroy({transaction});
}
});
return boms;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const boms = await db.boms.findByPk(id, options);
await boms.update({
deletedBy: currentUser.id
}, {
transaction,
});
await boms.destroy({
transaction
});
return boms;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const boms = await db.boms.findOne(
{ where },
{ transaction },
);
if (!boms) {
return boms;
}
const output = boms.get({plain: true});
output.bom_lines_bom = await boms.getBom_lines_bom({
transaction
});
output.work_orders_bom = await boms.getWork_orders_bom({
transaction
});
output.company = await boms.getCompany({
transaction
});
output.parent_item = await boms.getParent_item({
transaction
});
output.organizations = await boms.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.companies,
as: 'company',
where: filter.company ? {
[Op.or]: [
{ id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.items,
as: 'parent_item',
where: filter.parent_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.parent_item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.parent_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.revision) {
where = {
...where,
[Op.and]: Utils.ilike(
'boms',
'revision',
filter.revision,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'boms',
'notes',
filter.notes,
),
};
}
if (filter.effective_fromRange) {
const [start, end] = filter.effective_fromRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_from: {
...where.effective_from,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_from: {
...where.effective_from,
[Op.lte]: end,
},
};
}
}
if (filter.effective_toRange) {
const [start, end] = filter.effective_toRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_to: {
...where.effective_to,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_to: {
...where.effective_to,
[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.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.boms.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'boms',
'revision',
query,
),
],
};
}
const records = await db.boms.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,
}));
}
};

753
backend/src/db/api/capas.js Normal file
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 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
,
status: data.status
||
null
,
problem_statement: data.problem_statement
||
null
,
root_cause: data.root_cause
||
null
,
corrective_action: data.corrective_action
||
null
,
preventive_action: data.preventive_action
||
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.setPlant( data.plant || null, {
transaction,
});
await capas.setNonconformance( data.nonconformance || null, {
transaction,
});
await capas.setOwner_user( data.owner_user || null, {
transaction,
});
await capas.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.capas.getTableName(),
belongsToColumn: 'attachments',
belongsToId: capas.id,
},
data.attachments,
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
,
status: item.status
||
null
,
problem_statement: item.problem_statement
||
null
,
root_cause: item.root_cause
||
null
,
corrective_action: item.corrective_action
||
null
,
preventive_action: item.preventive_action
||
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: 'attachments',
belongsToId: capas[i].id,
},
data[i].attachments,
options,
);
}
return capas;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const capas = await db.capas.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.capa_number !== undefined) updatePayload.capa_number = data.capa_number;
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_action !== undefined) updatePayload.corrective_action = data.corrective_action;
if (data.preventive_action !== undefined) updatePayload.preventive_action = data.preventive_action;
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.plant !== undefined) {
await capas.setPlant(
data.plant,
{ transaction }
);
}
if (data.nonconformance !== undefined) {
await capas.setNonconformance(
data.nonconformance,
{ transaction }
);
}
if (data.owner_user !== undefined) {
await capas.setOwner_user(
data.owner_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await capas.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.capas.getTableName(),
belongsToColumn: 'attachments',
belongsToId: capas.id,
},
data.attachments,
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.plant = await capas.getPlant({
transaction
});
output.nonconformance = await capas.getNonconformance({
transaction
});
output.owner_user = await capas.getOwner_user({
transaction
});
output.attachments = await capas.getAttachments({
transaction
});
output.organizations = await capas.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.plants,
as: 'plant',
where: filter.plant ? {
[Op.or]: [
{ id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.nonconformances,
as: 'nonconformance',
where: filter.nonconformance ? {
[Op.or]: [
{ id: { [Op.in]: filter.nonconformance.split('|').map(term => Utils.uuid(term)) } },
{
ncr_number: {
[Op.or]: filter.nonconformance.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner_user',
where: filter.owner_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'attachments',
},
];
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_action) {
where = {
...where,
[Op.and]: Utils.ilike(
'capas',
'corrective_action',
filter.corrective_action,
),
};
}
if (filter.preventive_action) {
where = {
...where,
[Op.and]: Utils.ilike(
'capas',
'preventive_action',
filter.preventive_action,
),
};
}
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.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
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,732 @@
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 CompaniesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const companies = await db.companies.create(
{
id: data.id || undefined,
name: data.name
||
null
,
legal_name: data.legal_name
||
null
,
tax_number: data.tax_number
||
null
,
website: data.website
||
null
,
phone: data.phone
||
null
,
address_line1: data.address_line1
||
null
,
address_line2: data.address_line2
||
null
,
city: data.city
||
null
,
state_region: data.state_region
||
null
,
postal_code: data.postal_code
||
null
,
country: data.country
||
null
,
is_active: data.is_active
||
false
,
timezone: data.timezone
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await companies.setOrganizations( data.organizations || null, {
transaction,
});
return companies;
}
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 companiesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
legal_name: item.legal_name
||
null
,
tax_number: item.tax_number
||
null
,
website: item.website
||
null
,
phone: item.phone
||
null
,
address_line1: item.address_line1
||
null
,
address_line2: item.address_line2
||
null
,
city: item.city
||
null
,
state_region: item.state_region
||
null
,
postal_code: item.postal_code
||
null
,
country: item.country
||
null
,
is_active: item.is_active
||
false
,
timezone: item.timezone
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const companies = await db.companies.bulkCreate(companiesData, { transaction });
// For each item created, replace relation files
return companies;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const companies = await db.companies.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
if (data.tax_number !== undefined) updatePayload.tax_number = data.tax_number;
if (data.website !== undefined) updatePayload.website = data.website;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state_region !== undefined) updatePayload.state_region = data.state_region;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
updatePayload.updatedById = currentUser.id;
await companies.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await companies.setOrganizations(
data.organizations,
{ transaction }
);
}
return companies;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const companies = await db.companies.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of companies) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of companies) {
await record.destroy({transaction});
}
});
return companies;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const companies = await db.companies.findByPk(id, options);
await companies.update({
deletedBy: currentUser.id
}, {
transaction,
});
await companies.destroy({
transaction
});
return companies;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const companies = await db.companies.findOne(
{ where },
{ transaction },
);
if (!companies) {
return companies;
}
const output = companies.get({plain: true});
output.plants_company = await companies.getPlants_company({
transaction
});
output.suppliers_company = await companies.getSuppliers_company({
transaction
});
output.customers_company = await companies.getCustomers_company({
transaction
});
output.items_company = await companies.getItems_company({
transaction
});
output.boms_company = await companies.getBoms_company({
transaction
});
output.lots_company = await companies.getLots_company({
transaction
});
output.qa_inspection_plans_company = await companies.getQa_inspection_plans_company({
transaction
});
output.documents_company = await companies.getDocuments_company({
transaction
});
output.audit_events_company = await companies.getAudit_events_company({
transaction
});
output.organizations = await companies.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'name',
filter.name,
),
};
}
if (filter.legal_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'legal_name',
filter.legal_name,
),
};
}
if (filter.tax_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'tax_number',
filter.tax_number,
),
};
}
if (filter.website) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'website',
filter.website,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'phone',
filter.phone,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'address_line1',
filter.address_line1,
),
};
}
if (filter.address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'address_line2',
filter.address_line2,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'city',
filter.city,
),
};
}
if (filter.state_region) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'state_region',
filter.state_region,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'postal_code',
filter.postal_code,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'country',
filter.country,
),
};
}
if (filter.timezone) {
where = {
...where,
[Op.and]: Utils.ilike(
'companies',
'timezone',
filter.timezone,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.companies.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'companies',
'name',
query,
),
],
};
}
const records = await db.companies.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,735 @@
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 CustomersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const customers = await db.customers.create(
{
id: data.id || undefined,
name: data.name
||
null
,
code: data.code
||
null
,
contact_name: data.contact_name
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
address_line1: data.address_line1
||
null
,
address_line2: data.address_line2
||
null
,
city: data.city
||
null
,
state_region: data.state_region
||
null
,
postal_code: data.postal_code
||
null
,
country: data.country
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await customers.setCompany( data.company || null, {
transaction,
});
await customers.setOrganizations( data.organizations || null, {
transaction,
});
return customers;
}
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 customersData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
code: item.code
||
null
,
contact_name: item.contact_name
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
address_line1: item.address_line1
||
null
,
address_line2: item.address_line2
||
null
,
city: item.city
||
null
,
state_region: item.state_region
||
null
,
postal_code: item.postal_code
||
null
,
country: item.country
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const customers = await db.customers.bulkCreate(customersData, { transaction });
// For each item created, replace relation files
return customers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const customers = await db.customers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state_region !== undefined) updatePayload.state_region = data.state_region;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await customers.update(updatePayload, {transaction});
if (data.company !== undefined) {
await customers.setCompany(
data.company,
{ transaction }
);
}
if (data.organizations !== undefined) {
await customers.setOrganizations(
data.organizations,
{ transaction }
);
}
return customers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const customers = await db.customers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of customers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of customers) {
await record.destroy({transaction});
}
});
return customers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const customers = await db.customers.findByPk(id, options);
await customers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await customers.destroy({
transaction
});
return customers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const customers = await db.customers.findOne(
{ where },
{ transaction },
);
if (!customers) {
return customers;
}
const output = customers.get({plain: true});
output.work_orders_customer = await customers.getWork_orders_customer({
transaction
});
output.company = await customers.getCompany({
transaction
});
output.organizations = await customers.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.companies,
as: 'company',
where: filter.company ? {
[Op.or]: [
{ id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'code',
filter.code,
),
};
}
if (filter.contact_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'contact_name',
filter.contact_name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'phone',
filter.phone,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'address_line1',
filter.address_line1,
),
};
}
if (filter.address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'address_line2',
filter.address_line2,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'city',
filter.city,
),
};
}
if (filter.state_region) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'state_region',
filter.state_region,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'postal_code',
filter.postal_code,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'country',
filter.country,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.customers.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'customers',
'name',
query,
),
],
};
}
const records = await db.customers.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,712 @@
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
,
document_type: data.document_type
||
null
,
revision: data.revision
||
null
,
status: data.status
||
null
,
effective_at: data.effective_at
||
null
,
review_due_at: data.review_due_at
||
null
,
summary: data.summary
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await documents.setCompany( data.company || null, {
transaction,
});
await documents.setOwner_user( data.owner_user || null, {
transaction,
});
await documents.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.documents.getTableName(),
belongsToColumn: 'file',
belongsToId: documents.id,
},
data.file,
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
,
document_type: item.document_type
||
null
,
revision: item.revision
||
null
,
status: item.status
||
null
,
effective_at: item.effective_at
||
null
,
review_due_at: item.review_due_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 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: 'file',
belongsToId: documents[i].id,
},
data[i].file,
options,
);
}
return documents;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const 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.document_type !== undefined) updatePayload.document_type = data.document_type;
if (data.revision !== undefined) updatePayload.revision = data.revision;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.effective_at !== undefined) updatePayload.effective_at = data.effective_at;
if (data.review_due_at !== undefined) updatePayload.review_due_at = data.review_due_at;
if (data.summary !== undefined) updatePayload.summary = data.summary;
updatePayload.updatedById = currentUser.id;
await documents.update(updatePayload, {transaction});
if (data.company !== undefined) {
await documents.setCompany(
data.company,
{ transaction }
);
}
if (data.owner_user !== undefined) {
await documents.setOwner_user(
data.owner_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await documents.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.documents.getTableName(),
belongsToColumn: 'file',
belongsToId: documents.id,
},
data.file,
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.company = await documents.getCompany({
transaction
});
output.file = await documents.getFile({
transaction
});
output.owner_user = await documents.getOwner_user({
transaction
});
output.organizations = await documents.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.companies,
as: 'company',
where: filter.company ? {
[Op.or]: [
{ id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner_user',
where: filter.owner_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'file',
},
];
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.revision) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'revision',
filter.revision,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'summary',
filter.summary,
),
};
}
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.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.document_type) {
where = {
...where,
document_type: filter.document_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
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,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,706 @@
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 Inventory_balancesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory_balances = await db.inventory_balances.create(
{
id: data.id || undefined,
quantity_on_hand: data.quantity_on_hand
||
null
,
quantity_allocated: data.quantity_allocated
||
null
,
quantity_available: data.quantity_available
||
null
,
uom: data.uom
||
null
,
last_counted_at: data.last_counted_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inventory_balances.setPlant( data.plant || null, {
transaction,
});
await inventory_balances.setLocation( data.location || null, {
transaction,
});
await inventory_balances.setItem( data.item || null, {
transaction,
});
await inventory_balances.setLot( data.lot || null, {
transaction,
});
await inventory_balances.setOrganizations( data.organizations || null, {
transaction,
});
return inventory_balances;
}
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 inventory_balancesData = data.map((item, index) => ({
id: item.id || undefined,
quantity_on_hand: item.quantity_on_hand
||
null
,
quantity_allocated: item.quantity_allocated
||
null
,
quantity_available: item.quantity_available
||
null
,
uom: item.uom
||
null
,
last_counted_at: item.last_counted_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const inventory_balances = await db.inventory_balances.bulkCreate(inventory_balancesData, { transaction });
// For each item created, replace relation files
return inventory_balances;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const inventory_balances = await db.inventory_balances.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.quantity_on_hand !== undefined) updatePayload.quantity_on_hand = data.quantity_on_hand;
if (data.quantity_allocated !== undefined) updatePayload.quantity_allocated = data.quantity_allocated;
if (data.quantity_available !== undefined) updatePayload.quantity_available = data.quantity_available;
if (data.uom !== undefined) updatePayload.uom = data.uom;
if (data.last_counted_at !== undefined) updatePayload.last_counted_at = data.last_counted_at;
updatePayload.updatedById = currentUser.id;
await inventory_balances.update(updatePayload, {transaction});
if (data.plant !== undefined) {
await inventory_balances.setPlant(
data.plant,
{ transaction }
);
}
if (data.location !== undefined) {
await inventory_balances.setLocation(
data.location,
{ transaction }
);
}
if (data.item !== undefined) {
await inventory_balances.setItem(
data.item,
{ transaction }
);
}
if (data.lot !== undefined) {
await inventory_balances.setLot(
data.lot,
{ transaction }
);
}
if (data.organizations !== undefined) {
await inventory_balances.setOrganizations(
data.organizations,
{ transaction }
);
}
return inventory_balances;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory_balances = await db.inventory_balances.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inventory_balances) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inventory_balances) {
await record.destroy({transaction});
}
});
return inventory_balances;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inventory_balances = await db.inventory_balances.findByPk(id, options);
await inventory_balances.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inventory_balances.destroy({
transaction
});
return inventory_balances;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inventory_balances = await db.inventory_balances.findOne(
{ where },
{ transaction },
);
if (!inventory_balances) {
return inventory_balances;
}
const output = inventory_balances.get({plain: true});
output.plant = await inventory_balances.getPlant({
transaction
});
output.location = await inventory_balances.getLocation({
transaction
});
output.item = await inventory_balances.getItem({
transaction
});
output.lot = await inventory_balances.getLot({
transaction
});
output.organizations = await inventory_balances.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.plants,
as: 'plant',
where: filter.plant ? {
[Op.or]: [
{ id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.locations,
as: 'location',
where: filter.location ? {
[Op.or]: [
{ id: { [Op.in]: filter.location.split('|').map(term => Utils.uuid(term)) } },
{
code: {
[Op.or]: filter.location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.lots,
as: 'lot',
where: filter.lot ? {
[Op.or]: [
{ id: { [Op.in]: filter.lot.split('|').map(term => Utils.uuid(term)) } },
{
lot_number: {
[Op.or]: filter.lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.uom) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_balances',
'uom',
filter.uom,
),
};
}
if (filter.quantity_on_handRange) {
const [start, end] = filter.quantity_on_handRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_on_hand: {
...where.quantity_on_hand,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_on_hand: {
...where.quantity_on_hand,
[Op.lte]: end,
},
};
}
}
if (filter.quantity_allocatedRange) {
const [start, end] = filter.quantity_allocatedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_allocated: {
...where.quantity_allocated,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_allocated: {
...where.quantity_allocated,
[Op.lte]: end,
},
};
}
}
if (filter.quantity_availableRange) {
const [start, end] = filter.quantity_availableRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_available: {
...where.quantity_available,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_available: {
...where.quantity_available,
[Op.lte]: end,
},
};
}
}
if (filter.last_counted_atRange) {
const [start, end] = filter.last_counted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_counted_at: {
...where.last_counted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_counted_at: {
...where.last_counted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.inventory_balances.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'inventory_balances',
'uom',
query,
),
],
};
}
const records = await db.inventory_balances.findAll({
attributes: [ 'id', 'uom' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['uom', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.uom,
}));
}
};

View File

@ -0,0 +1,774 @@
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 Inventory_transactionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory_transactions = await db.inventory_transactions.create(
{
id: data.id || undefined,
transaction_type: data.transaction_type
||
null
,
quantity: data.quantity
||
null
,
uom: data.uom
||
null
,
transaction_at: data.transaction_at
||
null
,
reference: data.reference
||
null
,
reason: data.reason
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inventory_transactions.setPlant( data.plant || null, {
transaction,
});
await inventory_transactions.setItem( data.item || null, {
transaction,
});
await inventory_transactions.setLot( data.lot || null, {
transaction,
});
await inventory_transactions.setFrom_location( data.from_location || null, {
transaction,
});
await inventory_transactions.setTo_location( data.to_location || null, {
transaction,
});
await inventory_transactions.setPerformed_by_user( data.performed_by_user || null, {
transaction,
});
await inventory_transactions.setOrganizations( data.organizations || null, {
transaction,
});
return inventory_transactions;
}
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 inventory_transactionsData = data.map((item, index) => ({
id: item.id || undefined,
transaction_type: item.transaction_type
||
null
,
quantity: item.quantity
||
null
,
uom: item.uom
||
null
,
transaction_at: item.transaction_at
||
null
,
reference: item.reference
||
null
,
reason: item.reason
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const inventory_transactions = await db.inventory_transactions.bulkCreate(inventory_transactionsData, { transaction });
// For each item created, replace relation files
return inventory_transactions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const inventory_transactions = await db.inventory_transactions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.transaction_type !== undefined) updatePayload.transaction_type = data.transaction_type;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.uom !== undefined) updatePayload.uom = data.uom;
if (data.transaction_at !== undefined) updatePayload.transaction_at = data.transaction_at;
if (data.reference !== undefined) updatePayload.reference = data.reference;
if (data.reason !== undefined) updatePayload.reason = data.reason;
updatePayload.updatedById = currentUser.id;
await inventory_transactions.update(updatePayload, {transaction});
if (data.plant !== undefined) {
await inventory_transactions.setPlant(
data.plant,
{ transaction }
);
}
if (data.item !== undefined) {
await inventory_transactions.setItem(
data.item,
{ transaction }
);
}
if (data.lot !== undefined) {
await inventory_transactions.setLot(
data.lot,
{ transaction }
);
}
if (data.from_location !== undefined) {
await inventory_transactions.setFrom_location(
data.from_location,
{ transaction }
);
}
if (data.to_location !== undefined) {
await inventory_transactions.setTo_location(
data.to_location,
{ transaction }
);
}
if (data.performed_by_user !== undefined) {
await inventory_transactions.setPerformed_by_user(
data.performed_by_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await inventory_transactions.setOrganizations(
data.organizations,
{ transaction }
);
}
return inventory_transactions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory_transactions = await db.inventory_transactions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inventory_transactions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inventory_transactions) {
await record.destroy({transaction});
}
});
return inventory_transactions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inventory_transactions = await db.inventory_transactions.findByPk(id, options);
await inventory_transactions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inventory_transactions.destroy({
transaction
});
return inventory_transactions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inventory_transactions = await db.inventory_transactions.findOne(
{ where },
{ transaction },
);
if (!inventory_transactions) {
return inventory_transactions;
}
const output = inventory_transactions.get({plain: true});
output.plant = await inventory_transactions.getPlant({
transaction
});
output.item = await inventory_transactions.getItem({
transaction
});
output.lot = await inventory_transactions.getLot({
transaction
});
output.from_location = await inventory_transactions.getFrom_location({
transaction
});
output.to_location = await inventory_transactions.getTo_location({
transaction
});
output.performed_by_user = await inventory_transactions.getPerformed_by_user({
transaction
});
output.organizations = await inventory_transactions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.plants,
as: 'plant',
where: filter.plant ? {
[Op.or]: [
{ id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.lots,
as: 'lot',
where: filter.lot ? {
[Op.or]: [
{ id: { [Op.in]: filter.lot.split('|').map(term => Utils.uuid(term)) } },
{
lot_number: {
[Op.or]: filter.lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.locations,
as: 'from_location',
where: filter.from_location ? {
[Op.or]: [
{ id: { [Op.in]: filter.from_location.split('|').map(term => Utils.uuid(term)) } },
{
code: {
[Op.or]: filter.from_location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.locations,
as: 'to_location',
where: filter.to_location ? {
[Op.or]: [
{ id: { [Op.in]: filter.to_location.split('|').map(term => Utils.uuid(term)) } },
{
code: {
[Op.or]: filter.to_location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'performed_by_user',
where: filter.performed_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.performed_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.performed_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.uom) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_transactions',
'uom',
filter.uom,
),
};
}
if (filter.reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_transactions',
'reference',
filter.reference,
),
};
}
if (filter.reason) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_transactions',
'reason',
filter.reason,
),
};
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.transaction_atRange) {
const [start, end] = filter.transaction_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
transaction_at: {
...where.transaction_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
transaction_at: {
...where.transaction_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.transaction_type) {
where = {
...where,
transaction_type: filter.transaction_type,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.inventory_transactions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'inventory_transactions',
'reference',
query,
),
],
};
}
const records = await db.inventory_transactions.findAll({
attributes: [ 'id', 'reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reference,
}));
}
};

838
backend/src/db/api/items.js Normal file
View File

@ -0,0 +1,838 @@
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 ItemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const items = await db.items.create(
{
id: data.id || undefined,
sku: data.sku
||
null
,
name: data.name
||
null
,
description: data.description
||
null
,
item_type: data.item_type
||
null
,
uom: data.uom
||
null
,
is_lot_tracked: data.is_lot_tracked
||
false
,
requires_expiry: data.requires_expiry
||
false
,
shelf_life_days: data.shelf_life_days
||
null
,
standard_cost: data.standard_cost
||
null
,
standard_price: data.standard_price
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await items.setCompany( data.company || null, {
transaction,
});
await items.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.items.getTableName(),
belongsToColumn: 'spec_documents',
belongsToId: items.id,
},
data.spec_documents,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.items.getTableName(),
belongsToColumn: 'images',
belongsToId: items.id,
},
data.images,
options,
);
return 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 itemsData = data.map((item, index) => ({
id: item.id || undefined,
sku: item.sku
||
null
,
name: item.name
||
null
,
description: item.description
||
null
,
item_type: item.item_type
||
null
,
uom: item.uom
||
null
,
is_lot_tracked: item.is_lot_tracked
||
false
,
requires_expiry: item.requires_expiry
||
false
,
shelf_life_days: item.shelf_life_days
||
null
,
standard_cost: item.standard_cost
||
null
,
standard_price: item.standard_price
||
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 items = await db.items.bulkCreate(itemsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < items.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.items.getTableName(),
belongsToColumn: 'spec_documents',
belongsToId: items[i].id,
},
data[i].spec_documents,
options,
);
}
for (let i = 0; i < items.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.items.getTableName(),
belongsToColumn: 'images',
belongsToId: items[i].id,
},
data[i].images,
options,
);
}
return items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const items = await db.items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.sku !== undefined) updatePayload.sku = data.sku;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
if (data.uom !== undefined) updatePayload.uom = data.uom;
if (data.is_lot_tracked !== undefined) updatePayload.is_lot_tracked = data.is_lot_tracked;
if (data.requires_expiry !== undefined) updatePayload.requires_expiry = data.requires_expiry;
if (data.shelf_life_days !== undefined) updatePayload.shelf_life_days = data.shelf_life_days;
if (data.standard_cost !== undefined) updatePayload.standard_cost = data.standard_cost;
if (data.standard_price !== undefined) updatePayload.standard_price = data.standard_price;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await items.update(updatePayload, {transaction});
if (data.company !== undefined) {
await items.setCompany(
data.company,
{ transaction }
);
}
if (data.organizations !== undefined) {
await items.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.items.getTableName(),
belongsToColumn: 'spec_documents',
belongsToId: items.id,
},
data.spec_documents,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.items.getTableName(),
belongsToColumn: 'images',
belongsToId: items.id,
},
data.images,
options,
);
return items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const items = await db.items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of items) {
await record.destroy({transaction});
}
});
return items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const items = await db.items.findByPk(id, options);
await items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await items.destroy({
transaction
});
return items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const items = await db.items.findOne(
{ where },
{ transaction },
);
if (!items) {
return items;
}
const output = items.get({plain: true});
output.boms_parent_item = await items.getBoms_parent_item({
transaction
});
output.bom_lines_component_item = await items.getBom_lines_component_item({
transaction
});
output.lots_item = await items.getLots_item({
transaction
});
output.inventory_balances_item = await items.getInventory_balances_item({
transaction
});
output.inventory_transactions_item = await items.getInventory_transactions_item({
transaction
});
output.work_orders_item = await items.getWork_orders_item({
transaction
});
output.material_issues_item = await items.getMaterial_issues_item({
transaction
});
output.qa_inspection_plans_item = await items.getQa_inspection_plans_item({
transaction
});
output.qa_inspections_item = await items.getQa_inspections_item({
transaction
});
output.nonconformances_item = await items.getNonconformances_item({
transaction
});
output.company = await items.getCompany({
transaction
});
output.spec_documents = await items.getSpec_documents({
transaction
});
output.images = await items.getImages({
transaction
});
output.organizations = await items.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.companies,
as: 'company',
where: filter.company ? {
[Op.or]: [
{ id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'spec_documents',
},
{
model: db.file,
as: 'images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.sku) {
where = {
...where,
[Op.and]: Utils.ilike(
'items',
'sku',
filter.sku,
),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'items',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'items',
'description',
filter.description,
),
};
}
if (filter.uom) {
where = {
...where,
[Op.and]: Utils.ilike(
'items',
'uom',
filter.uom,
),
};
}
if (filter.shelf_life_daysRange) {
const [start, end] = filter.shelf_life_daysRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
shelf_life_days: {
...where.shelf_life_days,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
shelf_life_days: {
...where.shelf_life_days,
[Op.lte]: end,
},
};
}
}
if (filter.standard_costRange) {
const [start, end] = filter.standard_costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
standard_cost: {
...where.standard_cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
standard_cost: {
...where.standard_cost,
[Op.lte]: end,
},
};
}
}
if (filter.standard_priceRange) {
const [start, end] = filter.standard_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
standard_price: {
...where.standard_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
standard_price: {
...where.standard_price,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.item_type) {
where = {
...where,
item_type: filter.item_type,
};
}
if (filter.is_lot_tracked) {
where = {
...where,
is_lot_tracked: filter.is_lot_tracked,
};
}
if (filter.requires_expiry) {
where = {
...where,
requires_expiry: filter.requires_expiry,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'items',
'name',
query,
),
],
};
}
const records = await db.items.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,529 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class LocationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const locations = await db.locations.create(
{
id: data.id || undefined,
name: data.name
||
null
,
code: data.code
||
null
,
location_type: data.location_type
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await locations.setWarehouse( data.warehouse || null, {
transaction,
});
await locations.setOrganizations( data.organizations || null, {
transaction,
});
return locations;
}
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 locationsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
code: item.code
||
null
,
location_type: item.location_type
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const locations = await db.locations.bulkCreate(locationsData, { transaction });
// For each item created, replace relation files
return locations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const locations = await db.locations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.location_type !== undefined) updatePayload.location_type = data.location_type;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await locations.update(updatePayload, {transaction});
if (data.warehouse !== undefined) {
await locations.setWarehouse(
data.warehouse,
{ transaction }
);
}
if (data.organizations !== undefined) {
await locations.setOrganizations(
data.organizations,
{ transaction }
);
}
return locations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const locations = await db.locations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of locations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of locations) {
await record.destroy({transaction});
}
});
return locations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const locations = await db.locations.findByPk(id, options);
await locations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await locations.destroy({
transaction
});
return locations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const locations = await db.locations.findOne(
{ where },
{ transaction },
);
if (!locations) {
return locations;
}
const output = locations.get({plain: true});
output.inventory_balances_location = await locations.getInventory_balances_location({
transaction
});
output.inventory_transactions_from_location = await locations.getInventory_transactions_from_location({
transaction
});
output.inventory_transactions_to_location = await locations.getInventory_transactions_to_location({
transaction
});
output.material_issues_from_location = await locations.getMaterial_issues_from_location({
transaction
});
output.warehouse = await locations.getWarehouse({
transaction
});
output.organizations = await locations.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.warehouses,
as: 'warehouse',
where: filter.warehouse ? {
[Op.or]: [
{ id: { [Op.in]: filter.warehouse.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.warehouse.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'locations',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'locations',
'code',
filter.code,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.location_type) {
where = {
...where,
location_type: filter.location_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.locations.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'locations',
'code',
query,
),
],
};
}
const records = await db.locations.findAll({
attributes: [ 'id', 'code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.code,
}));
}
};

864
backend/src/db/api/lots.js Normal file
View File

@ -0,0 +1,864 @@
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 LotsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const lots = await db.lots.create(
{
id: data.id || undefined,
lot_number: data.lot_number
||
null
,
supplier_lot_number: data.supplier_lot_number
||
null
,
received_at: data.received_at
||
null
,
manufactured_at: data.manufactured_at
||
null
,
expiry_at: data.expiry_at
||
null
,
status: data.status
||
null
,
quantity_received: data.quantity_received
||
null
,
quantity_available: data.quantity_available
||
null
,
uom: data.uom
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await lots.setCompany( data.company || null, {
transaction,
});
await lots.setItem( data.item || null, {
transaction,
});
await lots.setSupplier( data.supplier || null, {
transaction,
});
await lots.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.lots.getTableName(),
belongsToColumn: 'coa_documents',
belongsToId: lots.id,
},
data.coa_documents,
options,
);
return lots;
}
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 lotsData = data.map((item, index) => ({
id: item.id || undefined,
lot_number: item.lot_number
||
null
,
supplier_lot_number: item.supplier_lot_number
||
null
,
received_at: item.received_at
||
null
,
manufactured_at: item.manufactured_at
||
null
,
expiry_at: item.expiry_at
||
null
,
status: item.status
||
null
,
quantity_received: item.quantity_received
||
null
,
quantity_available: item.quantity_available
||
null
,
uom: item.uom
||
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 lots = await db.lots.bulkCreate(lotsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < lots.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.lots.getTableName(),
belongsToColumn: 'coa_documents',
belongsToId: lots[i].id,
},
data[i].coa_documents,
options,
);
}
return lots;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const lots = await db.lots.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.lot_number !== undefined) updatePayload.lot_number = data.lot_number;
if (data.supplier_lot_number !== undefined) updatePayload.supplier_lot_number = data.supplier_lot_number;
if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
if (data.manufactured_at !== undefined) updatePayload.manufactured_at = data.manufactured_at;
if (data.expiry_at !== undefined) updatePayload.expiry_at = data.expiry_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.quantity_received !== undefined) updatePayload.quantity_received = data.quantity_received;
if (data.quantity_available !== undefined) updatePayload.quantity_available = data.quantity_available;
if (data.uom !== undefined) updatePayload.uom = data.uom;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await lots.update(updatePayload, {transaction});
if (data.company !== undefined) {
await lots.setCompany(
data.company,
{ transaction }
);
}
if (data.item !== undefined) {
await lots.setItem(
data.item,
{ transaction }
);
}
if (data.supplier !== undefined) {
await lots.setSupplier(
data.supplier,
{ transaction }
);
}
if (data.organizations !== undefined) {
await lots.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.lots.getTableName(),
belongsToColumn: 'coa_documents',
belongsToId: lots.id,
},
data.coa_documents,
options,
);
return lots;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const lots = await db.lots.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of lots) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of lots) {
await record.destroy({transaction});
}
});
return lots;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const lots = await db.lots.findByPk(id, options);
await lots.update({
deletedBy: currentUser.id
}, {
transaction,
});
await lots.destroy({
transaction
});
return lots;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const lots = await db.lots.findOne(
{ where },
{ transaction },
);
if (!lots) {
return lots;
}
const output = lots.get({plain: true});
output.inventory_balances_lot = await lots.getInventory_balances_lot({
transaction
});
output.inventory_transactions_lot = await lots.getInventory_transactions_lot({
transaction
});
output.material_issues_lot = await lots.getMaterial_issues_lot({
transaction
});
output.production_lots_lot = await lots.getProduction_lots_lot({
transaction
});
output.qa_inspections_lot = await lots.getQa_inspections_lot({
transaction
});
output.nonconformances_lot = await lots.getNonconformances_lot({
transaction
});
output.company = await lots.getCompany({
transaction
});
output.item = await lots.getItem({
transaction
});
output.supplier = await lots.getSupplier({
transaction
});
output.coa_documents = await lots.getCoa_documents({
transaction
});
output.organizations = await lots.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.companies,
as: 'company',
where: filter.company ? {
[Op.or]: [
{ id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.item.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)) } },
{
name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'coa_documents',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.lot_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'lots',
'lot_number',
filter.lot_number,
),
};
}
if (filter.supplier_lot_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'lots',
'supplier_lot_number',
filter.supplier_lot_number,
),
};
}
if (filter.uom) {
where = {
...where,
[Op.and]: Utils.ilike(
'lots',
'uom',
filter.uom,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'lots',
'notes',
filter.notes,
),
};
}
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.manufactured_atRange) {
const [start, end] = filter.manufactured_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
manufactured_at: {
...where.manufactured_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
manufactured_at: {
...where.manufactured_at,
[Op.lte]: end,
},
};
}
}
if (filter.expiry_atRange) {
const [start, end] = filter.expiry_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expiry_at: {
...where.expiry_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expiry_at: {
...where.expiry_at,
[Op.lte]: end,
},
};
}
}
if (filter.quantity_receivedRange) {
const [start, end] = filter.quantity_receivedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_received: {
...where.quantity_received,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_received: {
...where.quantity_received,
[Op.lte]: end,
},
};
}
}
if (filter.quantity_availableRange) {
const [start, end] = filter.quantity_availableRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_available: {
...where.quantity_available,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_available: {
...where.quantity_available,
[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.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.lots.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'lots',
'lot_number',
query,
),
],
};
}
const records = await db.lots.findAll({
attributes: [ 'id', 'lot_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['lot_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.lot_number,
}));
}
};

View File

@ -0,0 +1,653 @@
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 Machine_downtime_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const machine_downtime_events = await db.machine_downtime_events.create(
{
id: data.id || undefined,
downtime_type: data.downtime_type
||
null
,
reason_category: data.reason_category
||
null
,
reason_detail: data.reason_detail
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
duration_minutes: data.duration_minutes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await machine_downtime_events.setMachine( data.machine || null, {
transaction,
});
await machine_downtime_events.setReported_by_user( data.reported_by_user || null, {
transaction,
});
await machine_downtime_events.setOrganizations( data.organizations || null, {
transaction,
});
return machine_downtime_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 machine_downtime_eventsData = data.map((item, index) => ({
id: item.id || undefined,
downtime_type: item.downtime_type
||
null
,
reason_category: item.reason_category
||
null
,
reason_detail: item.reason_detail
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
duration_minutes: item.duration_minutes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const machine_downtime_events = await db.machine_downtime_events.bulkCreate(machine_downtime_eventsData, { transaction });
// For each item created, replace relation files
return machine_downtime_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const machine_downtime_events = await db.machine_downtime_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.downtime_type !== undefined) updatePayload.downtime_type = data.downtime_type;
if (data.reason_category !== undefined) updatePayload.reason_category = data.reason_category;
if (data.reason_detail !== undefined) updatePayload.reason_detail = data.reason_detail;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.duration_minutes !== undefined) updatePayload.duration_minutes = data.duration_minutes;
updatePayload.updatedById = currentUser.id;
await machine_downtime_events.update(updatePayload, {transaction});
if (data.machine !== undefined) {
await machine_downtime_events.setMachine(
data.machine,
{ transaction }
);
}
if (data.reported_by_user !== undefined) {
await machine_downtime_events.setReported_by_user(
data.reported_by_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await machine_downtime_events.setOrganizations(
data.organizations,
{ transaction }
);
}
return machine_downtime_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const machine_downtime_events = await db.machine_downtime_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of machine_downtime_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of machine_downtime_events) {
await record.destroy({transaction});
}
});
return machine_downtime_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const machine_downtime_events = await db.machine_downtime_events.findByPk(id, options);
await machine_downtime_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await machine_downtime_events.destroy({
transaction
});
return machine_downtime_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const machine_downtime_events = await db.machine_downtime_events.findOne(
{ where },
{ transaction },
);
if (!machine_downtime_events) {
return machine_downtime_events;
}
const output = machine_downtime_events.get({plain: true});
output.machine = await machine_downtime_events.getMachine({
transaction
});
output.reported_by_user = await machine_downtime_events.getReported_by_user({
transaction
});
output.organizations = await machine_downtime_events.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.machines,
as: 'machine',
where: filter.machine ? {
[Op.or]: [
{ id: { [Op.in]: filter.machine.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.machine.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'reported_by_user',
where: filter.reported_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.reported_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.reported_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reason_detail) {
where = {
...where,
[Op.and]: Utils.ilike(
'machine_downtime_events',
'reason_detail',
filter.reason_detail,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_atRange) {
const [start, end] = filter.start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.lte]: end,
},
};
}
}
if (filter.end_atRange) {
const [start, end] = filter.end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.lte]: end,
},
};
}
}
if (filter.duration_minutesRange) {
const [start, end] = filter.duration_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_minutes: {
...where.duration_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_minutes: {
...where.duration_minutes,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.downtime_type) {
where = {
...where,
downtime_type: filter.downtime_type,
};
}
if (filter.reason_category) {
where = {
...where,
reason_category: filter.reason_category,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.machine_downtime_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'machine_downtime_events',
'reason_detail',
query,
),
],
};
}
const records = await db.machine_downtime_events.findAll({
attributes: [ 'id', 'reason_detail' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reason_detail', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reason_detail,
}));
}
};

View File

@ -0,0 +1,676 @@
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 MachinesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const machines = await db.machines.create(
{
id: data.id || undefined,
name: data.name
||
null
,
asset_tag: data.asset_tag
||
null
,
serial_number: data.serial_number
||
null
,
manufacturer: data.manufacturer
||
null
,
model: data.model
||
null
,
commissioned_at: data.commissioned_at
||
null
,
status: data.status
||
null
,
criticality: data.criticality
||
null
,
location_description: data.location_description
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await machines.setPlant( data.plant || null, {
transaction,
});
await machines.setOrganizations( data.organizations || null, {
transaction,
});
return machines;
}
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 machinesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
asset_tag: item.asset_tag
||
null
,
serial_number: item.serial_number
||
null
,
manufacturer: item.manufacturer
||
null
,
model: item.model
||
null
,
commissioned_at: item.commissioned_at
||
null
,
status: item.status
||
null
,
criticality: item.criticality
||
null
,
location_description: item.location_description
||
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 machines = await db.machines.bulkCreate(machinesData, { transaction });
// For each item created, replace relation files
return machines;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const machines = await db.machines.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.asset_tag !== undefined) updatePayload.asset_tag = data.asset_tag;
if (data.serial_number !== undefined) updatePayload.serial_number = data.serial_number;
if (data.manufacturer !== undefined) updatePayload.manufacturer = data.manufacturer;
if (data.model !== undefined) updatePayload.model = data.model;
if (data.commissioned_at !== undefined) updatePayload.commissioned_at = data.commissioned_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.criticality !== undefined) updatePayload.criticality = data.criticality;
if (data.location_description !== undefined) updatePayload.location_description = data.location_description;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await machines.update(updatePayload, {transaction});
if (data.plant !== undefined) {
await machines.setPlant(
data.plant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await machines.setOrganizations(
data.organizations,
{ transaction }
);
}
return machines;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const machines = await db.machines.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of machines) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of machines) {
await record.destroy({transaction});
}
});
return machines;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const machines = await db.machines.findByPk(id, options);
await machines.update({
deletedBy: currentUser.id
}, {
transaction,
});
await machines.destroy({
transaction
});
return machines;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const machines = await db.machines.findOne(
{ where },
{ transaction },
);
if (!machines) {
return machines;
}
const output = machines.get({plain: true});
output.machine_downtime_events_machine = await machines.getMachine_downtime_events_machine({
transaction
});
output.production_operations_machine = await machines.getProduction_operations_machine({
transaction
});
output.plant = await machines.getPlant({
transaction
});
output.organizations = await machines.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.plants,
as: 'plant',
where: filter.plant ? {
[Op.or]: [
{ id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'name',
filter.name,
),
};
}
if (filter.asset_tag) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'asset_tag',
filter.asset_tag,
),
};
}
if (filter.serial_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'serial_number',
filter.serial_number,
),
};
}
if (filter.manufacturer) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'manufacturer',
filter.manufacturer,
),
};
}
if (filter.model) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'model',
filter.model,
),
};
}
if (filter.location_description) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'location_description',
filter.location_description,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'notes',
filter.notes,
),
};
}
if (filter.commissioned_atRange) {
const [start, end] = filter.commissioned_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commissioned_at: {
...where.commissioned_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commissioned_at: {
...where.commissioned_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.criticality) {
where = {
...where,
criticality: filter.criticality,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.machines.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'machines',
'name',
query,
),
],
};
}
const records = await db.machines.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,713 @@
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 Material_issuesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const material_issues = await db.material_issues.create(
{
id: data.id || undefined,
quantity_issued: data.quantity_issued
||
null
,
uom: data.uom
||
null
,
issued_at: data.issued_at
||
null
,
issue_method: data.issue_method
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await material_issues.setWork_order( data.work_order || null, {
transaction,
});
await material_issues.setItem( data.item || null, {
transaction,
});
await material_issues.setLot( data.lot || null, {
transaction,
});
await material_issues.setFrom_location( data.from_location || null, {
transaction,
});
await material_issues.setIssued_by_user( data.issued_by_user || null, {
transaction,
});
await material_issues.setOrganizations( data.organizations || null, {
transaction,
});
return material_issues;
}
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 material_issuesData = data.map((item, index) => ({
id: item.id || undefined,
quantity_issued: item.quantity_issued
||
null
,
uom: item.uom
||
null
,
issued_at: item.issued_at
||
null
,
issue_method: item.issue_method
||
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 material_issues = await db.material_issues.bulkCreate(material_issuesData, { transaction });
// For each item created, replace relation files
return material_issues;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const material_issues = await db.material_issues.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.quantity_issued !== undefined) updatePayload.quantity_issued = data.quantity_issued;
if (data.uom !== undefined) updatePayload.uom = data.uom;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.issue_method !== undefined) updatePayload.issue_method = data.issue_method;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await material_issues.update(updatePayload, {transaction});
if (data.work_order !== undefined) {
await material_issues.setWork_order(
data.work_order,
{ transaction }
);
}
if (data.item !== undefined) {
await material_issues.setItem(
data.item,
{ transaction }
);
}
if (data.lot !== undefined) {
await material_issues.setLot(
data.lot,
{ transaction }
);
}
if (data.from_location !== undefined) {
await material_issues.setFrom_location(
data.from_location,
{ transaction }
);
}
if (data.issued_by_user !== undefined) {
await material_issues.setIssued_by_user(
data.issued_by_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await material_issues.setOrganizations(
data.organizations,
{ transaction }
);
}
return material_issues;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const material_issues = await db.material_issues.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of material_issues) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of material_issues) {
await record.destroy({transaction});
}
});
return material_issues;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const material_issues = await db.material_issues.findByPk(id, options);
await material_issues.update({
deletedBy: currentUser.id
}, {
transaction,
});
await material_issues.destroy({
transaction
});
return material_issues;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const material_issues = await db.material_issues.findOne(
{ where },
{ transaction },
);
if (!material_issues) {
return material_issues;
}
const output = material_issues.get({plain: true});
output.work_order = await material_issues.getWork_order({
transaction
});
output.item = await material_issues.getItem({
transaction
});
output.lot = await material_issues.getLot({
transaction
});
output.from_location = await material_issues.getFrom_location({
transaction
});
output.issued_by_user = await material_issues.getIssued_by_user({
transaction
});
output.organizations = await material_issues.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.work_orders,
as: 'work_order',
where: filter.work_order ? {
[Op.or]: [
{ id: { [Op.in]: filter.work_order.split('|').map(term => Utils.uuid(term)) } },
{
work_order_number: {
[Op.or]: filter.work_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.lots,
as: 'lot',
where: filter.lot ? {
[Op.or]: [
{ id: { [Op.in]: filter.lot.split('|').map(term => Utils.uuid(term)) } },
{
lot_number: {
[Op.or]: filter.lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.locations,
as: 'from_location',
where: filter.from_location ? {
[Op.or]: [
{ id: { [Op.in]: filter.from_location.split('|').map(term => Utils.uuid(term)) } },
{
code: {
[Op.or]: filter.from_location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'issued_by_user',
where: filter.issued_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.issued_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.issued_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.uom) {
where = {
...where,
[Op.and]: Utils.ilike(
'material_issues',
'uom',
filter.uom,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'material_issues',
'notes',
filter.notes,
),
};
}
if (filter.quantity_issuedRange) {
const [start, end] = filter.quantity_issuedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_issued: {
...where.quantity_issued,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_issued: {
...where.quantity_issued,
[Op.lte]: end,
},
};
}
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.issue_method) {
where = {
...where,
issue_method: filter.issue_method,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.material_issues.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'material_issues',
'notes',
query,
),
],
};
}
const records = await db.material_issues.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};

View File

@ -0,0 +1,843 @@
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,
ncr_number: data.ncr_number
||
null
,
source: data.source
||
null
,
severity: data.severity
||
null
,
status: data.status
||
null
,
description: data.description
||
null
,
containment_action: data.containment_action
||
null
,
disposition: data.disposition
||
null
,
reported_at: data.reported_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await nonconformances.setPlant( data.plant || null, {
transaction,
});
await nonconformances.setInspection( data.inspection || null, {
transaction,
});
await nonconformances.setWork_order( data.work_order || null, {
transaction,
});
await nonconformances.setItem( data.item || null, {
transaction,
});
await nonconformances.setLot( data.lot || null, {
transaction,
});
await nonconformances.setReported_by_user( data.reported_by_user || null, {
transaction,
});
await nonconformances.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.nonconformances.getTableName(),
belongsToColumn: 'attachments',
belongsToId: nonconformances.id,
},
data.attachments,
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,
ncr_number: item.ncr_number
||
null
,
source: item.source
||
null
,
severity: item.severity
||
null
,
status: item.status
||
null
,
description: item.description
||
null
,
containment_action: item.containment_action
||
null
,
disposition: item.disposition
||
null
,
reported_at: item.reported_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: 'attachments',
belongsToId: nonconformances[i].id,
},
data[i].attachments,
options,
);
}
return nonconformances;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const nonconformances = await db.nonconformances.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.ncr_number !== undefined) updatePayload.ncr_number = data.ncr_number;
if (data.source !== undefined) updatePayload.source = data.source;
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.containment_action !== undefined) updatePayload.containment_action = data.containment_action;
if (data.disposition !== undefined) updatePayload.disposition = data.disposition;
if (data.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
updatePayload.updatedById = currentUser.id;
await nonconformances.update(updatePayload, {transaction});
if (data.plant !== undefined) {
await nonconformances.setPlant(
data.plant,
{ transaction }
);
}
if (data.inspection !== undefined) {
await nonconformances.setInspection(
data.inspection,
{ transaction }
);
}
if (data.work_order !== undefined) {
await nonconformances.setWork_order(
data.work_order,
{ transaction }
);
}
if (data.item !== undefined) {
await nonconformances.setItem(
data.item,
{ transaction }
);
}
if (data.lot !== undefined) {
await nonconformances.setLot(
data.lot,
{ transaction }
);
}
if (data.reported_by_user !== undefined) {
await nonconformances.setReported_by_user(
data.reported_by_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await nonconformances.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.nonconformances.getTableName(),
belongsToColumn: 'attachments',
belongsToId: nonconformances.id,
},
data.attachments,
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.capas_nonconformance = await nonconformances.getCapas_nonconformance({
transaction
});
output.plant = await nonconformances.getPlant({
transaction
});
output.inspection = await nonconformances.getInspection({
transaction
});
output.work_order = await nonconformances.getWork_order({
transaction
});
output.item = await nonconformances.getItem({
transaction
});
output.lot = await nonconformances.getLot({
transaction
});
output.reported_by_user = await nonconformances.getReported_by_user({
transaction
});
output.attachments = await nonconformances.getAttachments({
transaction
});
output.organizations = await nonconformances.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.plants,
as: 'plant',
where: filter.plant ? {
[Op.or]: [
{ id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.qa_inspections,
as: 'inspection',
where: filter.inspection ? {
[Op.or]: [
{ id: { [Op.in]: filter.inspection.split('|').map(term => Utils.uuid(term)) } },
{
notes: {
[Op.or]: filter.inspection.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.work_orders,
as: 'work_order',
where: filter.work_order ? {
[Op.or]: [
{ id: { [Op.in]: filter.work_order.split('|').map(term => Utils.uuid(term)) } },
{
work_order_number: {
[Op.or]: filter.work_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.lots,
as: 'lot',
where: filter.lot ? {
[Op.or]: [
{ id: { [Op.in]: filter.lot.split('|').map(term => Utils.uuid(term)) } },
{
lot_number: {
[Op.or]: filter.lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'reported_by_user',
where: filter.reported_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.reported_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.reported_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.ncr_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'nonconformances',
'ncr_number',
filter.ncr_number,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'nonconformances',
'description',
filter.description,
),
};
}
if (filter.containment_action) {
where = {
...where,
[Op.and]: Utils.ilike(
'nonconformances',
'containment_action',
filter.containment_action,
),
};
}
if (filter.reported_atRange) {
const [start, end] = filter.reported_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reported_at: {
...where.reported_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reported_at: {
...where.reported_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.severity) {
where = {
...where,
severity: filter.severity,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.disposition) {
where = {
...where,
disposition: filter.disposition,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'nonconformances',
'ncr_number',
query,
),
],
};
}
const records = await db.nonconformances.findAll({
attributes: [ 'id', 'ncr_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['ncr_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.ncr_number,
}));
}
};

View File

@ -0,0 +1,481 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class OrganizationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return organizations;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const organizationsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const organizations = await db.organizations.bulkCreate(organizationsData, { transaction });
// For each item created, replace relation files
return organizations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const organizations = await db.organizations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await organizations.update(updatePayload, {transaction});
return organizations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of organizations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of organizations) {
await record.destroy({transaction});
}
});
return organizations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findByPk(id, options);
await organizations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await organizations.destroy({
transaction
});
return organizations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findOne(
{ where },
{ transaction },
);
if (!organizations) {
return organizations;
}
const output = organizations.get({plain: true});
output.users_organizations = await organizations.getUsers_organizations({
transaction
});
output.companies_organizations = await organizations.getCompanies_organizations({
transaction
});
output.plants_organizations = await organizations.getPlants_organizations({
transaction
});
output.suppliers_organizations = await organizations.getSuppliers_organizations({
transaction
});
output.customers_organizations = await organizations.getCustomers_organizations({
transaction
});
output.items_organizations = await organizations.getItems_organizations({
transaction
});
output.boms_organizations = await organizations.getBoms_organizations({
transaction
});
output.bom_lines_organizations = await organizations.getBom_lines_organizations({
transaction
});
output.warehouses_organizations = await organizations.getWarehouses_organizations({
transaction
});
output.locations_organizations = await organizations.getLocations_organizations({
transaction
});
output.lots_organizations = await organizations.getLots_organizations({
transaction
});
output.inventory_balances_organizations = await organizations.getInventory_balances_organizations({
transaction
});
output.inventory_transactions_organizations = await organizations.getInventory_transactions_organizations({
transaction
});
output.machines_organizations = await organizations.getMachines_organizations({
transaction
});
output.machine_downtime_events_organizations = await organizations.getMachine_downtime_events_organizations({
transaction
});
output.work_orders_organizations = await organizations.getWork_orders_organizations({
transaction
});
output.production_operations_organizations = await organizations.getProduction_operations_organizations({
transaction
});
output.material_issues_organizations = await organizations.getMaterial_issues_organizations({
transaction
});
output.production_lots_organizations = await organizations.getProduction_lots_organizations({
transaction
});
output.qa_inspection_plans_organizations = await organizations.getQa_inspection_plans_organizations({
transaction
});
output.qa_characteristics_organizations = await organizations.getQa_characteristics_organizations({
transaction
});
output.qa_inspections_organizations = await organizations.getQa_inspections_organizations({
transaction
});
output.qa_results_organizations = await organizations.getQa_results_organizations({
transaction
});
output.nonconformances_organizations = await organizations.getNonconformances_organizations({
transaction
});
output.capas_organizations = await organizations.getCapas_organizations({
transaction
});
output.documents_organizations = await organizations.getDocuments_organizations({
transaction
});
output.audit_events_organizations = await organizations.getAudit_events_organizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'organizations',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.organizations.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'organizations',
'name',
query,
),
],
};
}
const records = await db.organizations.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

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

View File

@ -0,0 +1,721 @@
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 PlantsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const plants = await db.plants.create(
{
id: data.id || undefined,
name: data.name
||
null
,
code: data.code
||
null
,
timezone: data.timezone
||
null
,
phone: data.phone
||
null
,
address_line1: data.address_line1
||
null
,
address_line2: data.address_line2
||
null
,
city: data.city
||
null
,
state_region: data.state_region
||
null
,
postal_code: data.postal_code
||
null
,
country: data.country
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await plants.setCompany( data.company || null, {
transaction,
});
await plants.setOrganizations( data.organizations || null, {
transaction,
});
return plants;
}
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 plantsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
code: item.code
||
null
,
timezone: item.timezone
||
null
,
phone: item.phone
||
null
,
address_line1: item.address_line1
||
null
,
address_line2: item.address_line2
||
null
,
city: item.city
||
null
,
state_region: item.state_region
||
null
,
postal_code: item.postal_code
||
null
,
country: item.country
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const plants = await db.plants.bulkCreate(plantsData, { transaction });
// For each item created, replace relation files
return plants;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const plants = await db.plants.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state_region !== undefined) updatePayload.state_region = data.state_region;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await plants.update(updatePayload, {transaction});
if (data.company !== undefined) {
await plants.setCompany(
data.company,
{ transaction }
);
}
if (data.organizations !== undefined) {
await plants.setOrganizations(
data.organizations,
{ transaction }
);
}
return plants;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const plants = await db.plants.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of plants) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of plants) {
await record.destroy({transaction});
}
});
return plants;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const plants = await db.plants.findByPk(id, options);
await plants.update({
deletedBy: currentUser.id
}, {
transaction,
});
await plants.destroy({
transaction
});
return plants;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const plants = await db.plants.findOne(
{ where },
{ transaction },
);
if (!plants) {
return plants;
}
const output = plants.get({plain: true});
output.warehouses_plant = await plants.getWarehouses_plant({
transaction
});
output.inventory_balances_plant = await plants.getInventory_balances_plant({
transaction
});
output.inventory_transactions_plant = await plants.getInventory_transactions_plant({
transaction
});
output.machines_plant = await plants.getMachines_plant({
transaction
});
output.work_orders_plant = await plants.getWork_orders_plant({
transaction
});
output.qa_inspections_plant = await plants.getQa_inspections_plant({
transaction
});
output.nonconformances_plant = await plants.getNonconformances_plant({
transaction
});
output.capas_plant = await plants.getCapas_plant({
transaction
});
output.audit_events_plant = await plants.getAudit_events_plant({
transaction
});
output.company = await plants.getCompany({
transaction
});
output.organizations = await plants.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.companies,
as: 'company',
where: filter.company ? {
[Op.or]: [
{ id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'plants',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'plants',
'code',
filter.code,
),
};
}
if (filter.timezone) {
where = {
...where,
[Op.and]: Utils.ilike(
'plants',
'timezone',
filter.timezone,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'plants',
'phone',
filter.phone,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'plants',
'address_line1',
filter.address_line1,
),
};
}
if (filter.address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'plants',
'address_line2',
filter.address_line2,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'plants',
'city',
filter.city,
),
};
}
if (filter.state_region) {
where = {
...where,
[Op.and]: Utils.ilike(
'plants',
'state_region',
filter.state_region,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'plants',
'postal_code',
filter.postal_code,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'plants',
'country',
filter.country,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.plants.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'plants',
'name',
query,
),
],
};
}
const records = await db.plants.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,602 @@
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 Production_lotsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const production_lots = await db.production_lots.create(
{
id: data.id || undefined,
produced_at: data.produced_at
||
null
,
quantity_produced: data.quantity_produced
||
null
,
uom: data.uom
||
null
,
disposition: data.disposition
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await production_lots.setWork_order( data.work_order || null, {
transaction,
});
await production_lots.setLot( data.lot || null, {
transaction,
});
await production_lots.setOrganizations( data.organizations || null, {
transaction,
});
return production_lots;
}
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 production_lotsData = data.map((item, index) => ({
id: item.id || undefined,
produced_at: item.produced_at
||
null
,
quantity_produced: item.quantity_produced
||
null
,
uom: item.uom
||
null
,
disposition: item.disposition
||
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 production_lots = await db.production_lots.bulkCreate(production_lotsData, { transaction });
// For each item created, replace relation files
return production_lots;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const production_lots = await db.production_lots.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.produced_at !== undefined) updatePayload.produced_at = data.produced_at;
if (data.quantity_produced !== undefined) updatePayload.quantity_produced = data.quantity_produced;
if (data.uom !== undefined) updatePayload.uom = data.uom;
if (data.disposition !== undefined) updatePayload.disposition = data.disposition;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await production_lots.update(updatePayload, {transaction});
if (data.work_order !== undefined) {
await production_lots.setWork_order(
data.work_order,
{ transaction }
);
}
if (data.lot !== undefined) {
await production_lots.setLot(
data.lot,
{ transaction }
);
}
if (data.organizations !== undefined) {
await production_lots.setOrganizations(
data.organizations,
{ transaction }
);
}
return production_lots;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const production_lots = await db.production_lots.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of production_lots) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of production_lots) {
await record.destroy({transaction});
}
});
return production_lots;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const production_lots = await db.production_lots.findByPk(id, options);
await production_lots.update({
deletedBy: currentUser.id
}, {
transaction,
});
await production_lots.destroy({
transaction
});
return production_lots;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const production_lots = await db.production_lots.findOne(
{ where },
{ transaction },
);
if (!production_lots) {
return production_lots;
}
const output = production_lots.get({plain: true});
output.work_order = await production_lots.getWork_order({
transaction
});
output.lot = await production_lots.getLot({
transaction
});
output.organizations = await production_lots.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.work_orders,
as: 'work_order',
where: filter.work_order ? {
[Op.or]: [
{ id: { [Op.in]: filter.work_order.split('|').map(term => Utils.uuid(term)) } },
{
work_order_number: {
[Op.or]: filter.work_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.lots,
as: 'lot',
where: filter.lot ? {
[Op.or]: [
{ id: { [Op.in]: filter.lot.split('|').map(term => Utils.uuid(term)) } },
{
lot_number: {
[Op.or]: filter.lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.uom) {
where = {
...where,
[Op.and]: Utils.ilike(
'production_lots',
'uom',
filter.uom,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'production_lots',
'notes',
filter.notes,
),
};
}
if (filter.produced_atRange) {
const [start, end] = filter.produced_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
produced_at: {
...where.produced_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
produced_at: {
...where.produced_at,
[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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.disposition) {
where = {
...where,
disposition: filter.disposition,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.production_lots.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'production_lots',
'notes',
query,
),
],
};
}
const records = await db.production_lots.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};

View File

@ -0,0 +1,787 @@
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 Production_operationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const production_operations = await db.production_operations.create(
{
id: data.id || undefined,
operation_sequence: data.operation_sequence
||
null
,
name: data.name
||
null
,
status: data.status
||
null
,
planned_start_at: data.planned_start_at
||
null
,
planned_end_at: data.planned_end_at
||
null
,
actual_start_at: data.actual_start_at
||
null
,
actual_end_at: data.actual_end_at
||
null
,
labor_minutes: data.labor_minutes
||
null
,
machine_minutes: data.machine_minutes
||
null
,
instructions: data.instructions
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await production_operations.setWork_order( data.work_order || null, {
transaction,
});
await production_operations.setMachine( data.machine || null, {
transaction,
});
await production_operations.setOrganizations( data.organizations || null, {
transaction,
});
return production_operations;
}
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 production_operationsData = data.map((item, index) => ({
id: item.id || undefined,
operation_sequence: item.operation_sequence
||
null
,
name: item.name
||
null
,
status: item.status
||
null
,
planned_start_at: item.planned_start_at
||
null
,
planned_end_at: item.planned_end_at
||
null
,
actual_start_at: item.actual_start_at
||
null
,
actual_end_at: item.actual_end_at
||
null
,
labor_minutes: item.labor_minutes
||
null
,
machine_minutes: item.machine_minutes
||
null
,
instructions: item.instructions
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const production_operations = await db.production_operations.bulkCreate(production_operationsData, { transaction });
// For each item created, replace relation files
return production_operations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const production_operations = await db.production_operations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.operation_sequence !== undefined) updatePayload.operation_sequence = data.operation_sequence;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.planned_start_at !== undefined) updatePayload.planned_start_at = data.planned_start_at;
if (data.planned_end_at !== undefined) updatePayload.planned_end_at = data.planned_end_at;
if (data.actual_start_at !== undefined) updatePayload.actual_start_at = data.actual_start_at;
if (data.actual_end_at !== undefined) updatePayload.actual_end_at = data.actual_end_at;
if (data.labor_minutes !== undefined) updatePayload.labor_minutes = data.labor_minutes;
if (data.machine_minutes !== undefined) updatePayload.machine_minutes = data.machine_minutes;
if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
updatePayload.updatedById = currentUser.id;
await production_operations.update(updatePayload, {transaction});
if (data.work_order !== undefined) {
await production_operations.setWork_order(
data.work_order,
{ transaction }
);
}
if (data.machine !== undefined) {
await production_operations.setMachine(
data.machine,
{ transaction }
);
}
if (data.organizations !== undefined) {
await production_operations.setOrganizations(
data.organizations,
{ transaction }
);
}
return production_operations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const production_operations = await db.production_operations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of production_operations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of production_operations) {
await record.destroy({transaction});
}
});
return production_operations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const production_operations = await db.production_operations.findByPk(id, options);
await production_operations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await production_operations.destroy({
transaction
});
return production_operations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const production_operations = await db.production_operations.findOne(
{ where },
{ transaction },
);
if (!production_operations) {
return production_operations;
}
const output = production_operations.get({plain: true});
output.work_order = await production_operations.getWork_order({
transaction
});
output.machine = await production_operations.getMachine({
transaction
});
output.organizations = await production_operations.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.work_orders,
as: 'work_order',
where: filter.work_order ? {
[Op.or]: [
{ id: { [Op.in]: filter.work_order.split('|').map(term => Utils.uuid(term)) } },
{
work_order_number: {
[Op.or]: filter.work_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.machines,
as: 'machine',
where: filter.machine ? {
[Op.or]: [
{ id: { [Op.in]: filter.machine.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.machine.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'production_operations',
'name',
filter.name,
),
};
}
if (filter.instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'production_operations',
'instructions',
filter.instructions,
),
};
}
if (filter.operation_sequenceRange) {
const [start, end] = filter.operation_sequenceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
operation_sequence: {
...where.operation_sequence,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
operation_sequence: {
...where.operation_sequence,
[Op.lte]: end,
},
};
}
}
if (filter.planned_start_atRange) {
const [start, end] = filter.planned_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
planned_start_at: {
...where.planned_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
planned_start_at: {
...where.planned_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.planned_end_atRange) {
const [start, end] = filter.planned_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
planned_end_at: {
...where.planned_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
planned_end_at: {
...where.planned_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.actual_start_atRange) {
const [start, end] = filter.actual_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
actual_start_at: {
...where.actual_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
actual_start_at: {
...where.actual_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.actual_end_atRange) {
const [start, end] = filter.actual_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
actual_end_at: {
...where.actual_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
actual_end_at: {
...where.actual_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.labor_minutesRange) {
const [start, end] = filter.labor_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
labor_minutes: {
...where.labor_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
labor_minutes: {
...where.labor_minutes,
[Op.lte]: end,
},
};
}
}
if (filter.machine_minutesRange) {
const [start, end] = filter.machine_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
machine_minutes: {
...where.machine_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
machine_minutes: {
...where.machine_minutes,
[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.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.production_operations.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'production_operations',
'name',
query,
),
],
};
}
const records = await db.production_operations.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,650 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Qa_characteristicsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_characteristics = await db.qa_characteristics.create(
{
id: data.id || undefined,
name: data.name
||
null
,
data_type: data.data_type
||
null
,
unit: data.unit
||
null
,
lower_spec: data.lower_spec
||
null
,
upper_spec: data.upper_spec
||
null
,
result_required: data.result_required
||
null
,
sequence: data.sequence
||
null
,
method: data.method
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await qa_characteristics.setInspection_plan( data.inspection_plan || null, {
transaction,
});
await qa_characteristics.setOrganizations( data.organizations || null, {
transaction,
});
return qa_characteristics;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const qa_characteristicsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
data_type: item.data_type
||
null
,
unit: item.unit
||
null
,
lower_spec: item.lower_spec
||
null
,
upper_spec: item.upper_spec
||
null
,
result_required: item.result_required
||
null
,
sequence: item.sequence
||
null
,
method: item.method
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const qa_characteristics = await db.qa_characteristics.bulkCreate(qa_characteristicsData, { transaction });
// For each item created, replace relation files
return qa_characteristics;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const qa_characteristics = await db.qa_characteristics.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.data_type !== undefined) updatePayload.data_type = data.data_type;
if (data.unit !== undefined) updatePayload.unit = data.unit;
if (data.lower_spec !== undefined) updatePayload.lower_spec = data.lower_spec;
if (data.upper_spec !== undefined) updatePayload.upper_spec = data.upper_spec;
if (data.result_required !== undefined) updatePayload.result_required = data.result_required;
if (data.sequence !== undefined) updatePayload.sequence = data.sequence;
if (data.method !== undefined) updatePayload.method = data.method;
updatePayload.updatedById = currentUser.id;
await qa_characteristics.update(updatePayload, {transaction});
if (data.inspection_plan !== undefined) {
await qa_characteristics.setInspection_plan(
data.inspection_plan,
{ transaction }
);
}
if (data.organizations !== undefined) {
await qa_characteristics.setOrganizations(
data.organizations,
{ transaction }
);
}
return qa_characteristics;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_characteristics = await db.qa_characteristics.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of qa_characteristics) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of qa_characteristics) {
await record.destroy({transaction});
}
});
return qa_characteristics;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const qa_characteristics = await db.qa_characteristics.findByPk(id, options);
await qa_characteristics.update({
deletedBy: currentUser.id
}, {
transaction,
});
await qa_characteristics.destroy({
transaction
});
return qa_characteristics;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const qa_characteristics = await db.qa_characteristics.findOne(
{ where },
{ transaction },
);
if (!qa_characteristics) {
return qa_characteristics;
}
const output = qa_characteristics.get({plain: true});
output.qa_results_characteristic = await qa_characteristics.getQa_results_characteristic({
transaction
});
output.inspection_plan = await qa_characteristics.getInspection_plan({
transaction
});
output.organizations = await qa_characteristics.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.qa_inspection_plans,
as: 'inspection_plan',
where: filter.inspection_plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.inspection_plan.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.inspection_plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_characteristics',
'name',
filter.name,
),
};
}
if (filter.unit) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_characteristics',
'unit',
filter.unit,
),
};
}
if (filter.method) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_characteristics',
'method',
filter.method,
),
};
}
if (filter.lower_specRange) {
const [start, end] = filter.lower_specRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lower_spec: {
...where.lower_spec,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lower_spec: {
...where.lower_spec,
[Op.lte]: end,
},
};
}
}
if (filter.upper_specRange) {
const [start, end] = filter.upper_specRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
upper_spec: {
...where.upper_spec,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
upper_spec: {
...where.upper_spec,
[Op.lte]: end,
},
};
}
}
if (filter.sequenceRange) {
const [start, end] = filter.sequenceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sequence: {
...where.sequence,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sequence: {
...where.sequence,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.data_type) {
where = {
...where,
data_type: filter.data_type,
};
}
if (filter.result_required) {
where = {
...where,
result_required: filter.result_required,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.qa_characteristics.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'qa_characteristics',
'name',
query,
),
],
};
}
const records = await db.qa_characteristics.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,613 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Qa_inspection_plansDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_inspection_plans = await db.qa_inspection_plans.create(
{
id: data.id || undefined,
name: data.name
||
null
,
inspection_type: data.inspection_type
||
null
,
sampling_method: data.sampling_method
||
null
,
sample_size: data.sample_size
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await qa_inspection_plans.setCompany( data.company || null, {
transaction,
});
await qa_inspection_plans.setItem( data.item || null, {
transaction,
});
await qa_inspection_plans.setOrganizations( data.organizations || null, {
transaction,
});
return qa_inspection_plans;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const qa_inspection_plansData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
inspection_type: item.inspection_type
||
null
,
sampling_method: item.sampling_method
||
null
,
sample_size: item.sample_size
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const qa_inspection_plans = await db.qa_inspection_plans.bulkCreate(qa_inspection_plansData, { transaction });
// For each item created, replace relation files
return qa_inspection_plans;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const qa_inspection_plans = await db.qa_inspection_plans.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.inspection_type !== undefined) updatePayload.inspection_type = data.inspection_type;
if (data.sampling_method !== undefined) updatePayload.sampling_method = data.sampling_method;
if (data.sample_size !== undefined) updatePayload.sample_size = data.sample_size;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await qa_inspection_plans.update(updatePayload, {transaction});
if (data.company !== undefined) {
await qa_inspection_plans.setCompany(
data.company,
{ transaction }
);
}
if (data.item !== undefined) {
await qa_inspection_plans.setItem(
data.item,
{ transaction }
);
}
if (data.organizations !== undefined) {
await qa_inspection_plans.setOrganizations(
data.organizations,
{ transaction }
);
}
return qa_inspection_plans;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_inspection_plans = await db.qa_inspection_plans.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of qa_inspection_plans) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of qa_inspection_plans) {
await record.destroy({transaction});
}
});
return qa_inspection_plans;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const qa_inspection_plans = await db.qa_inspection_plans.findByPk(id, options);
await qa_inspection_plans.update({
deletedBy: currentUser.id
}, {
transaction,
});
await qa_inspection_plans.destroy({
transaction
});
return qa_inspection_plans;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const qa_inspection_plans = await db.qa_inspection_plans.findOne(
{ where },
{ transaction },
);
if (!qa_inspection_plans) {
return qa_inspection_plans;
}
const output = qa_inspection_plans.get({plain: true});
output.qa_characteristics_inspection_plan = await qa_inspection_plans.getQa_characteristics_inspection_plan({
transaction
});
output.qa_inspections_inspection_plan = await qa_inspection_plans.getQa_inspections_inspection_plan({
transaction
});
output.company = await qa_inspection_plans.getCompany({
transaction
});
output.item = await qa_inspection_plans.getItem({
transaction
});
output.organizations = await qa_inspection_plans.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.companies,
as: 'company',
where: filter.company ? {
[Op.or]: [
{ id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_inspection_plans',
'name',
filter.name,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_inspection_plans',
'notes',
filter.notes,
),
};
}
if (filter.sample_sizeRange) {
const [start, end] = filter.sample_sizeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sample_size: {
...where.sample_size,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sample_size: {
...where.sample_size,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.inspection_type) {
where = {
...where,
inspection_type: filter.inspection_type,
};
}
if (filter.sampling_method) {
where = {
...where,
sampling_method: filter.sampling_method,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.qa_inspection_plans.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'qa_inspection_plans',
'name',
query,
),
],
};
}
const records = await db.qa_inspection_plans.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,871 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Qa_inspectionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_inspections = await db.qa_inspections.create(
{
id: data.id || undefined,
inspection_type: data.inspection_type
||
null
,
scheduled_at: data.scheduled_at
||
null
,
started_at: data.started_at
||
null
,
completed_at: data.completed_at
||
null
,
status: data.status
||
null
,
overall_result: data.overall_result
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await qa_inspections.setPlant( data.plant || null, {
transaction,
});
await qa_inspections.setInspection_plan( data.inspection_plan || null, {
transaction,
});
await qa_inspections.setItem( data.item || null, {
transaction,
});
await qa_inspections.setLot( data.lot || null, {
transaction,
});
await qa_inspections.setWork_order( data.work_order || null, {
transaction,
});
await qa_inspections.setInspector_user( data.inspector_user || null, {
transaction,
});
await qa_inspections.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.qa_inspections.getTableName(),
belongsToColumn: 'attachments',
belongsToId: qa_inspections.id,
},
data.attachments,
options,
);
return qa_inspections;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const qa_inspectionsData = data.map((item, index) => ({
id: item.id || undefined,
inspection_type: item.inspection_type
||
null
,
scheduled_at: item.scheduled_at
||
null
,
started_at: item.started_at
||
null
,
completed_at: item.completed_at
||
null
,
status: item.status
||
null
,
overall_result: item.overall_result
||
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 qa_inspections = await db.qa_inspections.bulkCreate(qa_inspectionsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < qa_inspections.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.qa_inspections.getTableName(),
belongsToColumn: 'attachments',
belongsToId: qa_inspections[i].id,
},
data[i].attachments,
options,
);
}
return qa_inspections;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const qa_inspections = await db.qa_inspections.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.inspection_type !== undefined) updatePayload.inspection_type = data.inspection_type;
if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.overall_result !== undefined) updatePayload.overall_result = data.overall_result;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await qa_inspections.update(updatePayload, {transaction});
if (data.plant !== undefined) {
await qa_inspections.setPlant(
data.plant,
{ transaction }
);
}
if (data.inspection_plan !== undefined) {
await qa_inspections.setInspection_plan(
data.inspection_plan,
{ transaction }
);
}
if (data.item !== undefined) {
await qa_inspections.setItem(
data.item,
{ transaction }
);
}
if (data.lot !== undefined) {
await qa_inspections.setLot(
data.lot,
{ transaction }
);
}
if (data.work_order !== undefined) {
await qa_inspections.setWork_order(
data.work_order,
{ transaction }
);
}
if (data.inspector_user !== undefined) {
await qa_inspections.setInspector_user(
data.inspector_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await qa_inspections.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.qa_inspections.getTableName(),
belongsToColumn: 'attachments',
belongsToId: qa_inspections.id,
},
data.attachments,
options,
);
return qa_inspections;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_inspections = await db.qa_inspections.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of qa_inspections) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of qa_inspections) {
await record.destroy({transaction});
}
});
return qa_inspections;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const qa_inspections = await db.qa_inspections.findByPk(id, options);
await qa_inspections.update({
deletedBy: currentUser.id
}, {
transaction,
});
await qa_inspections.destroy({
transaction
});
return qa_inspections;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const qa_inspections = await db.qa_inspections.findOne(
{ where },
{ transaction },
);
if (!qa_inspections) {
return qa_inspections;
}
const output = qa_inspections.get({plain: true});
output.qa_results_inspection = await qa_inspections.getQa_results_inspection({
transaction
});
output.nonconformances_inspection = await qa_inspections.getNonconformances_inspection({
transaction
});
output.plant = await qa_inspections.getPlant({
transaction
});
output.inspection_plan = await qa_inspections.getInspection_plan({
transaction
});
output.item = await qa_inspections.getItem({
transaction
});
output.lot = await qa_inspections.getLot({
transaction
});
output.work_order = await qa_inspections.getWork_order({
transaction
});
output.inspector_user = await qa_inspections.getInspector_user({
transaction
});
output.attachments = await qa_inspections.getAttachments({
transaction
});
output.organizations = await qa_inspections.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.plants,
as: 'plant',
where: filter.plant ? {
[Op.or]: [
{ id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.qa_inspection_plans,
as: 'inspection_plan',
where: filter.inspection_plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.inspection_plan.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.inspection_plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.lots,
as: 'lot',
where: filter.lot ? {
[Op.or]: [
{ id: { [Op.in]: filter.lot.split('|').map(term => Utils.uuid(term)) } },
{
lot_number: {
[Op.or]: filter.lot.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.work_orders,
as: 'work_order',
where: filter.work_order ? {
[Op.or]: [
{ id: { [Op.in]: filter.work_order.split('|').map(term => Utils.uuid(term)) } },
{
work_order_number: {
[Op.or]: filter.work_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'inspector_user',
where: filter.inspector_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.inspector_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.inspector_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_inspections',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
scheduled_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
completed_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.scheduled_atRange) {
const [start, end] = filter.scheduled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.lte]: end,
},
};
}
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.inspection_type) {
where = {
...where,
inspection_type: filter.inspection_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.overall_result) {
where = {
...where,
overall_result: filter.overall_result,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.qa_inspections.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'qa_inspections',
'notes',
query,
),
],
};
}
const records = await db.qa_inspections.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};

View File

@ -0,0 +1,585 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Qa_resultsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_results = await db.qa_results.create(
{
id: data.id || undefined,
numeric_value: data.numeric_value
||
null
,
attribute_value: data.attribute_value
||
null
,
result: data.result
||
null
,
unit: data.unit
||
null
,
comment: data.comment
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await qa_results.setInspection( data.inspection || null, {
transaction,
});
await qa_results.setCharacteristic( data.characteristic || null, {
transaction,
});
await qa_results.setOrganizations( data.organizations || null, {
transaction,
});
return qa_results;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const qa_resultsData = data.map((item, index) => ({
id: item.id || undefined,
numeric_value: item.numeric_value
||
null
,
attribute_value: item.attribute_value
||
null
,
result: item.result
||
null
,
unit: item.unit
||
null
,
comment: item.comment
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const qa_results = await db.qa_results.bulkCreate(qa_resultsData, { transaction });
// For each item created, replace relation files
return qa_results;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const qa_results = await db.qa_results.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.numeric_value !== undefined) updatePayload.numeric_value = data.numeric_value;
if (data.attribute_value !== undefined) updatePayload.attribute_value = data.attribute_value;
if (data.result !== undefined) updatePayload.result = data.result;
if (data.unit !== undefined) updatePayload.unit = data.unit;
if (data.comment !== undefined) updatePayload.comment = data.comment;
updatePayload.updatedById = currentUser.id;
await qa_results.update(updatePayload, {transaction});
if (data.inspection !== undefined) {
await qa_results.setInspection(
data.inspection,
{ transaction }
);
}
if (data.characteristic !== undefined) {
await qa_results.setCharacteristic(
data.characteristic,
{ transaction }
);
}
if (data.organizations !== undefined) {
await qa_results.setOrganizations(
data.organizations,
{ transaction }
);
}
return qa_results;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const qa_results = await db.qa_results.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of qa_results) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of qa_results) {
await record.destroy({transaction});
}
});
return qa_results;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const qa_results = await db.qa_results.findByPk(id, options);
await qa_results.update({
deletedBy: currentUser.id
}, {
transaction,
});
await qa_results.destroy({
transaction
});
return qa_results;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const qa_results = await db.qa_results.findOne(
{ where },
{ transaction },
);
if (!qa_results) {
return qa_results;
}
const output = qa_results.get({plain: true});
output.inspection = await qa_results.getInspection({
transaction
});
output.characteristic = await qa_results.getCharacteristic({
transaction
});
output.organizations = await qa_results.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.qa_inspections,
as: 'inspection',
where: filter.inspection ? {
[Op.or]: [
{ id: { [Op.in]: filter.inspection.split('|').map(term => Utils.uuid(term)) } },
{
notes: {
[Op.or]: filter.inspection.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.qa_characteristics,
as: 'characteristic',
where: filter.characteristic ? {
[Op.or]: [
{ id: { [Op.in]: filter.characteristic.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.characteristic.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.unit) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_results',
'unit',
filter.unit,
),
};
}
if (filter.comment) {
where = {
...where,
[Op.and]: Utils.ilike(
'qa_results',
'comment',
filter.comment,
),
};
}
if (filter.numeric_valueRange) {
const [start, end] = filter.numeric_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
numeric_value: {
...where.numeric_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
numeric_value: {
...where.numeric_value,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.attribute_value) {
where = {
...where,
attribute_value: filter.attribute_value,
};
}
if (filter.result) {
where = {
...where,
result: filter.result,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.qa_results.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'qa_results',
'comment',
query,
),
],
};
}
const records = await db.qa_results.findAll({
attributes: [ 'id', 'comment' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['comment', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.comment,
}));
}
};

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

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

View File

@ -0,0 +1,759 @@
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,
name: data.name
||
null
,
code: data.code
||
null
,
contact_name: data.contact_name
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
website: data.website
||
null
,
address_line1: data.address_line1
||
null
,
address_line2: data.address_line2
||
null
,
city: data.city
||
null
,
state_region: data.state_region
||
null
,
postal_code: data.postal_code
||
null
,
country: data.country
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await suppliers.setCompany( data.company || null, {
transaction,
});
await suppliers.setOrganizations( data.organizations || null, {
transaction,
});
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,
name: item.name
||
null
,
code: item.code
||
null
,
contact_name: item.contact_name
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
website: item.website
||
null
,
address_line1: item.address_line1
||
null
,
address_line2: item.address_line2
||
null
,
city: item.city
||
null
,
state_region: item.state_region
||
null
,
postal_code: item.postal_code
||
null
,
country: item.country
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const suppliers = await db.suppliers.bulkCreate(suppliersData, { transaction });
// For each item created, replace relation files
return suppliers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const suppliers = await db.suppliers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.website !== undefined) updatePayload.website = data.website;
if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state_region !== undefined) updatePayload.state_region = data.state_region;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await suppliers.update(updatePayload, {transaction});
if (data.company !== undefined) {
await suppliers.setCompany(
data.company,
{ transaction }
);
}
if (data.organizations !== undefined) {
await suppliers.setOrganizations(
data.organizations,
{ transaction }
);
}
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.lots_supplier = await suppliers.getLots_supplier({
transaction
});
output.company = await suppliers.getCompany({
transaction
});
output.organizations = await suppliers.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.companies,
as: 'company',
where: filter.company ? {
[Op.or]: [
{ id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'code',
filter.code,
),
};
}
if (filter.contact_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'contact_name',
filter.contact_name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'phone',
filter.phone,
),
};
}
if (filter.website) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'website',
filter.website,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'address_line1',
filter.address_line1,
),
};
}
if (filter.address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'address_line2',
filter.address_line2,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'city',
filter.city,
),
};
}
if (filter.state_region) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'state_region',
filter.state_region,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'postal_code',
filter.postal_code,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'country',
filter.country,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'suppliers',
'name',
query,
),
],
};
}
const records = await db.suppliers.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,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,517 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class WarehousesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const warehouses = await db.warehouses.create(
{
id: data.id || undefined,
name: data.name
||
null
,
code: data.code
||
null
,
warehouse_type: data.warehouse_type
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await warehouses.setPlant( data.plant || null, {
transaction,
});
await warehouses.setOrganizations( data.organizations || null, {
transaction,
});
return warehouses;
}
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 warehousesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
code: item.code
||
null
,
warehouse_type: item.warehouse_type
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const warehouses = await db.warehouses.bulkCreate(warehousesData, { transaction });
// For each item created, replace relation files
return warehouses;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const warehouses = await db.warehouses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.warehouse_type !== undefined) updatePayload.warehouse_type = data.warehouse_type;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await warehouses.update(updatePayload, {transaction});
if (data.plant !== undefined) {
await warehouses.setPlant(
data.plant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await warehouses.setOrganizations(
data.organizations,
{ transaction }
);
}
return warehouses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const warehouses = await db.warehouses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of warehouses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of warehouses) {
await record.destroy({transaction});
}
});
return warehouses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const warehouses = await db.warehouses.findByPk(id, options);
await warehouses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await warehouses.destroy({
transaction
});
return warehouses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const warehouses = await db.warehouses.findOne(
{ where },
{ transaction },
);
if (!warehouses) {
return warehouses;
}
const output = warehouses.get({plain: true});
output.locations_warehouse = await warehouses.getLocations_warehouse({
transaction
});
output.plant = await warehouses.getPlant({
transaction
});
output.organizations = await warehouses.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.plants,
as: 'plant',
where: filter.plant ? {
[Op.or]: [
{ id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'warehouses',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'warehouses',
'code',
filter.code,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.warehouse_type) {
where = {
...where,
warehouse_type: filter.warehouse_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.warehouses.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'warehouses',
'name',
query,
),
],
};
}
const records = await db.warehouses.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,892 @@
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 Work_ordersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const work_orders = await db.work_orders.create(
{
id: data.id || undefined,
work_order_number: data.work_order_number
||
null
,
quantity_planned: data.quantity_planned
||
null
,
quantity_completed: data.quantity_completed
||
null
,
uom: data.uom
||
null
,
status: data.status
||
null
,
scheduled_start_at: data.scheduled_start_at
||
null
,
scheduled_end_at: data.scheduled_end_at
||
null
,
actual_start_at: data.actual_start_at
||
null
,
actual_end_at: data.actual_end_at
||
null
,
customer_po: data.customer_po
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await work_orders.setPlant( data.plant || null, {
transaction,
});
await work_orders.setItem( data.item || null, {
transaction,
});
await work_orders.setBom( data.bom || null, {
transaction,
});
await work_orders.setCustomer( data.customer || null, {
transaction,
});
await work_orders.setOrganizations( data.organizations || null, {
transaction,
});
return work_orders;
}
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 work_ordersData = data.map((item, index) => ({
id: item.id || undefined,
work_order_number: item.work_order_number
||
null
,
quantity_planned: item.quantity_planned
||
null
,
quantity_completed: item.quantity_completed
||
null
,
uom: item.uom
||
null
,
status: item.status
||
null
,
scheduled_start_at: item.scheduled_start_at
||
null
,
scheduled_end_at: item.scheduled_end_at
||
null
,
actual_start_at: item.actual_start_at
||
null
,
actual_end_at: item.actual_end_at
||
null
,
customer_po: item.customer_po
||
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 work_orders = await db.work_orders.bulkCreate(work_ordersData, { transaction });
// For each item created, replace relation files
return work_orders;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const work_orders = await db.work_orders.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.work_order_number !== undefined) updatePayload.work_order_number = data.work_order_number;
if (data.quantity_planned !== undefined) updatePayload.quantity_planned = data.quantity_planned;
if (data.quantity_completed !== undefined) updatePayload.quantity_completed = data.quantity_completed;
if (data.uom !== undefined) updatePayload.uom = data.uom;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.scheduled_start_at !== undefined) updatePayload.scheduled_start_at = data.scheduled_start_at;
if (data.scheduled_end_at !== undefined) updatePayload.scheduled_end_at = data.scheduled_end_at;
if (data.actual_start_at !== undefined) updatePayload.actual_start_at = data.actual_start_at;
if (data.actual_end_at !== undefined) updatePayload.actual_end_at = data.actual_end_at;
if (data.customer_po !== undefined) updatePayload.customer_po = data.customer_po;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await work_orders.update(updatePayload, {transaction});
if (data.plant !== undefined) {
await work_orders.setPlant(
data.plant,
{ transaction }
);
}
if (data.item !== undefined) {
await work_orders.setItem(
data.item,
{ transaction }
);
}
if (data.bom !== undefined) {
await work_orders.setBom(
data.bom,
{ transaction }
);
}
if (data.customer !== undefined) {
await work_orders.setCustomer(
data.customer,
{ transaction }
);
}
if (data.organizations !== undefined) {
await work_orders.setOrganizations(
data.organizations,
{ transaction }
);
}
return work_orders;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const work_orders = await db.work_orders.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of work_orders) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of work_orders) {
await record.destroy({transaction});
}
});
return work_orders;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const work_orders = await db.work_orders.findByPk(id, options);
await work_orders.update({
deletedBy: currentUser.id
}, {
transaction,
});
await work_orders.destroy({
transaction
});
return work_orders;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const work_orders = await db.work_orders.findOne(
{ where },
{ transaction },
);
if (!work_orders) {
return work_orders;
}
const output = work_orders.get({plain: true});
output.production_operations_work_order = await work_orders.getProduction_operations_work_order({
transaction
});
output.material_issues_work_order = await work_orders.getMaterial_issues_work_order({
transaction
});
output.production_lots_work_order = await work_orders.getProduction_lots_work_order({
transaction
});
output.qa_inspections_work_order = await work_orders.getQa_inspections_work_order({
transaction
});
output.nonconformances_work_order = await work_orders.getNonconformances_work_order({
transaction
});
output.plant = await work_orders.getPlant({
transaction
});
output.item = await work_orders.getItem({
transaction
});
output.bom = await work_orders.getBom({
transaction
});
output.customer = await work_orders.getCustomer({
transaction
});
output.organizations = await work_orders.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.plants,
as: 'plant',
where: filter.plant ? {
[Op.or]: [
{ id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.boms,
as: 'bom',
where: filter.bom ? {
[Op.or]: [
{ id: { [Op.in]: filter.bom.split('|').map(term => Utils.uuid(term)) } },
{
revision: {
[Op.or]: filter.bom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customers,
as: 'customer',
where: filter.customer ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.work_order_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_orders',
'work_order_number',
filter.work_order_number,
),
};
}
if (filter.uom) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_orders',
'uom',
filter.uom,
),
};
}
if (filter.customer_po) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_orders',
'customer_po',
filter.customer_po,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_orders',
'notes',
filter.notes,
),
};
}
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_completedRange) {
const [start, end] = filter.quantity_completedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_completed: {
...where.quantity_completed,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_completed: {
...where.quantity_completed,
[Op.lte]: end,
},
};
}
}
if (filter.scheduled_start_atRange) {
const [start, end] = filter.scheduled_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_start_at: {
...where.scheduled_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_start_at: {
...where.scheduled_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.scheduled_end_atRange) {
const [start, end] = filter.scheduled_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_end_at: {
...where.scheduled_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_end_at: {
...where.scheduled_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.actual_start_atRange) {
const [start, end] = filter.actual_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
actual_start_at: {
...where.actual_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
actual_start_at: {
...where.actual_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.actual_end_atRange) {
const [start, end] = filter.actual_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
actual_end_at: {
...where.actual_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
actual_end_at: {
...where.actual_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.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.work_orders.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'work_orders',
'work_order_number',
query,
),
],
};
}
const records = await db.work_orders.findAll({
attributes: [ 'id', 'work_order_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['work_order_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.work_order_number,
}));
}
};

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_manufacturing_erp',
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,273 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_events = sequelize.define(
'audit_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
entity_type: {
type: DataTypes.ENUM,
values: [
"company",
"plant",
"user",
"supplier",
"customer",
"item",
"bom",
"bom_line",
"warehouse",
"location",
"lot",
"inventory_balance",
"inventory_transaction",
"machine",
"machine_downtime_event",
"work_order",
"production_operation",
"material_issue",
"production_lot",
"qa_inspection_plan",
"qa_characteristic",
"qa_inspection",
"qa_result",
"nonconformance",
"capa",
"document"
],
},
entity_reference: {
type: DataTypes.TEXT,
},
action: {
type: DataTypes.ENUM,
values: [
"create",
"update",
"delete",
"login",
"export",
"approve",
"release",
"void",
"close"
],
},
event_at: {
type: DataTypes.DATE,
},
details: {
type: DataTypes.TEXT,
},
ip_address: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
audit_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.audit_events.belongsTo(db.companies, {
as: 'company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.audit_events.belongsTo(db.plants, {
as: 'plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.audit_events.belongsTo(db.users, {
as: 'actor_user',
foreignKey: {
name: 'actor_userId',
},
constraints: false,
});
db.audit_events.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.audit_events.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_events;
};

View File

@ -0,0 +1,163 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const bom_lines = sequelize.define(
'bom_lines',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
quantity_per: {
type: DataTypes.DECIMAL,
},
uom: {
type: DataTypes.TEXT,
},
scrap_factor: {
type: DataTypes.DECIMAL,
},
issue_method: {
type: DataTypes.ENUM,
values: [
"manual",
"backflush"
],
},
line_number: {
type: DataTypes.INTEGER,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
bom_lines.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.bom_lines.belongsTo(db.boms, {
as: 'bom',
foreignKey: {
name: 'bomId',
},
constraints: false,
});
db.bom_lines.belongsTo(db.items, {
as: 'component_item',
foreignKey: {
name: 'component_itemId',
},
constraints: false,
});
db.bom_lines.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.bom_lines.belongsTo(db.users, {
as: 'createdBy',
});
db.bom_lines.belongsTo(db.users, {
as: 'updatedBy',
});
};
return bom_lines;
};

View File

@ -0,0 +1,175 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const boms = sequelize.define(
'boms',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
revision: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"active",
"obsolete"
],
},
effective_from: {
type: DataTypes.DATE,
},
effective_to: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
boms.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.boms.hasMany(db.bom_lines, {
as: 'bom_lines_bom',
foreignKey: {
name: 'bomId',
},
constraints: false,
});
db.boms.hasMany(db.work_orders, {
as: 'work_orders_bom',
foreignKey: {
name: 'bomId',
},
constraints: false,
});
//end loop
db.boms.belongsTo(db.companies, {
as: 'company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.boms.belongsTo(db.items, {
as: 'parent_item',
foreignKey: {
name: 'parent_itemId',
},
constraints: false,
});
db.boms.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.boms.belongsTo(db.users, {
as: 'createdBy',
});
db.boms.belongsTo(db.users, {
as: 'updatedBy',
});
};
return boms;
};

View File

@ -0,0 +1,210 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const capas = sequelize.define(
'capas',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
capa_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"root_cause",
"action_planning",
"implementing",
"verifying",
"closed",
"cancelled"
],
},
problem_statement: {
type: DataTypes.TEXT,
},
root_cause: {
type: DataTypes.TEXT,
},
corrective_action: {
type: DataTypes.TEXT,
},
preventive_action: {
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,
},
);
capas.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.capas.belongsTo(db.plants, {
as: 'plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.capas.belongsTo(db.nonconformances, {
as: 'nonconformance',
foreignKey: {
name: 'nonconformanceId',
},
constraints: false,
});
db.capas.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.capas.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.capas.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.capas.getTableName(),
belongsToColumn: 'attachments',
},
});
db.capas.belongsTo(db.users, {
as: 'createdBy',
});
db.capas.belongsTo(db.users, {
as: 'updatedBy',
});
};
return capas;
};

View File

@ -0,0 +1,262 @@
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 companies = sequelize.define(
'companies',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
legal_name: {
type: DataTypes.TEXT,
},
tax_number: {
type: DataTypes.TEXT,
},
website: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
address_line2: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state_region: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
timezone: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
companies.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.companies.hasMany(db.plants, {
as: 'plants_company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.companies.hasMany(db.suppliers, {
as: 'suppliers_company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.companies.hasMany(db.customers, {
as: 'customers_company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.companies.hasMany(db.items, {
as: 'items_company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.companies.hasMany(db.boms, {
as: 'boms_company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.companies.hasMany(db.lots, {
as: 'lots_company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.companies.hasMany(db.qa_inspection_plans, {
as: 'qa_inspection_plans_company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.companies.hasMany(db.documents, {
as: 'documents_company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.companies.hasMany(db.audit_events, {
as: 'audit_events_company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
//end loop
db.companies.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.companies.belongsTo(db.users, {
as: 'createdBy',
});
db.companies.belongsTo(db.users, {
as: 'updatedBy',
});
};
return companies;
};

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 customers = sequelize.define(
'customers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
contact_name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
address_line2: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state_region: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"on_hold",
"inactive"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
customers.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.customers.hasMany(db.work_orders, {
as: 'work_orders_customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
//end loop
db.customers.belongsTo(db.companies, {
as: 'company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.customers.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.customers.belongsTo(db.users, {
as: 'createdBy',
});
db.customers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return customers;
};

View File

@ -0,0 +1,217 @@
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,
},
document_type: {
type: DataTypes.ENUM,
values: [
"sop",
"work_instruction",
"specification",
"form",
"policy",
"certificate",
"other"
],
},
revision: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"in_review",
"approved",
"obsolete"
],
},
effective_at: {
type: DataTypes.DATE,
},
review_due_at: {
type: DataTypes.DATE,
},
summary: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
documents.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.documents.belongsTo(db.companies, {
as: 'company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.documents.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.documents.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.documents.hasMany(db.file, {
as: 'file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.documents.getTableName(),
belongsToColumn: 'file',
},
});
db.documents.belongsTo(db.users, {
as: 'createdBy',
});
db.documents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return documents;
};

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,163 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const inventory_balances = sequelize.define(
'inventory_balances',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
quantity_on_hand: {
type: DataTypes.DECIMAL,
},
quantity_allocated: {
type: DataTypes.DECIMAL,
},
quantity_available: {
type: DataTypes.DECIMAL,
},
uom: {
type: DataTypes.TEXT,
},
last_counted_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
inventory_balances.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.inventory_balances.belongsTo(db.plants, {
as: 'plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.inventory_balances.belongsTo(db.locations, {
as: 'location',
foreignKey: {
name: 'locationId',
},
constraints: false,
});
db.inventory_balances.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.inventory_balances.belongsTo(db.lots, {
as: 'lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.inventory_balances.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.inventory_balances.belongsTo(db.users, {
as: 'createdBy',
});
db.inventory_balances.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inventory_balances;
};

View File

@ -0,0 +1,207 @@
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 inventory_transactions = sequelize.define(
'inventory_transactions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
transaction_type: {
type: DataTypes.ENUM,
values: [
"receipt",
"issue",
"move",
"adjustment",
"scrap",
"cycle_count"
],
},
quantity: {
type: DataTypes.DECIMAL,
},
uom: {
type: DataTypes.TEXT,
},
transaction_at: {
type: DataTypes.DATE,
},
reference: {
type: DataTypes.TEXT,
},
reason: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
inventory_transactions.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.inventory_transactions.belongsTo(db.plants, {
as: 'plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.inventory_transactions.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.inventory_transactions.belongsTo(db.lots, {
as: 'lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.inventory_transactions.belongsTo(db.locations, {
as: 'from_location',
foreignKey: {
name: 'from_locationId',
},
constraints: false,
});
db.inventory_transactions.belongsTo(db.locations, {
as: 'to_location',
foreignKey: {
name: 'to_locationId',
},
constraints: false,
});
db.inventory_transactions.belongsTo(db.users, {
as: 'performed_by_user',
foreignKey: {
name: 'performed_by_userId',
},
constraints: false,
});
db.inventory_transactions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.inventory_transactions.belongsTo(db.users, {
as: 'createdBy',
});
db.inventory_transactions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inventory_transactions;
};

View File

@ -0,0 +1,314 @@
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 items = sequelize.define(
'items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
sku: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
item_type: {
type: DataTypes.ENUM,
values: [
"raw_material",
"component",
"subassembly",
"finished_good",
"consumable"
],
},
uom: {
type: DataTypes.TEXT,
},
is_lot_tracked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
requires_expiry: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
shelf_life_days: {
type: DataTypes.INTEGER,
},
standard_cost: {
type: DataTypes.DECIMAL,
},
standard_price: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"inactive"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.items.hasMany(db.boms, {
as: 'boms_parent_item',
foreignKey: {
name: 'parent_itemId',
},
constraints: false,
});
db.items.hasMany(db.bom_lines, {
as: 'bom_lines_component_item',
foreignKey: {
name: 'component_itemId',
},
constraints: false,
});
db.items.hasMany(db.lots, {
as: 'lots_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.inventory_balances, {
as: 'inventory_balances_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.inventory_transactions, {
as: 'inventory_transactions_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.work_orders, {
as: 'work_orders_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.material_issues, {
as: 'material_issues_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.qa_inspection_plans, {
as: 'qa_inspection_plans_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.qa_inspections, {
as: 'qa_inspections_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.nonconformances, {
as: 'nonconformances_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
//end loop
db.items.belongsTo(db.companies, {
as: 'company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.items.hasMany(db.file, {
as: 'spec_documents',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.items.getTableName(),
belongsToColumn: 'spec_documents',
},
});
db.items.hasMany(db.file, {
as: 'images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.items.getTableName(),
belongsToColumn: 'images',
},
});
db.items.belongsTo(db.users, {
as: 'createdBy',
});
db.items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return items;
};

View File

@ -0,0 +1,185 @@
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 locations = sequelize.define(
'locations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
location_type: {
type: DataTypes.ENUM,
values: [
"rack",
"bin",
"floor",
"staging",
"quarantine"
],
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
locations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.locations.hasMany(db.inventory_balances, {
as: 'inventory_balances_location',
foreignKey: {
name: 'locationId',
},
constraints: false,
});
db.locations.hasMany(db.inventory_transactions, {
as: 'inventory_transactions_from_location',
foreignKey: {
name: 'from_locationId',
},
constraints: false,
});
db.locations.hasMany(db.inventory_transactions, {
as: 'inventory_transactions_to_location',
foreignKey: {
name: 'to_locationId',
},
constraints: false,
});
db.locations.hasMany(db.material_issues, {
as: 'material_issues_from_location',
foreignKey: {
name: 'from_locationId',
},
constraints: false,
});
//end loop
db.locations.belongsTo(db.warehouses, {
as: 'warehouse',
foreignKey: {
name: 'warehouseId',
},
constraints: false,
});
db.locations.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.locations.belongsTo(db.users, {
as: 'createdBy',
});
db.locations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return locations;
};

View File

@ -0,0 +1,266 @@
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 lots = sequelize.define(
'lots',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
lot_number: {
type: DataTypes.TEXT,
},
supplier_lot_number: {
type: DataTypes.TEXT,
},
received_at: {
type: DataTypes.DATE,
},
manufactured_at: {
type: DataTypes.DATE,
},
expiry_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"available",
"quarantine",
"released",
"consumed",
"scrapped"
],
},
quantity_received: {
type: DataTypes.DECIMAL,
},
quantity_available: {
type: DataTypes.DECIMAL,
},
uom: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
lots.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.lots.hasMany(db.inventory_balances, {
as: 'inventory_balances_lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.lots.hasMany(db.inventory_transactions, {
as: 'inventory_transactions_lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.lots.hasMany(db.material_issues, {
as: 'material_issues_lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.lots.hasMany(db.production_lots, {
as: 'production_lots_lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.lots.hasMany(db.qa_inspections, {
as: 'qa_inspections_lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.lots.hasMany(db.nonconformances, {
as: 'nonconformances_lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
//end loop
db.lots.belongsTo(db.companies, {
as: 'company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.lots.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.lots.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.lots.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.lots.hasMany(db.file, {
as: 'coa_documents',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.lots.getTableName(),
belongsToColumn: 'coa_documents',
},
});
db.lots.belongsTo(db.users, {
as: 'createdBy',
});
db.lots.belongsTo(db.users, {
as: 'updatedBy',
});
};
return lots;
};

View File

@ -0,0 +1,190 @@
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 machine_downtime_events = sequelize.define(
'machine_downtime_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
downtime_type: {
type: DataTypes.ENUM,
values: [
"planned",
"unplanned"
],
},
reason_category: {
type: DataTypes.ENUM,
values: [
"mechanical",
"electrical",
"software",
"changeover",
"material_shortage",
"quality_hold",
"operator_unavailable",
"other"
],
},
reason_detail: {
type: DataTypes.TEXT,
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
duration_minutes: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
machine_downtime_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.machine_downtime_events.belongsTo(db.machines, {
as: 'machine',
foreignKey: {
name: 'machineId',
},
constraints: false,
});
db.machine_downtime_events.belongsTo(db.users, {
as: 'reported_by_user',
foreignKey: {
name: 'reported_by_userId',
},
constraints: false,
});
db.machine_downtime_events.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.machine_downtime_events.belongsTo(db.users, {
as: 'createdBy',
});
db.machine_downtime_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return machine_downtime_events;
};

View File

@ -0,0 +1,220 @@
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 machines = sequelize.define(
'machines',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
asset_tag: {
type: DataTypes.TEXT,
},
serial_number: {
type: DataTypes.TEXT,
},
manufacturer: {
type: DataTypes.TEXT,
},
model: {
type: DataTypes.TEXT,
},
commissioned_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"running",
"idle",
"down",
"maintenance",
"offline"
],
},
criticality: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high"
],
},
location_description: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
machines.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.machines.hasMany(db.machine_downtime_events, {
as: 'machine_downtime_events_machine',
foreignKey: {
name: 'machineId',
},
constraints: false,
});
db.machines.hasMany(db.production_operations, {
as: 'production_operations_machine',
foreignKey: {
name: 'machineId',
},
constraints: false,
});
//end loop
db.machines.belongsTo(db.plants, {
as: 'plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.machines.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.machines.belongsTo(db.users, {
as: 'createdBy',
});
db.machines.belongsTo(db.users, {
as: 'updatedBy',
});
};
return machines;
};

View File

@ -0,0 +1,180 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const material_issues = sequelize.define(
'material_issues',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
quantity_issued: {
type: DataTypes.DECIMAL,
},
uom: {
type: DataTypes.TEXT,
},
issued_at: {
type: DataTypes.DATE,
},
issue_method: {
type: DataTypes.ENUM,
values: [
"manual",
"backflush"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
material_issues.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.material_issues.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.material_issues.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.material_issues.belongsTo(db.lots, {
as: 'lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.material_issues.belongsTo(db.locations, {
as: 'from_location',
foreignKey: {
name: 'from_locationId',
},
constraints: false,
});
db.material_issues.belongsTo(db.users, {
as: 'issued_by_user',
foreignKey: {
name: 'issued_by_userId',
},
constraints: false,
});
db.material_issues.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.material_issues.belongsTo(db.users, {
as: 'createdBy',
});
db.material_issues.belongsTo(db.users, {
as: 'updatedBy',
});
};
return material_issues;
};

View File

@ -0,0 +1,287 @@
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,
},
ncr_number: {
type: DataTypes.TEXT,
},
source: {
type: DataTypes.ENUM,
values: [
"incoming",
"in_process",
"final",
"customer",
"audit"
],
},
severity: {
type: DataTypes.ENUM,
values: [
"minor",
"major",
"critical"
],
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"under_investigation",
"containment",
"capa_required",
"closed",
"void"
],
},
description: {
type: DataTypes.TEXT,
},
containment_action: {
type: DataTypes.TEXT,
},
disposition: {
type: DataTypes.ENUM,
values: [
"use_as_is",
"rework",
"scrap",
"return_to_supplier",
"sort"
],
},
reported_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
db.nonconformances.hasMany(db.capas, {
as: 'capas_nonconformance',
foreignKey: {
name: 'nonconformanceId',
},
constraints: false,
});
//end loop
db.nonconformances.belongsTo(db.plants, {
as: 'plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.qa_inspections, {
as: 'inspection',
foreignKey: {
name: 'inspectionId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.lots, {
as: 'lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.users, {
as: 'reported_by_user',
foreignKey: {
name: 'reported_by_userId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.nonconformances.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.nonconformances.getTableName(),
belongsToColumn: 'attachments',
},
});
db.nonconformances.belongsTo(db.users, {
as: 'createdBy',
});
db.nonconformances.belongsTo(db.users, {
as: 'updatedBy',
});
};
return nonconformances;
};

View File

@ -0,0 +1,311 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const organizations = sequelize.define(
'organizations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
organizations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.organizations.hasMany(db.users, {
as: 'users_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.companies, {
as: 'companies_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.plants, {
as: 'plants_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.suppliers, {
as: 'suppliers_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.customers, {
as: 'customers_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.items, {
as: 'items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.boms, {
as: 'boms_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.bom_lines, {
as: 'bom_lines_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.warehouses, {
as: 'warehouses_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.locations, {
as: 'locations_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.lots, {
as: 'lots_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.inventory_balances, {
as: 'inventory_balances_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.inventory_transactions, {
as: 'inventory_transactions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.machines, {
as: 'machines_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.machine_downtime_events, {
as: 'machine_downtime_events_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.work_orders, {
as: 'work_orders_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.production_operations, {
as: 'production_operations_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.material_issues, {
as: 'material_issues_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.production_lots, {
as: 'production_lots_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.qa_inspection_plans, {
as: 'qa_inspection_plans_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.qa_characteristics, {
as: 'qa_characteristics_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.qa_inspections, {
as: 'qa_inspections_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.qa_results, {
as: 'qa_results_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.nonconformances, {
as: 'nonconformances_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.capas, {
as: 'capas_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.documents, {
as: 'documents_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.audit_events, {
as: 'audit_events_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
//end loop
db.organizations.belongsTo(db.users, {
as: 'createdBy',
});
db.organizations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return organizations;
};

View File

@ -0,0 +1,95 @@
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,256 @@
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 plants = sequelize.define(
'plants',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
timezone: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
address_line2: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state_region: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
plants.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.plants.hasMany(db.warehouses, {
as: 'warehouses_plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.plants.hasMany(db.inventory_balances, {
as: 'inventory_balances_plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.plants.hasMany(db.inventory_transactions, {
as: 'inventory_transactions_plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.plants.hasMany(db.machines, {
as: 'machines_plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.plants.hasMany(db.work_orders, {
as: 'work_orders_plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.plants.hasMany(db.qa_inspections, {
as: 'qa_inspections_plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.plants.hasMany(db.nonconformances, {
as: 'nonconformances_plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.plants.hasMany(db.capas, {
as: 'capas_plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.plants.hasMany(db.audit_events, {
as: 'audit_events_plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
//end loop
db.plants.belongsTo(db.companies, {
as: 'company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.plants.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.plants.belongsTo(db.users, {
as: 'createdBy',
});
db.plants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return plants;
};

View File

@ -0,0 +1,162 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const production_lots = sequelize.define(
'production_lots',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
produced_at: {
type: DataTypes.DATE,
},
quantity_produced: {
type: DataTypes.DECIMAL,
},
uom: {
type: DataTypes.TEXT,
},
disposition: {
type: DataTypes.ENUM,
values: [
"wip",
"quarantine",
"released",
"scrapped"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
production_lots.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.production_lots.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.production_lots.belongsTo(db.lots, {
as: 'lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.production_lots.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.production_lots.belongsTo(db.users, {
as: 'createdBy',
});
db.production_lots.belongsTo(db.users, {
as: 'updatedBy',
});
};
return production_lots;
};

View File

@ -0,0 +1,200 @@
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 production_operations = sequelize.define(
'production_operations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
operation_sequence: {
type: DataTypes.INTEGER,
},
name: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"not_started",
"in_progress",
"paused",
"completed",
"blocked"
],
},
planned_start_at: {
type: DataTypes.DATE,
},
planned_end_at: {
type: DataTypes.DATE,
},
actual_start_at: {
type: DataTypes.DATE,
},
actual_end_at: {
type: DataTypes.DATE,
},
labor_minutes: {
type: DataTypes.DECIMAL,
},
machine_minutes: {
type: DataTypes.DECIMAL,
},
instructions: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
production_operations.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.production_operations.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.production_operations.belongsTo(db.machines, {
as: 'machine',
foreignKey: {
name: 'machineId',
},
constraints: false,
});
db.production_operations.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.production_operations.belongsTo(db.users, {
as: 'createdBy',
});
db.production_operations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return production_operations;
};

View File

@ -0,0 +1,186 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const qa_characteristics = sequelize.define(
'qa_characteristics',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
data_type: {
type: DataTypes.ENUM,
values: [
"numeric",
"attribute"
],
},
unit: {
type: DataTypes.TEXT,
},
lower_spec: {
type: DataTypes.DECIMAL,
},
upper_spec: {
type: DataTypes.DECIMAL,
},
result_required: {
type: DataTypes.ENUM,
values: [
"required",
"optional"
],
},
sequence: {
type: DataTypes.INTEGER,
},
method: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
qa_characteristics.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.qa_characteristics.hasMany(db.qa_results, {
as: 'qa_results_characteristic',
foreignKey: {
name: 'characteristicId',
},
constraints: false,
});
//end loop
db.qa_characteristics.belongsTo(db.qa_inspection_plans, {
as: 'inspection_plan',
foreignKey: {
name: 'inspection_planId',
},
constraints: false,
});
db.qa_characteristics.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.qa_characteristics.belongsTo(db.users, {
as: 'createdBy',
});
db.qa_characteristics.belongsTo(db.users, {
as: 'updatedBy',
});
};
return qa_characteristics;
};

View File

@ -0,0 +1,209 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const qa_inspection_plans = sequelize.define(
'qa_inspection_plans',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
inspection_type: {
type: DataTypes.ENUM,
values: [
"incoming",
"in_process",
"final"
],
},
sampling_method: {
type: DataTypes.ENUM,
values: [
"100_percent",
"aql",
"fixed_n",
"c_equals_0"
],
},
sample_size: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"active",
"inactive"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
qa_inspection_plans.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.qa_inspection_plans.hasMany(db.qa_characteristics, {
as: 'qa_characteristics_inspection_plan',
foreignKey: {
name: 'inspection_planId',
},
constraints: false,
});
db.qa_inspection_plans.hasMany(db.qa_inspections, {
as: 'qa_inspections_inspection_plan',
foreignKey: {
name: 'inspection_planId',
},
constraints: false,
});
//end loop
db.qa_inspection_plans.belongsTo(db.companies, {
as: 'company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.qa_inspection_plans.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.qa_inspection_plans.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.qa_inspection_plans.belongsTo(db.users, {
as: 'createdBy',
});
db.qa_inspection_plans.belongsTo(db.users, {
as: 'updatedBy',
});
};
return qa_inspection_plans;
};

View File

@ -0,0 +1,261 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const qa_inspections = sequelize.define(
'qa_inspections',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
inspection_type: {
type: DataTypes.ENUM,
values: [
"incoming",
"in_process",
"final"
],
},
scheduled_at: {
type: DataTypes.DATE,
},
started_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"planned",
"in_progress",
"completed",
"void"
],
},
overall_result: {
type: DataTypes.ENUM,
values: [
"pass",
"fail",
"conditional",
"pending"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
qa_inspections.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.qa_inspections.hasMany(db.qa_results, {
as: 'qa_results_inspection',
foreignKey: {
name: 'inspectionId',
},
constraints: false,
});
db.qa_inspections.hasMany(db.nonconformances, {
as: 'nonconformances_inspection',
foreignKey: {
name: 'inspectionId',
},
constraints: false,
});
//end loop
db.qa_inspections.belongsTo(db.plants, {
as: 'plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.qa_inspections.belongsTo(db.qa_inspection_plans, {
as: 'inspection_plan',
foreignKey: {
name: 'inspection_planId',
},
constraints: false,
});
db.qa_inspections.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.qa_inspections.belongsTo(db.lots, {
as: 'lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.qa_inspections.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.qa_inspections.belongsTo(db.users, {
as: 'inspector_user',
foreignKey: {
name: 'inspector_userId',
},
constraints: false,
});
db.qa_inspections.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.qa_inspections.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.qa_inspections.getTableName(),
belongsToColumn: 'attachments',
},
});
db.qa_inspections.belongsTo(db.users, {
as: 'createdBy',
});
db.qa_inspections.belongsTo(db.users, {
as: 'updatedBy',
});
};
return qa_inspections;
};

View File

@ -0,0 +1,171 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const qa_results = sequelize.define(
'qa_results',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
numeric_value: {
type: DataTypes.DECIMAL,
},
attribute_value: {
type: DataTypes.ENUM,
values: [
"pass",
"fail",
"na"
],
},
result: {
type: DataTypes.ENUM,
values: [
"pass",
"fail",
"na"
],
},
unit: {
type: DataTypes.TEXT,
},
comment: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
qa_results.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.qa_results.belongsTo(db.qa_inspections, {
as: 'inspection',
foreignKey: {
name: 'inspectionId',
},
constraints: false,
});
db.qa_results.belongsTo(db.qa_characteristics, {
as: 'characteristic',
foreignKey: {
name: 'characteristicId',
},
constraints: false,
});
db.qa_results.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.qa_results.belongsTo(db.users, {
as: 'createdBy',
});
db.qa_results.belongsTo(db.users, {
as: 'updatedBy',
});
};
return qa_results;
};

View File

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

View File

@ -0,0 +1,222 @@
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,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
contact_name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
website: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
address_line2: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state_region: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"on_hold",
"inactive"
],
},
notes: {
type: DataTypes.TEXT,
},
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.lots, {
as: 'lots_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
//end loop
db.suppliers.belongsTo(db.companies, {
as: 'company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.suppliers.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.suppliers.belongsTo(db.users, {
as: 'createdBy',
});
db.suppliers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return suppliers;
};

View File

@ -0,0 +1,325 @@
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.inventory_transactions, {
as: 'inventory_transactions_performed_by_user',
foreignKey: {
name: 'performed_by_userId',
},
constraints: false,
});
db.users.hasMany(db.machine_downtime_events, {
as: 'machine_downtime_events_reported_by_user',
foreignKey: {
name: 'reported_by_userId',
},
constraints: false,
});
db.users.hasMany(db.material_issues, {
as: 'material_issues_issued_by_user',
foreignKey: {
name: 'issued_by_userId',
},
constraints: false,
});
db.users.hasMany(db.qa_inspections, {
as: 'qa_inspections_inspector_user',
foreignKey: {
name: 'inspector_userId',
},
constraints: false,
});
db.users.hasMany(db.nonconformances, {
as: 'nonconformances_reported_by_user',
foreignKey: {
name: 'reported_by_userId',
},
constraints: false,
});
db.users.hasMany(db.capas, {
as: 'capas_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.users.hasMany(db.documents, {
as: 'documents_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.users.hasMany(db.audit_events, {
as: 'audit_events_actor_user',
foreignKey: {
name: 'actor_userId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

View File

@ -0,0 +1,161 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const warehouses = sequelize.define(
'warehouses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
warehouse_type: {
type: DataTypes.ENUM,
values: [
"raw",
"wip",
"finished",
"quarantine",
"external"
],
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
warehouses.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.warehouses.hasMany(db.locations, {
as: 'locations_warehouse',
foreignKey: {
name: 'warehouseId',
},
constraints: false,
});
//end loop
db.warehouses.belongsTo(db.plants, {
as: 'plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.warehouses.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.warehouses.belongsTo(db.users, {
as: 'createdBy',
});
db.warehouses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return warehouses;
};

View File

@ -0,0 +1,269 @@
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 work_orders = sequelize.define(
'work_orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
work_order_number: {
type: DataTypes.TEXT,
},
quantity_planned: {
type: DataTypes.DECIMAL,
},
quantity_completed: {
type: DataTypes.DECIMAL,
},
uom: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"planned",
"released",
"in_progress",
"qa_hold",
"completed",
"closed",
"cancelled"
],
},
scheduled_start_at: {
type: DataTypes.DATE,
},
scheduled_end_at: {
type: DataTypes.DATE,
},
actual_start_at: {
type: DataTypes.DATE,
},
actual_end_at: {
type: DataTypes.DATE,
},
customer_po: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
work_orders.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.work_orders.hasMany(db.production_operations, {
as: 'production_operations_work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.work_orders.hasMany(db.material_issues, {
as: 'material_issues_work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.work_orders.hasMany(db.production_lots, {
as: 'production_lots_work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.work_orders.hasMany(db.qa_inspections, {
as: 'qa_inspections_work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.work_orders.hasMany(db.nonconformances, {
as: 'nonconformances_work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
//end loop
db.work_orders.belongsTo(db.plants, {
as: 'plant',
foreignKey: {
name: 'plantId',
},
constraints: false,
});
db.work_orders.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.work_orders.belongsTo(db.boms, {
as: 'bom',
foreignKey: {
name: 'bomId',
},
constraints: false,
});
db.work_orders.belongsTo(db.customers, {
as: 'customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.work_orders.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.work_orders.belongsTo(db.users, {
as: 'createdBy',
});
db.work_orders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return work_orders;
};

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

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

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

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

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

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

@ -0,0 +1,251 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const organizationForAuthRoutes = require('./routes/organizationLogin');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const organizationsRoutes = require('./routes/organizations');
const companiesRoutes = require('./routes/companies');
const plantsRoutes = require('./routes/plants');
const suppliersRoutes = require('./routes/suppliers');
const customersRoutes = require('./routes/customers');
const itemsRoutes = require('./routes/items');
const bomsRoutes = require('./routes/boms');
const bom_linesRoutes = require('./routes/bom_lines');
const warehousesRoutes = require('./routes/warehouses');
const locationsRoutes = require('./routes/locations');
const lotsRoutes = require('./routes/lots');
const inventory_balancesRoutes = require('./routes/inventory_balances');
const inventory_transactionsRoutes = require('./routes/inventory_transactions');
const machinesRoutes = require('./routes/machines');
const machine_downtime_eventsRoutes = require('./routes/machine_downtime_events');
const work_ordersRoutes = require('./routes/work_orders');
const production_operationsRoutes = require('./routes/production_operations');
const material_issuesRoutes = require('./routes/material_issues');
const production_lotsRoutes = require('./routes/production_lots');
const qa_inspection_plansRoutes = require('./routes/qa_inspection_plans');
const qa_characteristicsRoutes = require('./routes/qa_characteristics');
const qa_inspectionsRoutes = require('./routes/qa_inspections');
const qa_resultsRoutes = require('./routes/qa_results');
const nonconformancesRoutes = require('./routes/nonconformances');
const capasRoutes = require('./routes/capas');
const documentsRoutes = require('./routes/documents');
const audit_eventsRoutes = require('./routes/audit_events');
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: "Manufacturing ERP",
description: "Manufacturing ERP 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/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);
app.use('/api/companies', passport.authenticate('jwt', {session: false}), companiesRoutes);
app.use('/api/plants', passport.authenticate('jwt', {session: false}), plantsRoutes);
app.use('/api/suppliers', passport.authenticate('jwt', {session: false}), suppliersRoutes);
app.use('/api/customers', passport.authenticate('jwt', {session: false}), customersRoutes);
app.use('/api/items', passport.authenticate('jwt', {session: false}), itemsRoutes);
app.use('/api/boms', passport.authenticate('jwt', {session: false}), bomsRoutes);
app.use('/api/bom_lines', passport.authenticate('jwt', {session: false}), bom_linesRoutes);
app.use('/api/warehouses', passport.authenticate('jwt', {session: false}), warehousesRoutes);
app.use('/api/locations', passport.authenticate('jwt', {session: false}), locationsRoutes);
app.use('/api/lots', passport.authenticate('jwt', {session: false}), lotsRoutes);
app.use('/api/inventory_balances', passport.authenticate('jwt', {session: false}), inventory_balancesRoutes);
app.use('/api/inventory_transactions', passport.authenticate('jwt', {session: false}), inventory_transactionsRoutes);
app.use('/api/machines', passport.authenticate('jwt', {session: false}), machinesRoutes);
app.use('/api/machine_downtime_events', passport.authenticate('jwt', {session: false}), machine_downtime_eventsRoutes);
app.use('/api/work_orders', passport.authenticate('jwt', {session: false}), work_ordersRoutes);
app.use('/api/production_operations', passport.authenticate('jwt', {session: false}), production_operationsRoutes);
app.use('/api/material_issues', passport.authenticate('jwt', {session: false}), material_issuesRoutes);
app.use('/api/production_lots', passport.authenticate('jwt', {session: false}), production_lotsRoutes);
app.use('/api/qa_inspection_plans', passport.authenticate('jwt', {session: false}), qa_inspection_plansRoutes);
app.use('/api/qa_characteristics', passport.authenticate('jwt', {session: false}), qa_characteristicsRoutes);
app.use('/api/qa_inspections', passport.authenticate('jwt', {session: false}), qa_inspectionsRoutes);
app.use('/api/qa_results', passport.authenticate('jwt', {session: false}), qa_resultsRoutes);
app.use('/api/nonconformances', passport.authenticate('jwt', {session: false}), nonconformancesRoutes);
app.use('/api/capas', passport.authenticate('jwt', {session: false}), capasRoutes);
app.use('/api/documents', passport.authenticate('jwt', {session: false}), documentsRoutes);
app.use('/api/audit_events', passport.authenticate('jwt', {session: false}), audit_eventsRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
app.use(
'/api/org-for-auth',
organizationForAuthRoutes,
);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
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,448 @@
const express = require('express');
const Audit_eventsService = require('../services/audit_events');
const Audit_eventsDBApi = require('../db/api/audit_events');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('audit_events'));
/**
* @swagger
* components:
* schemas:
* Audit_events:
* type: object
* properties:
* entity_reference:
* type: string
* default: entity_reference
* details:
* type: string
* default: details
* ip_address:
* type: string
* default: ip_address
*
*
*/
/**
* @swagger
* tags:
* name: Audit_events
* description: The Audit_events managing API
*/
/**
* @swagger
* /api/audit_events:
* post:
* security:
* - bearerAuth: []
* tags: [Audit_events]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Audit_events"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_events"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Audit_eventsService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Audit_events]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Audit_events"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_events"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Audit_eventsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_events/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Audit_events]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Audit_events"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_events"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await Audit_eventsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_events/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Audit_events]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_events"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await Audit_eventsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_events/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Audit_events]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_events"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Audit_eventsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_events:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_events]
* summary: Get all audit_events
* description: Get all audit_events
* responses:
* 200:
* description: Audit_events list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Audit_events"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Audit_eventsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','entity_reference','details','ip_address',
'event_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/audit_events/count:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_events]
* summary: Count all audit_events
* description: Count all audit_events
* responses:
* 200:
* description: Audit_events count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Audit_events"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await Audit_eventsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_events/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_events]
* summary: Find all audit_events that match search criteria
* description: Find all audit_events that match search criteria
* responses:
* 200:
* description: Audit_events list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Audit_events"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await Audit_eventsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/audit_events/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_events]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_events"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await Audit_eventsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

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

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

View File

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

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

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

453
backend/src/routes/capas.js Normal file
View File

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