Initial version

This commit is contained in:
Flatlogic Bot 2026-04-29 12:21:13 +00:00
commit e2bc8a08d4
736 changed files with 250491 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>Manufacturing ERP for work orders, materials, machine tracking, QA inspections, and inventory 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`

1
backend/.env Normal file
View File

@ -0,0 +1 @@
PORT=8080

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});
});
}

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

@ -0,0 +1,79 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "9ecddabc",
user_pass: "2432647e3d09",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '9ecddabc-b1fa-4ac0-9544-2432647e3d09',
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: {
admin: 'Administrator',
user: 'Warehouse Operator',
},
project_uuid: '9ecddabc-b1fa-4ac0-9544-2432647e3d09',
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 = 'Steel gears in soft light';
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,552 @@
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 Approved_vendorsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approved_vendors = await db.approved_vendors.create(
{
id: data.id || undefined,
supplier_item_code: data.supplier_item_code
||
null
,
lead_time_days: data.lead_time_days
||
null
,
last_price: data.last_price
||
null
,
preferred: data.preferred
||
false
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await approved_vendors.setItem( data.item || null, {
transaction,
});
await approved_vendors.setSupplier( data.supplier || null, {
transaction,
});
return approved_vendors;
}
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 approved_vendorsData = data.map((item, index) => ({
id: item.id || undefined,
supplier_item_code: item.supplier_item_code
||
null
,
lead_time_days: item.lead_time_days
||
null
,
last_price: item.last_price
||
null
,
preferred: item.preferred
||
false
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const approved_vendors = await db.approved_vendors.bulkCreate(approved_vendorsData, { transaction });
// For each item created, replace relation files
return approved_vendors;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const approved_vendors = await db.approved_vendors.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.supplier_item_code !== undefined) updatePayload.supplier_item_code = data.supplier_item_code;
if (data.lead_time_days !== undefined) updatePayload.lead_time_days = data.lead_time_days;
if (data.last_price !== undefined) updatePayload.last_price = data.last_price;
if (data.preferred !== undefined) updatePayload.preferred = data.preferred;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await approved_vendors.update(updatePayload, {transaction});
if (data.item !== undefined) {
await approved_vendors.setItem(
data.item,
{ transaction }
);
}
if (data.supplier !== undefined) {
await approved_vendors.setSupplier(
data.supplier,
{ transaction }
);
}
return approved_vendors;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approved_vendors = await db.approved_vendors.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of approved_vendors) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of approved_vendors) {
await record.destroy({transaction});
}
});
return approved_vendors;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const approved_vendors = await db.approved_vendors.findByPk(id, options);
await approved_vendors.update({
deletedBy: currentUser.id
}, {
transaction,
});
await approved_vendors.destroy({
transaction
});
return approved_vendors;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const approved_vendors = await db.approved_vendors.findOne(
{ where },
{ transaction },
);
if (!approved_vendors) {
return approved_vendors;
}
const output = approved_vendors.get({plain: true});
output.item = await approved_vendors.getItem({
transaction
});
output.supplier = await approved_vendors.getSupplier({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
item_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)) } },
{
supplier_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.supplier_item_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'approved_vendors',
'supplier_item_code',
filter.supplier_item_code,
),
};
}
if (filter.lead_time_daysRange) {
const [start, end] = filter.lead_time_daysRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lead_time_days: {
...where.lead_time_days,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lead_time_days: {
...where.lead_time_days,
[Op.lte]: end,
},
};
}
}
if (filter.last_priceRange) {
const [start, end] = filter.last_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_price: {
...where.last_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_price: {
...where.last_price,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.preferred) {
where = {
...where,
preferred: filter.preferred,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.approved_vendors.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(
'approved_vendors',
'supplier_item_code',
query,
),
],
};
}
const records = await db.approved_vendors.findAll({
attributes: [ 'id', 'supplier_item_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['supplier_item_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.supplier_item_code,
}));
}
};

View File

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

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

@ -0,0 +1,547 @@
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,
bom_name: data.bom_name
||
null
,
bom_code: data.bom_code
||
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.setParent_item( data.parent_item || 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,
bom_name: item.bom_name
||
null
,
bom_code: item.bom_code
||
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 boms = await db.boms.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.bom_name !== undefined) updatePayload.bom_name = data.bom_name;
if (data.bom_code !== undefined) updatePayload.bom_code = data.bom_code;
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.parent_item !== undefined) {
await boms.setParent_item(
data.parent_item,
{ 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.parent_item = await boms.getParent_item({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.items,
as: 'parent_item',
where: filter.parent_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.parent_item.split('|').map(term => Utils.uuid(term)) } },
{
item_name: {
[Op.or]: filter.parent_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.bom_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'boms',
'bom_name',
filter.bom_name,
),
};
}
if (filter.bom_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'boms',
'bom_code',
filter.bom_code,
),
};
}
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.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.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'boms',
'bom_name',
query,
),
],
};
}
const records = await db.boms.findAll({
attributes: [ 'id', 'bom_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['bom_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.bom_name,
}));
}
};

View File

@ -0,0 +1,662 @@
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 Capa_actionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const capa_actions = await db.capa_actions.create(
{
id: data.id || undefined,
capa_number: data.capa_number
||
null
,
action_type: data.action_type
||
null
,
status: data.status
||
null
,
due_at: data.due_at
||
null
,
closed_at: data.closed_at
||
null
,
root_cause: data.root_cause
||
null
,
action_plan: data.action_plan
||
null
,
effectiveness_check: data.effectiveness_check
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await capa_actions.setNonconformance( data.nonconformance || null, {
transaction,
});
await capa_actions.setOwner( data.owner || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.capa_actions.getTableName(),
belongsToColumn: 'attachments',
belongsToId: capa_actions.id,
},
data.attachments,
options,
);
return capa_actions;
}
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 capa_actionsData = data.map((item, index) => ({
id: item.id || undefined,
capa_number: item.capa_number
||
null
,
action_type: item.action_type
||
null
,
status: item.status
||
null
,
due_at: item.due_at
||
null
,
closed_at: item.closed_at
||
null
,
root_cause: item.root_cause
||
null
,
action_plan: item.action_plan
||
null
,
effectiveness_check: item.effectiveness_check
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const capa_actions = await db.capa_actions.bulkCreate(capa_actionsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < capa_actions.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.capa_actions.getTableName(),
belongsToColumn: 'attachments',
belongsToId: capa_actions[i].id,
},
data[i].attachments,
options,
);
}
return capa_actions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const capa_actions = await db.capa_actions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.capa_number !== undefined) updatePayload.capa_number = data.capa_number;
if (data.action_type !== undefined) updatePayload.action_type = data.action_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
if (data.root_cause !== undefined) updatePayload.root_cause = data.root_cause;
if (data.action_plan !== undefined) updatePayload.action_plan = data.action_plan;
if (data.effectiveness_check !== undefined) updatePayload.effectiveness_check = data.effectiveness_check;
updatePayload.updatedById = currentUser.id;
await capa_actions.update(updatePayload, {transaction});
if (data.nonconformance !== undefined) {
await capa_actions.setNonconformance(
data.nonconformance,
{ transaction }
);
}
if (data.owner !== undefined) {
await capa_actions.setOwner(
data.owner,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.capa_actions.getTableName(),
belongsToColumn: 'attachments',
belongsToId: capa_actions.id,
},
data.attachments,
options,
);
return capa_actions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const capa_actions = await db.capa_actions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of capa_actions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of capa_actions) {
await record.destroy({transaction});
}
});
return capa_actions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const capa_actions = await db.capa_actions.findByPk(id, options);
await capa_actions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await capa_actions.destroy({
transaction
});
return capa_actions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const capa_actions = await db.capa_actions.findOne(
{ where },
{ transaction },
);
if (!capa_actions) {
return capa_actions;
}
const output = capa_actions.get({plain: true});
output.nonconformance = await capa_actions.getNonconformance({
transaction
});
output.owner = await capa_actions.getOwner({
transaction
});
output.attachments = await capa_actions.getAttachments({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.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',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.capa_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'capa_actions',
'capa_number',
filter.capa_number,
),
};
}
if (filter.root_cause) {
where = {
...where,
[Op.and]: Utils.ilike(
'capa_actions',
'root_cause',
filter.root_cause,
),
};
}
if (filter.action_plan) {
where = {
...where,
[Op.and]: Utils.ilike(
'capa_actions',
'action_plan',
filter.action_plan,
),
};
}
if (filter.effectiveness_check) {
where = {
...where,
[Op.and]: Utils.ilike(
'capa_actions',
'effectiveness_check',
filter.effectiveness_check,
),
};
}
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.action_type) {
where = {
...where,
action_type: filter.action_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.capa_actions.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(
'capa_actions',
'capa_number',
query,
),
],
};
}
const records = await db.capa_actions.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,486 @@
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,
customer_name: data.customer_name
||
null
,
customer_code: data.customer_code
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
address: data.address
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ 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,
customer_name: item.customer_name
||
null
,
customer_code: item.customer_code
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
address: item.address
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const 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 customers = await db.customers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.customer_name !== undefined) updatePayload.customer_name = data.customer_name;
if (data.customer_code !== undefined) updatePayload.customer_code = data.customer_code;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await customers.update(updatePayload, {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.inventory_movements_customer = await customers.getInventory_movements_customer({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.customer_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'customer_name',
filter.customer_name,
),
};
}
if (filter.customer_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'customer_code',
filter.customer_code,
),
};
}
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) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'address',
filter.address,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'customers',
'customer_name',
query,
),
],
};
}
const records = await db.customers.findAll({
attributes: [ 'id', 'customer_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['customer_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.customer_name,
}));
}
};

View File

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

View File

@ -0,0 +1,87 @@
const db = require('../models');
const assert = require('assert');
const services = require('../../services/file');
module.exports = class FileDBApi {
static async replaceRelationFiles(
relation,
rawFiles,
options,
) {
assert(relation.belongsTo, 'belongsTo is required');
assert(
relation.belongsToColumn,
'belongsToColumn is required',
);
assert(relation.belongsToId, 'belongsToId is required');
let files = [];
if (Array.isArray(rawFiles)) {
files = rawFiles;
} else {
files = rawFiles ? [rawFiles] : [];
}
await this._removeLegacyFiles(relation, files, options);
await this._addFiles(relation, files, options);
}
static async _addFiles(relation, files, options) {
const transaction = (options && options.transaction) || undefined;
const currentUser = (options && options.currentUser) || {id: null};
const inexistentFiles = files.filter(
(file) => !!file.new,
);
for (const file of inexistentFiles) {
await db.file.create(
{
belongsTo: relation.belongsTo,
belongsToColumn: relation.belongsToColumn,
belongsToId: relation.belongsToId,
name: file.name,
sizeInBytes: file.sizeInBytes,
privateUrl: file.privateUrl,
publicUrl: file.publicUrl,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{
transaction,
},
);
}
}
static async _removeLegacyFiles(
relation,
files,
options,
) {
const transaction = (options && options.transaction) || undefined;
const filesToDelete = await db.file.findAll({
where: {
belongsTo: relation.belongsTo,
belongsToId: relation.belongsToId,
belongsToColumn: relation.belongsToColumn,
id: {
[db.Sequelize.Op
.notIn]: files
.filter((file) => !file.new)
.map((file) => file.id)
},
},
transaction,
});
for (let file of filesToDelete) {
await services.deleteGCloud(file.privateUrl);
await file.destroy({
transaction,
});
}
}
};

View File

@ -0,0 +1,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 Inspection_characteristicsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inspection_characteristics = await db.inspection_characteristics.create(
{
id: data.id || undefined,
sequence_no: data.sequence_no
||
null
,
characteristic_name: data.characteristic_name
||
null
,
data_type: data.data_type
||
null
,
target_value: data.target_value
||
null
,
lower_limit: data.lower_limit
||
null
,
upper_limit: data.upper_limit
||
null
,
unit: data.unit
||
null
,
critical: data.critical
||
false
,
method: data.method
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inspection_characteristics.setInspection_plan( data.inspection_plan || null, {
transaction,
});
return inspection_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 inspection_characteristicsData = data.map((item, index) => ({
id: item.id || undefined,
sequence_no: item.sequence_no
||
null
,
characteristic_name: item.characteristic_name
||
null
,
data_type: item.data_type
||
null
,
target_value: item.target_value
||
null
,
lower_limit: item.lower_limit
||
null
,
upper_limit: item.upper_limit
||
null
,
unit: item.unit
||
null
,
critical: item.critical
||
false
,
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 inspection_characteristics = await db.inspection_characteristics.bulkCreate(inspection_characteristicsData, { transaction });
// For each item created, replace relation files
return inspection_characteristics;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inspection_characteristics = await db.inspection_characteristics.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.sequence_no !== undefined) updatePayload.sequence_no = data.sequence_no;
if (data.characteristic_name !== undefined) updatePayload.characteristic_name = data.characteristic_name;
if (data.data_type !== undefined) updatePayload.data_type = data.data_type;
if (data.target_value !== undefined) updatePayload.target_value = data.target_value;
if (data.lower_limit !== undefined) updatePayload.lower_limit = data.lower_limit;
if (data.upper_limit !== undefined) updatePayload.upper_limit = data.upper_limit;
if (data.unit !== undefined) updatePayload.unit = data.unit;
if (data.critical !== undefined) updatePayload.critical = data.critical;
if (data.method !== undefined) updatePayload.method = data.method;
updatePayload.updatedById = currentUser.id;
await inspection_characteristics.update(updatePayload, {transaction});
if (data.inspection_plan !== undefined) {
await inspection_characteristics.setInspection_plan(
data.inspection_plan,
{ transaction }
);
}
return inspection_characteristics;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inspection_characteristics = await db.inspection_characteristics.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inspection_characteristics) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inspection_characteristics) {
await record.destroy({transaction});
}
});
return inspection_characteristics;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inspection_characteristics = await db.inspection_characteristics.findByPk(id, options);
await inspection_characteristics.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inspection_characteristics.destroy({
transaction
});
return inspection_characteristics;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inspection_characteristics = await db.inspection_characteristics.findOne(
{ where },
{ transaction },
);
if (!inspection_characteristics) {
return inspection_characteristics;
}
const output = inspection_characteristics.get({plain: true});
output.inspection_results_characteristic = await inspection_characteristics.getInspection_results_characteristic({
transaction
});
output.inspection_plan = await inspection_characteristics.getInspection_plan({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.inspection_plans,
as: 'inspection_plan',
where: filter.inspection_plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.inspection_plan.split('|').map(term => Utils.uuid(term)) } },
{
plan_name: {
[Op.or]: filter.inspection_plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.characteristic_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'inspection_characteristics',
'characteristic_name',
filter.characteristic_name,
),
};
}
if (filter.unit) {
where = {
...where,
[Op.and]: Utils.ilike(
'inspection_characteristics',
'unit',
filter.unit,
),
};
}
if (filter.method) {
where = {
...where,
[Op.and]: Utils.ilike(
'inspection_characteristics',
'method',
filter.method,
),
};
}
if (filter.sequence_noRange) {
const [start, end] = filter.sequence_noRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sequence_no: {
...where.sequence_no,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sequence_no: {
...where.sequence_no,
[Op.lte]: end,
},
};
}
}
if (filter.target_valueRange) {
const [start, end] = filter.target_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.lte]: end,
},
};
}
}
if (filter.lower_limitRange) {
const [start, end] = filter.lower_limitRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lower_limit: {
...where.lower_limit,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lower_limit: {
...where.lower_limit,
[Op.lte]: end,
},
};
}
}
if (filter.upper_limitRange) {
const [start, end] = filter.upper_limitRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
upper_limit: {
...where.upper_limit,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
upper_limit: {
...where.upper_limit,
[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.critical) {
where = {
...where,
critical: filter.critical,
};
}
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.inspection_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'inspection_characteristics',
'characteristic_name',
query,
),
],
};
}
const records = await db.inspection_characteristics.findAll({
attributes: [ 'id', 'characteristic_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['characteristic_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.characteristic_name,
}));
}
};

View File

@ -0,0 +1,493 @@
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 Inspection_plansDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inspection_plans = await db.inspection_plans.create(
{
id: data.id || undefined,
plan_name: data.plan_name
||
null
,
plan_code: data.plan_code
||
null
,
plan_type: data.plan_type
||
null
,
status: data.status
||
null
,
instructions: data.instructions
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inspection_plans.setItem( data.item || null, {
transaction,
});
return 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 inspection_plansData = data.map((item, index) => ({
id: item.id || undefined,
plan_name: item.plan_name
||
null
,
plan_code: item.plan_code
||
null
,
plan_type: item.plan_type
||
null
,
status: item.status
||
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 inspection_plans = await db.inspection_plans.bulkCreate(inspection_plansData, { transaction });
// For each item created, replace relation files
return inspection_plans;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inspection_plans = await db.inspection_plans.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.plan_name !== undefined) updatePayload.plan_name = data.plan_name;
if (data.plan_code !== undefined) updatePayload.plan_code = data.plan_code;
if (data.plan_type !== undefined) updatePayload.plan_type = data.plan_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
updatePayload.updatedById = currentUser.id;
await inspection_plans.update(updatePayload, {transaction});
if (data.item !== undefined) {
await inspection_plans.setItem(
data.item,
{ transaction }
);
}
return inspection_plans;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inspection_plans = await db.inspection_plans.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inspection_plans) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inspection_plans) {
await record.destroy({transaction});
}
});
return inspection_plans;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inspection_plans = await db.inspection_plans.findByPk(id, options);
await inspection_plans.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inspection_plans.destroy({
transaction
});
return inspection_plans;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inspection_plans = await db.inspection_plans.findOne(
{ where },
{ transaction },
);
if (!inspection_plans) {
return inspection_plans;
}
const output = inspection_plans.get({plain: true});
output.inspection_characteristics_inspection_plan = await inspection_plans.getInspection_characteristics_inspection_plan({
transaction
});
output.inspections_inspection_plan = await inspection_plans.getInspections_inspection_plan({
transaction
});
output.item = await inspection_plans.getItem({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
item_name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.plan_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'inspection_plans',
'plan_name',
filter.plan_name,
),
};
}
if (filter.plan_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'inspection_plans',
'plan_code',
filter.plan_code,
),
};
}
if (filter.instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'inspection_plans',
'instructions',
filter.instructions,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.plan_type) {
where = {
...where,
plan_type: filter.plan_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'inspection_plans',
'plan_name',
query,
),
],
};
}
const records = await db.inspection_plans.findAll({
attributes: [ 'id', 'plan_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['plan_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.plan_name,
}));
}
};

View File

@ -0,0 +1,511 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Inspection_resultsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inspection_results = await db.inspection_results.create(
{
id: data.id || undefined,
measured_value: data.measured_value
||
null
,
attribute_value: data.attribute_value
||
null
,
judgement: data.judgement
||
null
,
comments: data.comments
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inspection_results.setInspection( data.inspection || null, {
transaction,
});
await inspection_results.setCharacteristic( data.characteristic || null, {
transaction,
});
return inspection_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 inspection_resultsData = data.map((item, index) => ({
id: item.id || undefined,
measured_value: item.measured_value
||
null
,
attribute_value: item.attribute_value
||
null
,
judgement: item.judgement
||
null
,
comments: item.comments
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const inspection_results = await db.inspection_results.bulkCreate(inspection_resultsData, { transaction });
// For each item created, replace relation files
return inspection_results;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inspection_results = await db.inspection_results.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.measured_value !== undefined) updatePayload.measured_value = data.measured_value;
if (data.attribute_value !== undefined) updatePayload.attribute_value = data.attribute_value;
if (data.judgement !== undefined) updatePayload.judgement = data.judgement;
if (data.comments !== undefined) updatePayload.comments = data.comments;
updatePayload.updatedById = currentUser.id;
await inspection_results.update(updatePayload, {transaction});
if (data.inspection !== undefined) {
await inspection_results.setInspection(
data.inspection,
{ transaction }
);
}
if (data.characteristic !== undefined) {
await inspection_results.setCharacteristic(
data.characteristic,
{ transaction }
);
}
return inspection_results;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inspection_results = await db.inspection_results.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inspection_results) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inspection_results) {
await record.destroy({transaction});
}
});
return inspection_results;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inspection_results = await db.inspection_results.findByPk(id, options);
await inspection_results.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inspection_results.destroy({
transaction
});
return inspection_results;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inspection_results = await db.inspection_results.findOne(
{ where },
{ transaction },
);
if (!inspection_results) {
return inspection_results;
}
const output = inspection_results.get({plain: true});
output.inspection = await inspection_results.getInspection({
transaction
});
output.characteristic = await inspection_results.getCharacteristic({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.inspections,
as: 'inspection',
where: filter.inspection ? {
[Op.or]: [
{ id: { [Op.in]: filter.inspection.split('|').map(term => Utils.uuid(term)) } },
{
inspection_number: {
[Op.or]: filter.inspection.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.inspection_characteristics,
as: 'characteristic',
where: filter.characteristic ? {
[Op.or]: [
{ id: { [Op.in]: filter.characteristic.split('|').map(term => Utils.uuid(term)) } },
{
characteristic_name: {
[Op.or]: filter.characteristic.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.comments) {
where = {
...where,
[Op.and]: Utils.ilike(
'inspection_results',
'comments',
filter.comments,
),
};
}
if (filter.measured_valueRange) {
const [start, end] = filter.measured_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
measured_value: {
...where.measured_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
measured_value: {
...where.measured_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.judgement) {
where = {
...where,
judgement: filter.judgement,
};
}
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.inspection_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'inspection_results',
'comments',
query,
),
],
};
}
const records = await db.inspection_results.findAll({
attributes: [ 'id', 'comments' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['comments', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.comments,
}));
}
};

View File

@ -0,0 +1,770 @@
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 InspectionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inspections = await db.inspections.create(
{
id: data.id || undefined,
inspection_number: data.inspection_number
||
null
,
inspection_type: data.inspection_type
||
null
,
inspected_at: data.inspected_at
||
null
,
result: data.result
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inspections.setInspection_plan( data.inspection_plan || null, {
transaction,
});
await inspections.setItem( data.item || null, {
transaction,
});
await inspections.setLot( data.lot || null, {
transaction,
});
await inspections.setSerial( data.serial || null, {
transaction,
});
await inspections.setWork_order( data.work_order || null, {
transaction,
});
await inspections.setSupplier( data.supplier || null, {
transaction,
});
await inspections.setInspected_by( data.inspected_by || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.inspections.getTableName(),
belongsToColumn: 'evidence',
belongsToId: inspections.id,
},
data.evidence,
options,
);
return 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 inspectionsData = data.map((item, index) => ({
id: item.id || undefined,
inspection_number: item.inspection_number
||
null
,
inspection_type: item.inspection_type
||
null
,
inspected_at: item.inspected_at
||
null
,
result: item.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 inspections = await db.inspections.bulkCreate(inspectionsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < inspections.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.inspections.getTableName(),
belongsToColumn: 'evidence',
belongsToId: inspections[i].id,
},
data[i].evidence,
options,
);
}
return inspections;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inspections = await db.inspections.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.inspection_number !== undefined) updatePayload.inspection_number = data.inspection_number;
if (data.inspection_type !== undefined) updatePayload.inspection_type = data.inspection_type;
if (data.inspected_at !== undefined) updatePayload.inspected_at = data.inspected_at;
if (data.result !== undefined) updatePayload.result = data.result;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await inspections.update(updatePayload, {transaction});
if (data.inspection_plan !== undefined) {
await inspections.setInspection_plan(
data.inspection_plan,
{ transaction }
);
}
if (data.item !== undefined) {
await inspections.setItem(
data.item,
{ transaction }
);
}
if (data.lot !== undefined) {
await inspections.setLot(
data.lot,
{ transaction }
);
}
if (data.serial !== undefined) {
await inspections.setSerial(
data.serial,
{ transaction }
);
}
if (data.work_order !== undefined) {
await inspections.setWork_order(
data.work_order,
{ transaction }
);
}
if (data.supplier !== undefined) {
await inspections.setSupplier(
data.supplier,
{ transaction }
);
}
if (data.inspected_by !== undefined) {
await inspections.setInspected_by(
data.inspected_by,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.inspections.getTableName(),
belongsToColumn: 'evidence',
belongsToId: inspections.id,
},
data.evidence,
options,
);
return inspections;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inspections = await db.inspections.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inspections) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inspections) {
await record.destroy({transaction});
}
});
return inspections;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inspections = await db.inspections.findByPk(id, options);
await inspections.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inspections.destroy({
transaction
});
return inspections;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inspections = await db.inspections.findOne(
{ where },
{ transaction },
);
if (!inspections) {
return inspections;
}
const output = inspections.get({plain: true});
output.inspection_results_inspection = await inspections.getInspection_results_inspection({
transaction
});
output.nonconformances_inspection = await inspections.getNonconformances_inspection({
transaction
});
output.inspection_plan = await inspections.getInspection_plan({
transaction
});
output.item = await inspections.getItem({
transaction
});
output.lot = await inspections.getLot({
transaction
});
output.serial = await inspections.getSerial({
transaction
});
output.work_order = await inspections.getWork_order({
transaction
});
output.supplier = await inspections.getSupplier({
transaction
});
output.inspected_by = await inspections.getInspected_by({
transaction
});
output.evidence = await inspections.getEvidence({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.inspection_plans,
as: 'inspection_plan',
where: filter.inspection_plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.inspection_plan.split('|').map(term => Utils.uuid(term)) } },
{
plan_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)) } },
{
item_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.serials,
as: 'serial',
where: filter.serial ? {
[Op.or]: [
{ id: { [Op.in]: filter.serial.split('|').map(term => Utils.uuid(term)) } },
{
serial_number: {
[Op.or]: filter.serial.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.suppliers,
as: 'supplier',
where: filter.supplier ? {
[Op.or]: [
{ id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
{
supplier_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'inspected_by',
where: filter.inspected_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.inspected_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.inspected_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'evidence',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.inspection_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'inspections',
'inspection_number',
filter.inspection_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'inspections',
'notes',
filter.notes,
),
};
}
if (filter.inspected_atRange) {
const [start, end] = filter.inspected_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
inspected_at: {
...where.inspected_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
inspected_at: {
...where.inspected_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.result) {
where = {
...where,
result: filter.result,
};
}
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.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'inspections',
'inspection_number',
query,
),
],
};
}
const records = await db.inspections.findAll({
attributes: [ 'id', 'inspection_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['inspection_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.inspection_number,
}));
}
};

View File

@ -0,0 +1,632 @@
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,
on_hand_quantity: data.on_hand_quantity
||
null
,
allocated_quantity: data.allocated_quantity
||
null
,
available_quantity: data.available_quantity
||
null
,
last_counted_at: data.last_counted_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inventory_balances.setItem( data.item || null, {
transaction,
});
await inventory_balances.setLocation( data.location || null, {
transaction,
});
await inventory_balances.setLot( data.lot || null, {
transaction,
});
await inventory_balances.setSerial( data.serial || 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,
on_hand_quantity: item.on_hand_quantity
||
null
,
allocated_quantity: item.allocated_quantity
||
null
,
available_quantity: item.available_quantity
||
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 inventory_balances = await db.inventory_balances.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.on_hand_quantity !== undefined) updatePayload.on_hand_quantity = data.on_hand_quantity;
if (data.allocated_quantity !== undefined) updatePayload.allocated_quantity = data.allocated_quantity;
if (data.available_quantity !== undefined) updatePayload.available_quantity = data.available_quantity;
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.item !== undefined) {
await inventory_balances.setItem(
data.item,
{ transaction }
);
}
if (data.location !== undefined) {
await inventory_balances.setLocation(
data.location,
{ transaction }
);
}
if (data.lot !== undefined) {
await inventory_balances.setLot(
data.lot,
{ transaction }
);
}
if (data.serial !== undefined) {
await inventory_balances.setSerial(
data.serial,
{ 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.item = await inventory_balances.getItem({
transaction
});
output.location = await inventory_balances.getLocation({
transaction
});
output.lot = await inventory_balances.getLot({
transaction
});
output.serial = await inventory_balances.getSerial({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
item_name: {
[Op.or]: filter.item.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)) } },
{
location_name: {
[Op.or]: filter.location.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.serials,
as: 'serial',
where: filter.serial ? {
[Op.or]: [
{ id: { [Op.in]: filter.serial.split('|').map(term => Utils.uuid(term)) } },
{
serial_number: {
[Op.or]: filter.serial.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.on_hand_quantityRange) {
const [start, end] = filter.on_hand_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
on_hand_quantity: {
...where.on_hand_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
on_hand_quantity: {
...where.on_hand_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.allocated_quantityRange) {
const [start, end] = filter.allocated_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
allocated_quantity: {
...where.allocated_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
allocated_quantity: {
...where.allocated_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.available_quantityRange) {
const [start, end] = filter.available_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
available_quantity: {
...where.available_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
available_quantity: {
...where.available_quantity,
[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.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.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'inventory_balances',
'on_hand_quantity',
query,
),
],
};
}
const records = await db.inventory_balances.findAll({
attributes: [ 'id', 'on_hand_quantity' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['on_hand_quantity', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.on_hand_quantity,
}));
}
};

View File

@ -0,0 +1,951 @@
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_movementsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory_movements = await db.inventory_movements.create(
{
id: data.id || undefined,
movement_number: data.movement_number
||
null
,
movement_type: data.movement_type
||
null
,
movement_at: data.movement_at
||
null
,
quantity: data.quantity
||
null
,
reference: data.reference
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inventory_movements.setItem( data.item || null, {
transaction,
});
await inventory_movements.setUom( data.uom || null, {
transaction,
});
await inventory_movements.setFrom_location( data.from_location || null, {
transaction,
});
await inventory_movements.setTo_location( data.to_location || null, {
transaction,
});
await inventory_movements.setLot( data.lot || null, {
transaction,
});
await inventory_movements.setSerial( data.serial || null, {
transaction,
});
await inventory_movements.setWork_order( data.work_order || null, {
transaction,
});
await inventory_movements.setSupplier( data.supplier || null, {
transaction,
});
await inventory_movements.setCustomer( data.customer || null, {
transaction,
});
await inventory_movements.setReason_code( data.reason_code || null, {
transaction,
});
await inventory_movements.setPerformed_by( data.performed_by || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.inventory_movements.getTableName(),
belongsToColumn: 'documents',
belongsToId: inventory_movements.id,
},
data.documents,
options,
);
return inventory_movements;
}
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_movementsData = data.map((item, index) => ({
id: item.id || undefined,
movement_number: item.movement_number
||
null
,
movement_type: item.movement_type
||
null
,
movement_at: item.movement_at
||
null
,
quantity: item.quantity
||
null
,
reference: item.reference
||
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 inventory_movements = await db.inventory_movements.bulkCreate(inventory_movementsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < inventory_movements.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.inventory_movements.getTableName(),
belongsToColumn: 'documents',
belongsToId: inventory_movements[i].id,
},
data[i].documents,
options,
);
}
return inventory_movements;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inventory_movements = await db.inventory_movements.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.movement_number !== undefined) updatePayload.movement_number = data.movement_number;
if (data.movement_type !== undefined) updatePayload.movement_type = data.movement_type;
if (data.movement_at !== undefined) updatePayload.movement_at = data.movement_at;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.reference !== undefined) updatePayload.reference = data.reference;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await inventory_movements.update(updatePayload, {transaction});
if (data.item !== undefined) {
await inventory_movements.setItem(
data.item,
{ transaction }
);
}
if (data.uom !== undefined) {
await inventory_movements.setUom(
data.uom,
{ transaction }
);
}
if (data.from_location !== undefined) {
await inventory_movements.setFrom_location(
data.from_location,
{ transaction }
);
}
if (data.to_location !== undefined) {
await inventory_movements.setTo_location(
data.to_location,
{ transaction }
);
}
if (data.lot !== undefined) {
await inventory_movements.setLot(
data.lot,
{ transaction }
);
}
if (data.serial !== undefined) {
await inventory_movements.setSerial(
data.serial,
{ transaction }
);
}
if (data.work_order !== undefined) {
await inventory_movements.setWork_order(
data.work_order,
{ transaction }
);
}
if (data.supplier !== undefined) {
await inventory_movements.setSupplier(
data.supplier,
{ transaction }
);
}
if (data.customer !== undefined) {
await inventory_movements.setCustomer(
data.customer,
{ transaction }
);
}
if (data.reason_code !== undefined) {
await inventory_movements.setReason_code(
data.reason_code,
{ transaction }
);
}
if (data.performed_by !== undefined) {
await inventory_movements.setPerformed_by(
data.performed_by,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.inventory_movements.getTableName(),
belongsToColumn: 'documents',
belongsToId: inventory_movements.id,
},
data.documents,
options,
);
return inventory_movements;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory_movements = await db.inventory_movements.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inventory_movements) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inventory_movements) {
await record.destroy({transaction});
}
});
return inventory_movements;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inventory_movements = await db.inventory_movements.findByPk(id, options);
await inventory_movements.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inventory_movements.destroy({
transaction
});
return inventory_movements;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inventory_movements = await db.inventory_movements.findOne(
{ where },
{ transaction },
);
if (!inventory_movements) {
return inventory_movements;
}
const output = inventory_movements.get({plain: true});
output.item = await inventory_movements.getItem({
transaction
});
output.uom = await inventory_movements.getUom({
transaction
});
output.from_location = await inventory_movements.getFrom_location({
transaction
});
output.to_location = await inventory_movements.getTo_location({
transaction
});
output.lot = await inventory_movements.getLot({
transaction
});
output.serial = await inventory_movements.getSerial({
transaction
});
output.work_order = await inventory_movements.getWork_order({
transaction
});
output.supplier = await inventory_movements.getSupplier({
transaction
});
output.customer = await inventory_movements.getCustomer({
transaction
});
output.reason_code = await inventory_movements.getReason_code({
transaction
});
output.performed_by = await inventory_movements.getPerformed_by({
transaction
});
output.documents = await inventory_movements.getDocuments({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
item_name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.uoms,
as: 'uom',
where: filter.uom ? {
[Op.or]: [
{ id: { [Op.in]: filter.uom.split('|').map(term => Utils.uuid(term)) } },
{
uom_name: {
[Op.or]: filter.uom.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)) } },
{
location_name: {
[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)) } },
{
location_name: {
[Op.or]: filter.to_location.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.serials,
as: 'serial',
where: filter.serial ? {
[Op.or]: [
{ id: { [Op.in]: filter.serial.split('|').map(term => Utils.uuid(term)) } },
{
serial_number: {
[Op.or]: filter.serial.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.suppliers,
as: 'supplier',
where: filter.supplier ? {
[Op.or]: [
{ id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
{
supplier_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customers,
as: 'customer',
where: filter.customer ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
{
customer_name: {
[Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.reason_codes,
as: 'reason_code',
where: filter.reason_code ? {
[Op.or]: [
{ id: { [Op.in]: filter.reason_code.split('|').map(term => Utils.uuid(term)) } },
{
reason_name: {
[Op.or]: filter.reason_code.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'performed_by',
where: filter.performed_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.performed_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.performed_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'documents',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.movement_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_movements',
'movement_number',
filter.movement_number,
),
};
}
if (filter.reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_movements',
'reference',
filter.reference,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_movements',
'notes',
filter.notes,
),
};
}
if (filter.movement_atRange) {
const [start, end] = filter.movement_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
movement_at: {
...where.movement_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
movement_at: {
...where.movement_at,
[Op.lte]: end,
},
};
}
}
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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.movement_type) {
where = {
...where,
movement_type: filter.movement_type,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.inventory_movements.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(
'inventory_movements',
'movement_number',
query,
),
],
};
}
const records = await db.inventory_movements.findAll({
attributes: [ 'id', 'movement_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['movement_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.movement_number,
}));
}
};

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

@ -0,0 +1,657 @@
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,
item_name: data.item_name
||
null
,
item_code: data.item_code
||
null
,
item_type: data.item_type
||
null
,
lot_tracked: data.lot_tracked
||
false
,
serial_tracked: data.serial_tracked
||
false
,
standard_cost: data.standard_cost
||
null
,
shelf_life_days: data.shelf_life_days
||
null
,
description: data.description
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await items.setDefault_uom( data.default_uom || null, {
transaction,
});
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,
item_name: item.item_name
||
null
,
item_code: item.item_code
||
null
,
item_type: item.item_type
||
null
,
lot_tracked: item.lot_tracked
||
false
,
serial_tracked: item.serial_tracked
||
false
,
standard_cost: item.standard_cost
||
null
,
shelf_life_days: item.shelf_life_days
||
null
,
description: item.description
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const items = await db.items.bulkCreate(itemsData, { transaction });
// For each item created, replace relation files
return items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const items = await db.items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.item_name !== undefined) updatePayload.item_name = data.item_name;
if (data.item_code !== undefined) updatePayload.item_code = data.item_code;
if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
if (data.lot_tracked !== undefined) updatePayload.lot_tracked = data.lot_tracked;
if (data.serial_tracked !== undefined) updatePayload.serial_tracked = data.serial_tracked;
if (data.standard_cost !== undefined) updatePayload.standard_cost = data.standard_cost;
if (data.shelf_life_days !== undefined) updatePayload.shelf_life_days = data.shelf_life_days;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await items.update(updatePayload, {transaction});
if (data.default_uom !== undefined) {
await items.setDefault_uom(
data.default_uom,
{ transaction }
);
}
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.approved_vendors_item = await items.getApproved_vendors_item({
transaction
});
output.boms_parent_item = await items.getBoms_parent_item({
transaction
});
output.bom_lines_component_item = await items.getBom_lines_component_item({
transaction
});
output.routings_item = await items.getRoutings_item({
transaction
});
output.work_orders_item = await items.getWork_orders_item({
transaction
});
output.lots_item = await items.getLots_item({
transaction
});
output.serials_item = await items.getSerials_item({
transaction
});
output.inventory_balances_item = await items.getInventory_balances_item({
transaction
});
output.inventory_movements_item = await items.getInventory_movements_item({
transaction
});
output.purchase_order_lines_item = await items.getPurchase_order_lines_item({
transaction
});
output.inspection_plans_item = await items.getInspection_plans_item({
transaction
});
output.inspections_item = await items.getInspections_item({
transaction
});
output.nonconformances_item = await items.getNonconformances_item({
transaction
});
output.default_uom = await items.getDefault_uom({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.uoms,
as: 'default_uom',
where: filter.default_uom ? {
[Op.or]: [
{ id: { [Op.in]: filter.default_uom.split('|').map(term => Utils.uuid(term)) } },
{
uom_name: {
[Op.or]: filter.default_uom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.item_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'items',
'item_name',
filter.item_name,
),
};
}
if (filter.item_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'items',
'item_code',
filter.item_code,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'items',
'description',
filter.description,
),
};
}
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.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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.item_type) {
where = {
...where,
item_type: filter.item_type,
};
}
if (filter.lot_tracked) {
where = {
...where,
lot_tracked: filter.lot_tracked,
};
}
if (filter.serial_tracked) {
where = {
...where,
serial_tracked: filter.serial_tracked,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'items',
'item_name',
query,
),
],
};
}
const records = await db.items.findAll({
attributes: [ 'id', 'item_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['item_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.item_name,
}));
}
};

View File

@ -0,0 +1,492 @@
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,
location_name: data.location_name
||
null
,
location_code: data.location_code
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await locations.setWarehouse( data.warehouse || null, {
transaction,
});
await locations.setParent_location( data.parent_location || 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,
location_name: item.location_name
||
null
,
location_code: item.location_code
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const 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 locations = await db.locations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.location_name !== undefined) updatePayload.location_name = data.location_name;
if (data.location_code !== undefined) updatePayload.location_code = data.location_code;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await locations.update(updatePayload, {transaction});
if (data.warehouse !== undefined) {
await locations.setWarehouse(
data.warehouse,
{ transaction }
);
}
if (data.parent_location !== undefined) {
await locations.setParent_location(
data.parent_location,
{ 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_movements_from_location = await locations.getInventory_movements_from_location({
transaction
});
output.inventory_movements_to_location = await locations.getInventory_movements_to_location({
transaction
});
output.warehouse = await locations.getWarehouse({
transaction
});
output.parent_location = await locations.getParent_location({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.warehouses,
as: 'warehouse',
where: filter.warehouse ? {
[Op.or]: [
{ id: { [Op.in]: filter.warehouse.split('|').map(term => Utils.uuid(term)) } },
{
warehouse_name: {
[Op.or]: filter.warehouse.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.locations,
as: 'parent_location',
where: filter.parent_location ? {
[Op.or]: [
{ id: { [Op.in]: filter.parent_location.split('|').map(term => Utils.uuid(term)) } },
{
location_name: {
[Op.or]: filter.parent_location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.location_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'locations',
'location_name',
filter.location_name,
),
};
}
if (filter.location_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'locations',
'location_code',
filter.location_code,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'locations',
'location_name',
query,
),
],
};
}
const records = await db.locations.findAll({
attributes: [ 'id', 'location_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['location_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.location_name,
}));
}
};

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

@ -0,0 +1,596 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class 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
,
manufactured_at: data.manufactured_at
||
null
,
expires_at: data.expires_at
||
null
,
supplier_lot_number: data.supplier_lot_number
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await lots.setItem( data.item || null, {
transaction,
});
await lots.setSupplier( data.supplier || null, {
transaction,
});
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
,
manufactured_at: item.manufactured_at
||
null
,
expires_at: item.expires_at
||
null
,
supplier_lot_number: item.supplier_lot_number
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const lots = await db.lots.bulkCreate(lotsData, { transaction });
// For each item created, replace relation files
return lots;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const lots = await db.lots.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.lot_number !== undefined) updatePayload.lot_number = data.lot_number;
if (data.manufactured_at !== undefined) updatePayload.manufactured_at = data.manufactured_at;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.supplier_lot_number !== undefined) updatePayload.supplier_lot_number = data.supplier_lot_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await lots.update(updatePayload, {transaction});
if (data.item !== undefined) {
await lots.setItem(
data.item,
{ transaction }
);
}
if (data.supplier !== undefined) {
await lots.setSupplier(
data.supplier,
{ transaction }
);
}
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.serials_lot = await lots.getSerials_lot({
transaction
});
output.inventory_balances_lot = await lots.getInventory_balances_lot({
transaction
});
output.inventory_movements_lot = await lots.getInventory_movements_lot({
transaction
});
output.inspections_lot = await lots.getInspections_lot({
transaction
});
output.nonconformances_lot = await lots.getNonconformances_lot({
transaction
});
output.item = await lots.getItem({
transaction
});
output.supplier = await lots.getSupplier({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
item_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)) } },
{
supplier_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
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.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'lots',
'notes',
filter.notes,
),
};
}
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.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, ) {
let where = {};
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,640 @@
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_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const machine_events = await db.machine_events.create(
{
id: data.id || undefined,
event_type: data.event_type
||
null
,
status: data.status
||
null
,
started_at: data.started_at
||
null
,
ended_at: data.ended_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await machine_events.setMachine( data.machine || null, {
transaction,
});
await machine_events.setWork_order( data.work_order || null, {
transaction,
});
await machine_events.setReason_code( data.reason_code || null, {
transaction,
});
await machine_events.setReported_by( data.reported_by || null, {
transaction,
});
return machine_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_eventsData = data.map((item, index) => ({
id: item.id || undefined,
event_type: item.event_type
||
null
,
status: item.status
||
null
,
started_at: item.started_at
||
null
,
ended_at: item.ended_at
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const machine_events = await db.machine_events.bulkCreate(machine_eventsData, { transaction });
// For each item created, replace relation files
return machine_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const machine_events = await db.machine_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await machine_events.update(updatePayload, {transaction});
if (data.machine !== undefined) {
await machine_events.setMachine(
data.machine,
{ transaction }
);
}
if (data.work_order !== undefined) {
await machine_events.setWork_order(
data.work_order,
{ transaction }
);
}
if (data.reason_code !== undefined) {
await machine_events.setReason_code(
data.reason_code,
{ transaction }
);
}
if (data.reported_by !== undefined) {
await machine_events.setReported_by(
data.reported_by,
{ transaction }
);
}
return machine_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const machine_events = await db.machine_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of machine_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of machine_events) {
await record.destroy({transaction});
}
});
return machine_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const machine_events = await db.machine_events.findByPk(id, options);
await machine_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await machine_events.destroy({
transaction
});
return machine_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const machine_events = await db.machine_events.findOne(
{ where },
{ transaction },
);
if (!machine_events) {
return machine_events;
}
const output = machine_events.get({plain: true});
output.machine = await machine_events.getMachine({
transaction
});
output.work_order = await machine_events.getWork_order({
transaction
});
output.reason_code = await machine_events.getReason_code({
transaction
});
output.reported_by = await machine_events.getReported_by({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.machines,
as: 'machine',
where: filter.machine ? {
[Op.or]: [
{ id: { [Op.in]: filter.machine.split('|').map(term => Utils.uuid(term)) } },
{
machine_name: {
[Op.or]: filter.machine.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.reason_codes,
as: 'reason_code',
where: filter.reason_code ? {
[Op.or]: [
{ id: { [Op.in]: filter.reason_code.split('|').map(term => Utils.uuid(term)) } },
{
reason_name: {
[Op.or]: filter.reason_code.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'reported_by',
where: filter.reported_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.reported_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.reported_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'machine_events',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
started_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ended_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
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.ended_atRange) {
const [start, end] = filter.ended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.event_type) {
where = {
...where,
event_type: filter.event_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.machine_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'machine_events',
'notes',
query,
),
],
};
}
const records = await db.machine_events.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,604 @@
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,
machine_name: data.machine_name
||
null
,
machine_code: data.machine_code
||
null
,
status: data.status
||
null
,
commissioned_on: data.commissioned_on
||
null
,
manufacturer: data.manufacturer
||
null
,
model: data.model
||
null
,
serial_number: data.serial_number
||
null
,
notes: data.notes
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await machines.setWork_center( data.work_center || 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,
machine_name: item.machine_name
||
null
,
machine_code: item.machine_code
||
null
,
status: item.status
||
null
,
commissioned_on: item.commissioned_on
||
null
,
manufacturer: item.manufacturer
||
null
,
model: item.model
||
null
,
serial_number: item.serial_number
||
null
,
notes: item.notes
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const 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 machines = await db.machines.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.machine_name !== undefined) updatePayload.machine_name = data.machine_name;
if (data.machine_code !== undefined) updatePayload.machine_code = data.machine_code;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.commissioned_on !== undefined) updatePayload.commissioned_on = data.commissioned_on;
if (data.manufacturer !== undefined) updatePayload.manufacturer = data.manufacturer;
if (data.model !== undefined) updatePayload.model = data.model;
if (data.serial_number !== undefined) updatePayload.serial_number = data.serial_number;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await machines.update(updatePayload, {transaction});
if (data.work_center !== undefined) {
await machines.setWork_center(
data.work_center,
{ 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_events_machine = await machines.getMachine_events_machine({
transaction
});
output.work_order_operations_machine = await machines.getWork_order_operations_machine({
transaction
});
output.work_center = await machines.getWork_center({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.work_centers,
as: 'work_center',
where: filter.work_center ? {
[Op.or]: [
{ id: { [Op.in]: filter.work_center.split('|').map(term => Utils.uuid(term)) } },
{
work_center_name: {
[Op.or]: filter.work_center.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.machine_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'machine_name',
filter.machine_name,
),
};
}
if (filter.machine_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'machine_code',
filter.machine_code,
),
};
}
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.serial_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'serial_number',
filter.serial_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'machines',
'notes',
filter.notes,
),
};
}
if (filter.commissioned_onRange) {
const [start, end] = filter.commissioned_onRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commissioned_on: {
...where.commissioned_on,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commissioned_on: {
...where.commissioned_on,
[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.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'machines',
'machine_name',
query,
),
],
};
}
const records = await db.machines.findAll({
attributes: [ 'id', 'machine_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['machine_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.machine_name,
}));
}
};

View File

@ -0,0 +1,810 @@
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
,
reported_at: data.reported_at
||
null
,
problem_description: data.problem_description
||
null
,
containment_actions: data.containment_actions
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await nonconformances.setItem( data.item || null, {
transaction,
});
await nonconformances.setLot( data.lot || null, {
transaction,
});
await nonconformances.setSerial( data.serial || null, {
transaction,
});
await nonconformances.setWork_order( data.work_order || null, {
transaction,
});
await nonconformances.setInspection( data.inspection || null, {
transaction,
});
await nonconformances.setReported_by( data.reported_by || null, {
transaction,
});
await nonconformances.setDisposition_code( data.disposition_code || 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
,
reported_at: item.reported_at
||
null
,
problem_description: item.problem_description
||
null
,
containment_actions: item.containment_actions
||
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 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.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
if (data.problem_description !== undefined) updatePayload.problem_description = data.problem_description;
if (data.containment_actions !== undefined) updatePayload.containment_actions = data.containment_actions;
updatePayload.updatedById = currentUser.id;
await nonconformances.update(updatePayload, {transaction});
if (data.item !== undefined) {
await nonconformances.setItem(
data.item,
{ transaction }
);
}
if (data.lot !== undefined) {
await nonconformances.setLot(
data.lot,
{ transaction }
);
}
if (data.serial !== undefined) {
await nonconformances.setSerial(
data.serial,
{ transaction }
);
}
if (data.work_order !== undefined) {
await nonconformances.setWork_order(
data.work_order,
{ transaction }
);
}
if (data.inspection !== undefined) {
await nonconformances.setInspection(
data.inspection,
{ transaction }
);
}
if (data.reported_by !== undefined) {
await nonconformances.setReported_by(
data.reported_by,
{ transaction }
);
}
if (data.disposition_code !== undefined) {
await nonconformances.setDisposition_code(
data.disposition_code,
{ 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.capa_actions_nonconformance = await nonconformances.getCapa_actions_nonconformance({
transaction
});
output.item = await nonconformances.getItem({
transaction
});
output.lot = await nonconformances.getLot({
transaction
});
output.serial = await nonconformances.getSerial({
transaction
});
output.work_order = await nonconformances.getWork_order({
transaction
});
output.inspection = await nonconformances.getInspection({
transaction
});
output.reported_by = await nonconformances.getReported_by({
transaction
});
output.disposition_code = await nonconformances.getDisposition_code({
transaction
});
output.attachments = await nonconformances.getAttachments({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
item_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.serials,
as: 'serial',
where: filter.serial ? {
[Op.or]: [
{ id: { [Op.in]: filter.serial.split('|').map(term => Utils.uuid(term)) } },
{
serial_number: {
[Op.or]: filter.serial.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.inspections,
as: 'inspection',
where: filter.inspection ? {
[Op.or]: [
{ id: { [Op.in]: filter.inspection.split('|').map(term => Utils.uuid(term)) } },
{
inspection_number: {
[Op.or]: filter.inspection.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'reported_by',
where: filter.reported_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.reported_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.reported_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.disposition_codes,
as: 'disposition_code',
where: filter.disposition_code ? {
[Op.or]: [
{ id: { [Op.in]: filter.disposition_code.split('|').map(term => Utils.uuid(term)) } },
{
disposition_name: {
[Op.or]: filter.disposition_code.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.ncr_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'nonconformances',
'ncr_number',
filter.ncr_number,
),
};
}
if (filter.problem_description) {
where = {
...where,
[Op.and]: Utils.ilike(
'nonconformances',
'problem_description',
filter.problem_description,
),
};
}
if (filter.containment_actions) {
where = {
...where,
[Op.and]: Utils.ilike(
'nonconformances',
'containment_actions',
filter.containment_actions,
),
};
}
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.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.nonconformances.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'nonconformances',
'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,360 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PermissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return permissions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const permissionsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const permissions = await db.permissions.bulkCreate(permissionsData, { transaction });
// For each item created, replace relation files
return permissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await permissions.update(updatePayload, {transaction});
return permissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of permissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of permissions) {
await record.destroy({transaction});
}
});
return permissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findByPk(id, options);
await permissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await permissions.destroy({
transaction
});
return permissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findOne(
{ where },
{ transaction },
);
if (!permissions) {
return permissions;
}
const output = permissions.get({plain: true});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'permissions',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.permissions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'permissions',
'name',
query,
),
],
};
}
const records = await db.permissions.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,656 @@
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 Purchase_order_linesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const purchase_order_lines = await db.purchase_order_lines.create(
{
id: data.id || undefined,
line_no: data.line_no
||
null
,
ordered_quantity: data.ordered_quantity
||
null
,
received_quantity: data.received_quantity
||
null
,
unit_price: data.unit_price
||
null
,
need_by: data.need_by
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await purchase_order_lines.setPurchase_order( data.purchase_order || null, {
transaction,
});
await purchase_order_lines.setItem( data.item || null, {
transaction,
});
await purchase_order_lines.setUom( data.uom || null, {
transaction,
});
return purchase_order_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 purchase_order_linesData = data.map((item, index) => ({
id: item.id || undefined,
line_no: item.line_no
||
null
,
ordered_quantity: item.ordered_quantity
||
null
,
received_quantity: item.received_quantity
||
null
,
unit_price: item.unit_price
||
null
,
need_by: item.need_by
||
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 purchase_order_lines = await db.purchase_order_lines.bulkCreate(purchase_order_linesData, { transaction });
// For each item created, replace relation files
return purchase_order_lines;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const purchase_order_lines = await db.purchase_order_lines.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.line_no !== undefined) updatePayload.line_no = data.line_no;
if (data.ordered_quantity !== undefined) updatePayload.ordered_quantity = data.ordered_quantity;
if (data.received_quantity !== undefined) updatePayload.received_quantity = data.received_quantity;
if (data.unit_price !== undefined) updatePayload.unit_price = data.unit_price;
if (data.need_by !== undefined) updatePayload.need_by = data.need_by;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await purchase_order_lines.update(updatePayload, {transaction});
if (data.purchase_order !== undefined) {
await purchase_order_lines.setPurchase_order(
data.purchase_order,
{ transaction }
);
}
if (data.item !== undefined) {
await purchase_order_lines.setItem(
data.item,
{ transaction }
);
}
if (data.uom !== undefined) {
await purchase_order_lines.setUom(
data.uom,
{ transaction }
);
}
return purchase_order_lines;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const purchase_order_lines = await db.purchase_order_lines.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of purchase_order_lines) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of purchase_order_lines) {
await record.destroy({transaction});
}
});
return purchase_order_lines;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const purchase_order_lines = await db.purchase_order_lines.findByPk(id, options);
await purchase_order_lines.update({
deletedBy: currentUser.id
}, {
transaction,
});
await purchase_order_lines.destroy({
transaction
});
return purchase_order_lines;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const purchase_order_lines = await db.purchase_order_lines.findOne(
{ where },
{ transaction },
);
if (!purchase_order_lines) {
return purchase_order_lines;
}
const output = purchase_order_lines.get({plain: true});
output.purchase_order = await purchase_order_lines.getPurchase_order({
transaction
});
output.item = await purchase_order_lines.getItem({
transaction
});
output.uom = await purchase_order_lines.getUom({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.purchase_orders,
as: 'purchase_order',
where: filter.purchase_order ? {
[Op.or]: [
{ id: { [Op.in]: filter.purchase_order.split('|').map(term => Utils.uuid(term)) } },
{
purchase_order_number: {
[Op.or]: filter.purchase_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)) } },
{
item_name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.uoms,
as: 'uom',
where: filter.uom ? {
[Op.or]: [
{ id: { [Op.in]: filter.uom.split('|').map(term => Utils.uuid(term)) } },
{
uom_name: {
[Op.or]: filter.uom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'purchase_order_lines',
'notes',
filter.notes,
),
};
}
if (filter.line_noRange) {
const [start, end] = filter.line_noRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
line_no: {
...where.line_no,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
line_no: {
...where.line_no,
[Op.lte]: end,
},
};
}
}
if (filter.ordered_quantityRange) {
const [start, end] = filter.ordered_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ordered_quantity: {
...where.ordered_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ordered_quantity: {
...where.ordered_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.received_quantityRange) {
const [start, end] = filter.received_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
received_quantity: {
...where.received_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
received_quantity: {
...where.received_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.unit_priceRange) {
const [start, end] = filter.unit_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unit_price: {
...where.unit_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unit_price: {
...where.unit_price,
[Op.lte]: end,
},
};
}
}
if (filter.need_byRange) {
const [start, end] = filter.need_byRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
need_by: {
...where.need_by,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
need_by: {
...where.need_by,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.purchase_order_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'purchase_order_lines',
'notes',
query,
),
],
};
}
const records = await db.purchase_order_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,
}));
}
};

View File

@ -0,0 +1,556 @@
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 Purchase_ordersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const purchase_orders = await db.purchase_orders.create(
{
id: data.id || undefined,
purchase_order_number: data.purchase_order_number
||
null
,
status: data.status
||
null
,
ordered_at: data.ordered_at
||
null
,
expected_at: data.expected_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await purchase_orders.setSupplier( data.supplier || null, {
transaction,
});
await purchase_orders.setCreated_by_user( data.created_by_user || null, {
transaction,
});
return purchase_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 purchase_ordersData = data.map((item, index) => ({
id: item.id || undefined,
purchase_order_number: item.purchase_order_number
||
null
,
status: item.status
||
null
,
ordered_at: item.ordered_at
||
null
,
expected_at: item.expected_at
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const purchase_orders = await db.purchase_orders.bulkCreate(purchase_ordersData, { transaction });
// For each item created, replace relation files
return purchase_orders;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const purchase_orders = await db.purchase_orders.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.purchase_order_number !== undefined) updatePayload.purchase_order_number = data.purchase_order_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.ordered_at !== undefined) updatePayload.ordered_at = data.ordered_at;
if (data.expected_at !== undefined) updatePayload.expected_at = data.expected_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await purchase_orders.update(updatePayload, {transaction});
if (data.supplier !== undefined) {
await purchase_orders.setSupplier(
data.supplier,
{ transaction }
);
}
if (data.created_by_user !== undefined) {
await purchase_orders.setCreated_by_user(
data.created_by_user,
{ transaction }
);
}
return purchase_orders;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const purchase_orders = await db.purchase_orders.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of purchase_orders) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of purchase_orders) {
await record.destroy({transaction});
}
});
return purchase_orders;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const purchase_orders = await db.purchase_orders.findByPk(id, options);
await purchase_orders.update({
deletedBy: currentUser.id
}, {
transaction,
});
await purchase_orders.destroy({
transaction
});
return purchase_orders;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const purchase_orders = await db.purchase_orders.findOne(
{ where },
{ transaction },
);
if (!purchase_orders) {
return purchase_orders;
}
const output = purchase_orders.get({plain: true});
output.purchase_order_lines_purchase_order = await purchase_orders.getPurchase_order_lines_purchase_order({
transaction
});
output.supplier = await purchase_orders.getSupplier({
transaction
});
output.created_by_user = await purchase_orders.getCreated_by_user({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.suppliers,
as: 'supplier',
where: filter.supplier ? {
[Op.or]: [
{ id: { [Op.in]: filter.supplier.split('|').map(term => Utils.uuid(term)) } },
{
supplier_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'created_by_user',
where: filter.created_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.purchase_order_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'purchase_orders',
'purchase_order_number',
filter.purchase_order_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'purchase_orders',
'notes',
filter.notes,
),
};
}
if (filter.ordered_atRange) {
const [start, end] = filter.ordered_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ordered_at: {
...where.ordered_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ordered_at: {
...where.ordered_at,
[Op.lte]: end,
},
};
}
}
if (filter.expected_atRange) {
const [start, end] = filter.expected_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expected_at: {
...where.expected_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expected_at: {
...where.expected_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.purchase_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'purchase_orders',
'purchase_order_number',
query,
),
],
};
}
const records = await db.purchase_orders.findAll({
attributes: [ 'id', 'purchase_order_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['purchase_order_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.purchase_order_number,
}));
}
};

View File

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

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

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

View File

@ -0,0 +1,611 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Routing_operationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const routing_operations = await db.routing_operations.create(
{
id: data.id || undefined,
operation_no: data.operation_no
||
null
,
operation_name: data.operation_name
||
null
,
setup_minutes: data.setup_minutes
||
null
,
run_minutes_per_unit: data.run_minutes_per_unit
||
null
,
work_instructions: data.work_instructions
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await routing_operations.setRouting( data.routing || null, {
transaction,
});
await routing_operations.setWork_center( data.work_center || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.routing_operations.getTableName(),
belongsToColumn: 'attachments',
belongsToId: routing_operations.id,
},
data.attachments,
options,
);
return routing_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 routing_operationsData = data.map((item, index) => ({
id: item.id || undefined,
operation_no: item.operation_no
||
null
,
operation_name: item.operation_name
||
null
,
setup_minutes: item.setup_minutes
||
null
,
run_minutes_per_unit: item.run_minutes_per_unit
||
null
,
work_instructions: item.work_instructions
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const routing_operations = await db.routing_operations.bulkCreate(routing_operationsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < routing_operations.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.routing_operations.getTableName(),
belongsToColumn: 'attachments',
belongsToId: routing_operations[i].id,
},
data[i].attachments,
options,
);
}
return routing_operations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const routing_operations = await db.routing_operations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.operation_no !== undefined) updatePayload.operation_no = data.operation_no;
if (data.operation_name !== undefined) updatePayload.operation_name = data.operation_name;
if (data.setup_minutes !== undefined) updatePayload.setup_minutes = data.setup_minutes;
if (data.run_minutes_per_unit !== undefined) updatePayload.run_minutes_per_unit = data.run_minutes_per_unit;
if (data.work_instructions !== undefined) updatePayload.work_instructions = data.work_instructions;
updatePayload.updatedById = currentUser.id;
await routing_operations.update(updatePayload, {transaction});
if (data.routing !== undefined) {
await routing_operations.setRouting(
data.routing,
{ transaction }
);
}
if (data.work_center !== undefined) {
await routing_operations.setWork_center(
data.work_center,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.routing_operations.getTableName(),
belongsToColumn: 'attachments',
belongsToId: routing_operations.id,
},
data.attachments,
options,
);
return routing_operations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const routing_operations = await db.routing_operations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of routing_operations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of routing_operations) {
await record.destroy({transaction});
}
});
return routing_operations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const routing_operations = await db.routing_operations.findByPk(id, options);
await routing_operations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await routing_operations.destroy({
transaction
});
return routing_operations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const routing_operations = await db.routing_operations.findOne(
{ where },
{ transaction },
);
if (!routing_operations) {
return routing_operations;
}
const output = routing_operations.get({plain: true});
output.routing = await routing_operations.getRouting({
transaction
});
output.work_center = await routing_operations.getWork_center({
transaction
});
output.attachments = await routing_operations.getAttachments({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.routings,
as: 'routing',
where: filter.routing ? {
[Op.or]: [
{ id: { [Op.in]: filter.routing.split('|').map(term => Utils.uuid(term)) } },
{
routing_name: {
[Op.or]: filter.routing.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.work_centers,
as: 'work_center',
where: filter.work_center ? {
[Op.or]: [
{ id: { [Op.in]: filter.work_center.split('|').map(term => Utils.uuid(term)) } },
{
work_center_name: {
[Op.or]: filter.work_center.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.operation_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'routing_operations',
'operation_name',
filter.operation_name,
),
};
}
if (filter.work_instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'routing_operations',
'work_instructions',
filter.work_instructions,
),
};
}
if (filter.operation_noRange) {
const [start, end] = filter.operation_noRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
operation_no: {
...where.operation_no,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
operation_no: {
...where.operation_no,
[Op.lte]: end,
},
};
}
}
if (filter.setup_minutesRange) {
const [start, end] = filter.setup_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
setup_minutes: {
...where.setup_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
setup_minutes: {
...where.setup_minutes,
[Op.lte]: end,
},
};
}
}
if (filter.run_minutes_per_unitRange) {
const [start, end] = filter.run_minutes_per_unitRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
run_minutes_per_unit: {
...where.run_minutes_per_unit,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
run_minutes_per_unit: {
...where.run_minutes_per_unit,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.routing_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'routing_operations',
'operation_name',
query,
),
],
};
}
const records = await db.routing_operations.findAll({
attributes: [ 'id', 'operation_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['operation_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.operation_name,
}));
}
};

View File

@ -0,0 +1,473 @@
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 RoutingsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const routings = await db.routings.create(
{
id: data.id || undefined,
routing_name: data.routing_name
||
null
,
routing_code: data.routing_code
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await routings.setItem( data.item || null, {
transaction,
});
return routings;
}
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 routingsData = data.map((item, index) => ({
id: item.id || undefined,
routing_name: item.routing_name
||
null
,
routing_code: item.routing_code
||
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 routings = await db.routings.bulkCreate(routingsData, { transaction });
// For each item created, replace relation files
return routings;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const routings = await db.routings.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.routing_name !== undefined) updatePayload.routing_name = data.routing_name;
if (data.routing_code !== undefined) updatePayload.routing_code = data.routing_code;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await routings.update(updatePayload, {transaction});
if (data.item !== undefined) {
await routings.setItem(
data.item,
{ transaction }
);
}
return routings;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const routings = await db.routings.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of routings) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of routings) {
await record.destroy({transaction});
}
});
return routings;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const routings = await db.routings.findByPk(id, options);
await routings.update({
deletedBy: currentUser.id
}, {
transaction,
});
await routings.destroy({
transaction
});
return routings;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const routings = await db.routings.findOne(
{ where },
{ transaction },
);
if (!routings) {
return routings;
}
const output = routings.get({plain: true});
output.routing_operations_routing = await routings.getRouting_operations_routing({
transaction
});
output.work_orders_routing = await routings.getWork_orders_routing({
transaction
});
output.item = await routings.getItem({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
item_name: {
[Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.routing_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'routings',
'routing_name',
filter.routing_name,
),
};
}
if (filter.routing_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'routings',
'routing_code',
filter.routing_code,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'routings',
'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.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.routings.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(
'routings',
'routing_name',
query,
),
],
};
}
const records = await db.routings.findAll({
attributes: [ 'id', 'routing_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['routing_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.routing_name,
}));
}
};

View File

@ -0,0 +1,531 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class SerialsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const serials = await db.serials.create(
{
id: data.id || undefined,
serial_number: data.serial_number
||
null
,
status: data.status
||
null
,
manufactured_at: data.manufactured_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await serials.setItem( data.item || null, {
transaction,
});
await serials.setLot( data.lot || null, {
transaction,
});
return serials;
}
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 serialsData = data.map((item, index) => ({
id: item.id || undefined,
serial_number: item.serial_number
||
null
,
status: item.status
||
null
,
manufactured_at: item.manufactured_at
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const serials = await db.serials.bulkCreate(serialsData, { transaction });
// For each item created, replace relation files
return serials;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const serials = await db.serials.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.serial_number !== undefined) updatePayload.serial_number = data.serial_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.manufactured_at !== undefined) updatePayload.manufactured_at = data.manufactured_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await serials.update(updatePayload, {transaction});
if (data.item !== undefined) {
await serials.setItem(
data.item,
{ transaction }
);
}
if (data.lot !== undefined) {
await serials.setLot(
data.lot,
{ transaction }
);
}
return serials;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const serials = await db.serials.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of serials) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of serials) {
await record.destroy({transaction});
}
});
return serials;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const serials = await db.serials.findByPk(id, options);
await serials.update({
deletedBy: currentUser.id
}, {
transaction,
});
await serials.destroy({
transaction
});
return serials;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const serials = await db.serials.findOne(
{ where },
{ transaction },
);
if (!serials) {
return serials;
}
const output = serials.get({plain: true});
output.inventory_balances_serial = await serials.getInventory_balances_serial({
transaction
});
output.inventory_movements_serial = await serials.getInventory_movements_serial({
transaction
});
output.inspections_serial = await serials.getInspections_serial({
transaction
});
output.nonconformances_serial = await serials.getNonconformances_serial({
transaction
});
output.item = await serials.getItem({
transaction
});
output.lot = await serials.getLot({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
item_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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.serial_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'serials',
'serial_number',
filter.serial_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'serials',
'notes',
filter.notes,
),
};
}
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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.serials.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(
'serials',
'serial_number',
query,
),
],
};
}
const records = await db.serials.findAll({
attributes: [ 'id', 'serial_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['serial_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.serial_number,
}));
}
};

View File

@ -0,0 +1,498 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class SuppliersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.create(
{
id: data.id || undefined,
supplier_name: data.supplier_name
||
null
,
supplier_code: data.supplier_code
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
address: data.address
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ 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,
supplier_name: item.supplier_name
||
null
,
supplier_code: item.supplier_code
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
address: item.address
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const suppliers = await db.suppliers.bulkCreate(suppliersData, { transaction });
// For each item created, replace relation files
return suppliers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.supplier_name !== undefined) updatePayload.supplier_name = data.supplier_name;
if (data.supplier_code !== undefined) updatePayload.supplier_code = data.supplier_code;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await suppliers.update(updatePayload, {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.approved_vendors_supplier = await suppliers.getApproved_vendors_supplier({
transaction
});
output.lots_supplier = await suppliers.getLots_supplier({
transaction
});
output.inventory_movements_supplier = await suppliers.getInventory_movements_supplier({
transaction
});
output.purchase_orders_supplier = await suppliers.getPurchase_orders_supplier({
transaction
});
output.inspections_supplier = await suppliers.getInspections_supplier({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.supplier_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'supplier_name',
filter.supplier_name,
),
};
}
if (filter.supplier_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'supplier_code',
filter.supplier_code,
),
};
}
if (filter.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.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'address',
filter.address,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.suppliers.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'suppliers',
'supplier_name',
query,
),
],
};
}
const records = await db.suppliers.findAll({
attributes: [ 'id', 'supplier_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['supplier_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.supplier_name,
}));
}
};

459
backend/src/db/api/uoms.js Normal file
View File

@ -0,0 +1,459 @@
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 UomsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const uoms = await db.uoms.create(
{
id: data.id || undefined,
uom_name: data.uom_name
||
null
,
uom_code: data.uom_code
||
null
,
base_multiplier: data.base_multiplier
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return uoms;
}
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 uomsData = data.map((item, index) => ({
id: item.id || undefined,
uom_name: item.uom_name
||
null
,
uom_code: item.uom_code
||
null
,
base_multiplier: item.base_multiplier
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const uoms = await db.uoms.bulkCreate(uomsData, { transaction });
// For each item created, replace relation files
return uoms;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const uoms = await db.uoms.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.uom_name !== undefined) updatePayload.uom_name = data.uom_name;
if (data.uom_code !== undefined) updatePayload.uom_code = data.uom_code;
if (data.base_multiplier !== undefined) updatePayload.base_multiplier = data.base_multiplier;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await uoms.update(updatePayload, {transaction});
return uoms;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const uoms = await db.uoms.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of uoms) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of uoms) {
await record.destroy({transaction});
}
});
return uoms;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const uoms = await db.uoms.findByPk(id, options);
await uoms.update({
deletedBy: currentUser.id
}, {
transaction,
});
await uoms.destroy({
transaction
});
return uoms;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const uoms = await db.uoms.findOne(
{ where },
{ transaction },
);
if (!uoms) {
return uoms;
}
const output = uoms.get({plain: true});
output.items_default_uom = await uoms.getItems_default_uom({
transaction
});
output.bom_lines_uom = await uoms.getBom_lines_uom({
transaction
});
output.inventory_movements_uom = await uoms.getInventory_movements_uom({
transaction
});
output.purchase_order_lines_uom = await uoms.getPurchase_order_lines_uom({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.uom_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'uoms',
'uom_name',
filter.uom_name,
),
};
}
if (filter.uom_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'uoms',
'uom_code',
filter.uom_code,
),
};
}
if (filter.base_multiplierRange) {
const [start, end] = filter.base_multiplierRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
base_multiplier: {
...where.base_multiplier,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
base_multiplier: {
...where.base_multiplier,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.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.uoms.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(
'uoms',
'uom_name',
query,
),
],
};
}
const records = await db.uoms.findAll({
attributes: [ 'id', 'uom_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['uom_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.uom_name,
}));
}
};

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

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

View File

@ -0,0 +1,434 @@
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,
warehouse_name: data.warehouse_name
||
null
,
warehouse_code: data.warehouse_code
||
null
,
description: data.description
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ 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,
warehouse_name: item.warehouse_name
||
null
,
warehouse_code: item.warehouse_code
||
null
,
description: item.description
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const 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 warehouses = await db.warehouses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.warehouse_name !== undefined) updatePayload.warehouse_name = data.warehouse_name;
if (data.warehouse_code !== undefined) updatePayload.warehouse_code = data.warehouse_code;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await warehouses.update(updatePayload, {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
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.warehouse_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'warehouses',
'warehouse_name',
filter.warehouse_name,
),
};
}
if (filter.warehouse_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'warehouses',
'warehouse_code',
filter.warehouse_code,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'warehouses',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'warehouses',
'warehouse_name',
query,
),
],
};
}
const records = await db.warehouses.findAll({
attributes: [ 'id', 'warehouse_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['warehouse_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.warehouse_name,
}));
}
};

View File

@ -0,0 +1,492 @@
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_centersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const work_centers = await db.work_centers.create(
{
id: data.id || undefined,
work_center_name: data.work_center_name
||
null
,
work_center_code: data.work_center_code
||
null
,
default_labor_rate: data.default_labor_rate
||
null
,
default_machine_rate: data.default_machine_rate
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return work_centers;
}
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_centersData = data.map((item, index) => ({
id: item.id || undefined,
work_center_name: item.work_center_name
||
null
,
work_center_code: item.work_center_code
||
null
,
default_labor_rate: item.default_labor_rate
||
null
,
default_machine_rate: item.default_machine_rate
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const work_centers = await db.work_centers.bulkCreate(work_centersData, { transaction });
// For each item created, replace relation files
return work_centers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const work_centers = await db.work_centers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.work_center_name !== undefined) updatePayload.work_center_name = data.work_center_name;
if (data.work_center_code !== undefined) updatePayload.work_center_code = data.work_center_code;
if (data.default_labor_rate !== undefined) updatePayload.default_labor_rate = data.default_labor_rate;
if (data.default_machine_rate !== undefined) updatePayload.default_machine_rate = data.default_machine_rate;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await work_centers.update(updatePayload, {transaction});
return work_centers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const work_centers = await db.work_centers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of work_centers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of work_centers) {
await record.destroy({transaction});
}
});
return work_centers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const work_centers = await db.work_centers.findByPk(id, options);
await work_centers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await work_centers.destroy({
transaction
});
return work_centers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const work_centers = await db.work_centers.findOne(
{ where },
{ transaction },
);
if (!work_centers) {
return work_centers;
}
const output = work_centers.get({plain: true});
output.routing_operations_work_center = await work_centers.getRouting_operations_work_center({
transaction
});
output.machines_work_center = await work_centers.getMachines_work_center({
transaction
});
output.work_order_operations_work_center = await work_centers.getWork_order_operations_work_center({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.work_center_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_centers',
'work_center_name',
filter.work_center_name,
),
};
}
if (filter.work_center_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_centers',
'work_center_code',
filter.work_center_code,
),
};
}
if (filter.default_labor_rateRange) {
const [start, end] = filter.default_labor_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
default_labor_rate: {
...where.default_labor_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
default_labor_rate: {
...where.default_labor_rate,
[Op.lte]: end,
},
};
}
}
if (filter.default_machine_rateRange) {
const [start, end] = filter.default_machine_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
default_machine_rate: {
...where.default_machine_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
default_machine_rate: {
...where.default_machine_rate,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.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.work_centers.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(
'work_centers',
'work_center_name',
query,
),
],
};
}
const records = await db.work_centers.findAll({
attributes: [ 'id', 'work_center_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['work_center_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.work_center_name,
}));
}
};

View File

@ -0,0 +1,737 @@
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_order_operationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const work_order_operations = await db.work_order_operations.create(
{
id: data.id || undefined,
operation_no: data.operation_no
||
null
,
operation_name: data.operation_name
||
null
,
status: data.status
||
null
,
started_at: data.started_at
||
null
,
ended_at: data.ended_at
||
null
,
good_quantity: data.good_quantity
||
null
,
scrap_quantity: data.scrap_quantity
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await work_order_operations.setWork_order( data.work_order || null, {
transaction,
});
await work_order_operations.setWork_center( data.work_center || null, {
transaction,
});
await work_order_operations.setMachine( data.machine || null, {
transaction,
});
await work_order_operations.setPerformed_by( data.performed_by || null, {
transaction,
});
return work_order_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 work_order_operationsData = data.map((item, index) => ({
id: item.id || undefined,
operation_no: item.operation_no
||
null
,
operation_name: item.operation_name
||
null
,
status: item.status
||
null
,
started_at: item.started_at
||
null
,
ended_at: item.ended_at
||
null
,
good_quantity: item.good_quantity
||
null
,
scrap_quantity: item.scrap_quantity
||
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_order_operations = await db.work_order_operations.bulkCreate(work_order_operationsData, { transaction });
// For each item created, replace relation files
return work_order_operations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const work_order_operations = await db.work_order_operations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.operation_no !== undefined) updatePayload.operation_no = data.operation_no;
if (data.operation_name !== undefined) updatePayload.operation_name = data.operation_name;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.good_quantity !== undefined) updatePayload.good_quantity = data.good_quantity;
if (data.scrap_quantity !== undefined) updatePayload.scrap_quantity = data.scrap_quantity;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await work_order_operations.update(updatePayload, {transaction});
if (data.work_order !== undefined) {
await work_order_operations.setWork_order(
data.work_order,
{ transaction }
);
}
if (data.work_center !== undefined) {
await work_order_operations.setWork_center(
data.work_center,
{ transaction }
);
}
if (data.machine !== undefined) {
await work_order_operations.setMachine(
data.machine,
{ transaction }
);
}
if (data.performed_by !== undefined) {
await work_order_operations.setPerformed_by(
data.performed_by,
{ transaction }
);
}
return work_order_operations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const work_order_operations = await db.work_order_operations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of work_order_operations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of work_order_operations) {
await record.destroy({transaction});
}
});
return work_order_operations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const work_order_operations = await db.work_order_operations.findByPk(id, options);
await work_order_operations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await work_order_operations.destroy({
transaction
});
return work_order_operations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const work_order_operations = await db.work_order_operations.findOne(
{ where },
{ transaction },
);
if (!work_order_operations) {
return work_order_operations;
}
const output = work_order_operations.get({plain: true});
output.work_order = await work_order_operations.getWork_order({
transaction
});
output.work_center = await work_order_operations.getWork_center({
transaction
});
output.machine = await work_order_operations.getMachine({
transaction
});
output.performed_by = await work_order_operations.getPerformed_by({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.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.work_centers,
as: 'work_center',
where: filter.work_center ? {
[Op.or]: [
{ id: { [Op.in]: filter.work_center.split('|').map(term => Utils.uuid(term)) } },
{
work_center_name: {
[Op.or]: filter.work_center.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)) } },
{
machine_name: {
[Op.or]: filter.machine.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'performed_by',
where: filter.performed_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.performed_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.performed_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.operation_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_order_operations',
'operation_name',
filter.operation_name,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_order_operations',
'notes',
filter.notes,
),
};
}
if (filter.operation_noRange) {
const [start, end] = filter.operation_noRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
operation_no: {
...where.operation_no,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
operation_no: {
...where.operation_no,
[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.ended_atRange) {
const [start, end] = filter.ended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.lte]: end,
},
};
}
}
if (filter.good_quantityRange) {
const [start, end] = filter.good_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
good_quantity: {
...where.good_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
good_quantity: {
...where.good_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.scrap_quantityRange) {
const [start, end] = filter.scrap_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scrap_quantity: {
...where.scrap_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scrap_quantity: {
...where.scrap_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.work_order_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'work_order_operations',
'operation_name',
query,
),
],
};
}
const records = await db.work_order_operations.findAll({
attributes: [ 'id', 'operation_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['operation_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.operation_name,
}));
}
};

View File

@ -0,0 +1,855 @@
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
,
status: data.status
||
null
,
planned_quantity: data.planned_quantity
||
null
,
completed_quantity: data.completed_quantity
||
null
,
scrap_quantity: data.scrap_quantity
||
null
,
scheduled_start: data.scheduled_start
||
null
,
scheduled_end: data.scheduled_end
||
null
,
released_at: data.released_at
||
null
,
completed_at: data.completed_at
||
null
,
priority: data.priority
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await work_orders.setItem( data.item || null, {
transaction,
});
await work_orders.setBom( data.bom || null, {
transaction,
});
await work_orders.setRouting( data.routing || null, {
transaction,
});
await work_orders.setCustomer( data.customer || 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
,
status: item.status
||
null
,
planned_quantity: item.planned_quantity
||
null
,
completed_quantity: item.completed_quantity
||
null
,
scrap_quantity: item.scrap_quantity
||
null
,
scheduled_start: item.scheduled_start
||
null
,
scheduled_end: item.scheduled_end
||
null
,
released_at: item.released_at
||
null
,
completed_at: item.completed_at
||
null
,
priority: item.priority
||
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 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.status !== undefined) updatePayload.status = data.status;
if (data.planned_quantity !== undefined) updatePayload.planned_quantity = data.planned_quantity;
if (data.completed_quantity !== undefined) updatePayload.completed_quantity = data.completed_quantity;
if (data.scrap_quantity !== undefined) updatePayload.scrap_quantity = data.scrap_quantity;
if (data.scheduled_start !== undefined) updatePayload.scheduled_start = data.scheduled_start;
if (data.scheduled_end !== undefined) updatePayload.scheduled_end = data.scheduled_end;
if (data.released_at !== undefined) updatePayload.released_at = data.released_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.priority !== undefined) updatePayload.priority = data.priority;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await work_orders.update(updatePayload, {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.routing !== undefined) {
await work_orders.setRouting(
data.routing,
{ transaction }
);
}
if (data.customer !== undefined) {
await work_orders.setCustomer(
data.customer,
{ 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.machine_events_work_order = await work_orders.getMachine_events_work_order({
transaction
});
output.work_order_operations_work_order = await work_orders.getWork_order_operations_work_order({
transaction
});
output.inventory_movements_work_order = await work_orders.getInventory_movements_work_order({
transaction
});
output.inspections_work_order = await work_orders.getInspections_work_order({
transaction
});
output.nonconformances_work_order = await work_orders.getNonconformances_work_order({
transaction
});
output.item = await work_orders.getItem({
transaction
});
output.bom = await work_orders.getBom({
transaction
});
output.routing = await work_orders.getRouting({
transaction
});
output.customer = await work_orders.getCustomer({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.items,
as: 'item',
where: filter.item ? {
[Op.or]: [
{ id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
{
item_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)) } },
{
bom_name: {
[Op.or]: filter.bom.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.routings,
as: 'routing',
where: filter.routing ? {
[Op.or]: [
{ id: { [Op.in]: filter.routing.split('|').map(term => Utils.uuid(term)) } },
{
routing_name: {
[Op.or]: filter.routing.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)) } },
{
customer_name: {
[Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
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.priority) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_orders',
'priority',
filter.priority,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_orders',
'notes',
filter.notes,
),
};
}
if (filter.planned_quantityRange) {
const [start, end] = filter.planned_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
planned_quantity: {
...where.planned_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
planned_quantity: {
...where.planned_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.completed_quantityRange) {
const [start, end] = filter.completed_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_quantity: {
...where.completed_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_quantity: {
...where.completed_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.scrap_quantityRange) {
const [start, end] = filter.scrap_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scrap_quantity: {
...where.scrap_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scrap_quantity: {
...where.scrap_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.scheduled_startRange) {
const [start, end] = filter.scheduled_startRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_start: {
...where.scheduled_start,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_start: {
...where.scheduled_start,
[Op.lte]: end,
},
};
}
}
if (filter.scheduled_endRange) {
const [start, end] = filter.scheduled_endRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_end: {
...where.scheduled_end,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_end: {
...where.scheduled_end,
[Op.lte]: end,
},
};
}
}
if (filter.released_atRange) {
const [start, end] = filter.released_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
released_at: {
...where.released_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
released_at: {
...where.released_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.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, ) {
let where = {};
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,149 @@
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 approved_vendors = sequelize.define(
'approved_vendors',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
supplier_item_code: {
type: DataTypes.TEXT,
},
lead_time_days: {
type: DataTypes.INTEGER,
},
last_price: {
type: DataTypes.DECIMAL,
},
preferred: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
approved_vendors.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.approved_vendors.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.approved_vendors.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.approved_vendors.belongsTo(db.users, {
as: 'createdBy',
});
db.approved_vendors.belongsTo(db.users, {
as: 'updatedBy',
});
};
return approved_vendors;
};

View File

@ -0,0 +1,172 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_logs = sequelize.define(
'audit_logs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_at: {
type: DataTypes.DATE,
},
entity_name: {
type: DataTypes.TEXT,
},
record_key: {
type: DataTypes.TEXT,
},
action: {
type: DataTypes.ENUM,
values: [
"create",
"update",
"delete",
"login",
"logout",
"export",
"import",
"approve",
"status_change"
],
},
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_logs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.audit_logs.belongsTo(db.users, {
as: 'actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.audit_logs.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_logs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_logs;
};

View File

@ -0,0 +1,160 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const bom_lines = sequelize.define(
'bom_lines',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
quantity_per: {
type: DataTypes.DECIMAL,
},
scrap_factor_ppm: {
type: DataTypes.INTEGER,
},
issue_method: {
type: DataTypes.ENUM,
values: [
"backflush",
"manual"
],
},
line_no: {
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.uoms, {
as: 'uom',
foreignKey: {
name: 'uomId',
},
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,170 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const boms = sequelize.define(
'boms',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
bom_name: {
type: DataTypes.TEXT,
},
bom_code: {
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.items, {
as: 'parent_item',
foreignKey: {
name: 'parent_itemId',
},
constraints: false,
});
db.boms.belongsTo(db.users, {
as: 'createdBy',
});
db.boms.belongsTo(db.users, {
as: 'updatedBy',
});
};
return boms;
};

View File

@ -0,0 +1,204 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const capa_actions = sequelize.define(
'capa_actions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
capa_number: {
type: DataTypes.TEXT,
},
action_type: {
type: DataTypes.ENUM,
values: [
"corrective",
"preventive"
],
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"investigating",
"implementing",
"verifying",
"closed",
"cancelled"
],
},
due_at: {
type: DataTypes.DATE,
},
closed_at: {
type: DataTypes.DATE,
},
root_cause: {
type: DataTypes.TEXT,
},
action_plan: {
type: DataTypes.TEXT,
},
effectiveness_check: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
capa_actions.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.capa_actions.belongsTo(db.nonconformances, {
as: 'nonconformance',
foreignKey: {
name: 'nonconformanceId',
},
constraints: false,
});
db.capa_actions.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.capa_actions.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.capa_actions.getTableName(),
belongsToColumn: 'attachments',
},
});
db.capa_actions.belongsTo(db.users, {
as: 'createdBy',
});
db.capa_actions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return capa_actions;
};

View File

@ -0,0 +1,153 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const customers = sequelize.define(
'customers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
customer_name: {
type: DataTypes.TEXT,
},
customer_code: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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,
});
db.customers.hasMany(db.inventory_movements, {
as: 'inventory_movements_customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
//end loop
db.customers.belongsTo(db.users, {
as: 'createdBy',
});
db.customers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return customers;
};

View File

@ -0,0 +1,152 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const disposition_codes = sequelize.define(
'disposition_codes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
disposition_name: {
type: DataTypes.TEXT,
},
disposition_code: {
type: DataTypes.TEXT,
},
category: {
type: DataTypes.ENUM,
values: [
"use_as_is",
"rework",
"repair",
"scrap",
"return_to_supplier",
"sort"
],
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
disposition_codes.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.disposition_codes.hasMany(db.nonconformances, {
as: 'nonconformances_disposition_code',
foreignKey: {
name: 'disposition_codeId',
},
constraints: false,
});
//end loop
db.disposition_codes.belongsTo(db.users, {
as: 'createdBy',
});
db.disposition_codes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return disposition_codes;
};

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,183 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const inspection_characteristics = sequelize.define(
'inspection_characteristics',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
sequence_no: {
type: DataTypes.INTEGER,
},
characteristic_name: {
type: DataTypes.TEXT,
},
data_type: {
type: DataTypes.ENUM,
values: [
"numeric",
"attribute"
],
},
target_value: {
type: DataTypes.DECIMAL,
},
lower_limit: {
type: DataTypes.DECIMAL,
},
upper_limit: {
type: DataTypes.DECIMAL,
},
unit: {
type: DataTypes.TEXT,
},
critical: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
method: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
inspection_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.inspection_characteristics.hasMany(db.inspection_results, {
as: 'inspection_results_characteristic',
foreignKey: {
name: 'characteristicId',
},
constraints: false,
});
//end loop
db.inspection_characteristics.belongsTo(db.inspection_plans, {
as: 'inspection_plan',
foreignKey: {
name: 'inspection_planId',
},
constraints: false,
});
db.inspection_characteristics.belongsTo(db.users, {
as: 'createdBy',
});
db.inspection_characteristics.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inspection_characteristics;
};

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 inspection_plans = sequelize.define(
'inspection_plans',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
plan_name: {
type: DataTypes.TEXT,
},
plan_code: {
type: DataTypes.TEXT,
},
plan_type: {
type: DataTypes.ENUM,
values: [
"incoming",
"in_process",
"final"
],
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"active",
"obsolete"
],
},
instructions: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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.inspection_plans.hasMany(db.inspection_characteristics, {
as: 'inspection_characteristics_inspection_plan',
foreignKey: {
name: 'inspection_planId',
},
constraints: false,
});
db.inspection_plans.hasMany(db.inspections, {
as: 'inspections_inspection_plan',
foreignKey: {
name: 'inspection_planId',
},
constraints: false,
});
//end loop
db.inspection_plans.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.inspection_plans.belongsTo(db.users, {
as: 'createdBy',
});
db.inspection_plans.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inspection_plans;
};

View File

@ -0,0 +1,160 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const inspection_results = sequelize.define(
'inspection_results',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
measured_value: {
type: DataTypes.DECIMAL,
},
attribute_value: {
type: DataTypes.ENUM,
values: [
"pass",
"fail",
"na"
],
},
judgement: {
type: DataTypes.ENUM,
values: [
"pass",
"fail",
"na"
],
},
comments: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
inspection_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.inspection_results.belongsTo(db.inspections, {
as: 'inspection',
foreignKey: {
name: 'inspectionId',
},
constraints: false,
});
db.inspection_results.belongsTo(db.inspection_characteristics, {
as: 'characteristic',
foreignKey: {
name: 'characteristicId',
},
constraints: false,
});
db.inspection_results.belongsTo(db.users, {
as: 'createdBy',
});
db.inspection_results.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inspection_results;
};

View File

@ -0,0 +1,236 @@
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 inspections = sequelize.define(
'inspections',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
inspection_number: {
type: DataTypes.TEXT,
},
inspection_type: {
type: DataTypes.ENUM,
values: [
"incoming",
"in_process",
"final"
],
},
inspected_at: {
type: DataTypes.DATE,
},
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,
},
);
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.inspections.hasMany(db.inspection_results, {
as: 'inspection_results_inspection',
foreignKey: {
name: 'inspectionId',
},
constraints: false,
});
db.inspections.hasMany(db.nonconformances, {
as: 'nonconformances_inspection',
foreignKey: {
name: 'inspectionId',
},
constraints: false,
});
//end loop
db.inspections.belongsTo(db.inspection_plans, {
as: 'inspection_plan',
foreignKey: {
name: 'inspection_planId',
},
constraints: false,
});
db.inspections.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.inspections.belongsTo(db.lots, {
as: 'lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.inspections.belongsTo(db.serials, {
as: 'serial',
foreignKey: {
name: 'serialId',
},
constraints: false,
});
db.inspections.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.inspections.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.inspections.belongsTo(db.users, {
as: 'inspected_by',
foreignKey: {
name: 'inspected_byId',
},
constraints: false,
});
db.inspections.hasMany(db.file, {
as: 'evidence',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.inspections.getTableName(),
belongsToColumn: 'evidence',
},
});
db.inspections.belongsTo(db.users, {
as: 'createdBy',
});
db.inspections.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inspections;
};

View File

@ -0,0 +1,152 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const inventory_balances = sequelize.define(
'inventory_balances',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
on_hand_quantity: {
type: DataTypes.DECIMAL,
},
allocated_quantity: {
type: DataTypes.DECIMAL,
},
available_quantity: {
type: DataTypes.DECIMAL,
},
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.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.inventory_balances.belongsTo(db.locations, {
as: 'location',
foreignKey: {
name: 'locationId',
},
constraints: false,
});
db.inventory_balances.belongsTo(db.lots, {
as: 'lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.inventory_balances.belongsTo(db.serials, {
as: 'serial',
foreignKey: {
name: 'serialId',
},
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,259 @@
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_movements = sequelize.define(
'inventory_movements',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
movement_number: {
type: DataTypes.TEXT,
},
movement_type: {
type: DataTypes.ENUM,
values: [
"receipt",
"issue",
"transfer",
"adjustment",
"production_output",
"scrap",
"customer_shipment",
"customer_return"
],
},
movement_at: {
type: DataTypes.DATE,
},
quantity: {
type: DataTypes.DECIMAL,
},
reference: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
inventory_movements.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_movements.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.uoms, {
as: 'uom',
foreignKey: {
name: 'uomId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.locations, {
as: 'from_location',
foreignKey: {
name: 'from_locationId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.locations, {
as: 'to_location',
foreignKey: {
name: 'to_locationId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.lots, {
as: 'lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.serials, {
as: 'serial',
foreignKey: {
name: 'serialId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.customers, {
as: 'customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.reason_codes, {
as: 'reason_code',
foreignKey: {
name: 'reason_codeId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.users, {
as: 'performed_by',
foreignKey: {
name: 'performed_byId',
},
constraints: false,
});
db.inventory_movements.hasMany(db.file, {
as: 'documents',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.inventory_movements.getTableName(),
belongsToColumn: 'documents',
},
});
db.inventory_movements.belongsTo(db.users, {
as: 'createdBy',
});
db.inventory_movements.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inventory_movements;
};

View File

@ -0,0 +1,297 @@
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,
},
item_name: {
type: DataTypes.TEXT,
},
item_code: {
type: DataTypes.TEXT,
},
item_type: {
type: DataTypes.ENUM,
values: [
"raw_material",
"component",
"subassembly",
"finished_good",
"consumable",
"packaging"
],
},
lot_tracked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
serial_tracked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
standard_cost: {
type: DataTypes.DECIMAL,
},
shelf_life_days: {
type: DataTypes.INTEGER,
},
description: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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.approved_vendors, {
as: 'approved_vendors_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
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.routings, {
as: 'routings_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.lots, {
as: 'lots_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.serials, {
as: 'serials_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_movements, {
as: 'inventory_movements_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.purchase_order_lines, {
as: 'purchase_order_lines_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.inspection_plans, {
as: 'inspection_plans_item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.items.hasMany(db.inspections, {
as: '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.uoms, {
as: 'default_uom',
foreignKey: {
name: 'default_uomId',
},
constraints: false,
});
db.items.belongsTo(db.users, {
as: 'createdBy',
});
db.items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return items;
};

View File

@ -0,0 +1,156 @@
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,
},
location_name: {
type: DataTypes.TEXT,
},
location_code: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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_movements, {
as: 'inventory_movements_from_location',
foreignKey: {
name: 'from_locationId',
},
constraints: false,
});
db.locations.hasMany(db.inventory_movements, {
as: 'inventory_movements_to_location',
foreignKey: {
name: 'to_locationId',
},
constraints: false,
});
//end loop
db.locations.belongsTo(db.warehouses, {
as: 'warehouse',
foreignKey: {
name: 'warehouseId',
},
constraints: false,
});
db.locations.belongsTo(db.locations, {
as: 'parent_location',
foreignKey: {
name: 'parent_locationId',
},
constraints: false,
});
db.locations.belongsTo(db.users, {
as: 'createdBy',
});
db.locations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return locations;
};

View File

@ -0,0 +1,211 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const lots = sequelize.define(
'lots',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
lot_number: {
type: DataTypes.TEXT,
},
manufactured_at: {
type: DataTypes.DATE,
},
expires_at: {
type: DataTypes.DATE,
},
supplier_lot_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"available",
"quarantined",
"released",
"consumed",
"scrapped",
"expired"
],
},
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.serials, {
as: 'serials_lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.lots.hasMany(db.inventory_balances, {
as: 'inventory_balances_lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.lots.hasMany(db.inventory_movements, {
as: 'inventory_movements_lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.lots.hasMany(db.inspections, {
as: '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.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.lots.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.lots.belongsTo(db.users, {
as: 'createdBy',
});
db.lots.belongsTo(db.users, {
as: 'updatedBy',
});
};
return lots;
};

View File

@ -0,0 +1,195 @@
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_events = sequelize.define(
'machine_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_type: {
type: DataTypes.ENUM,
values: [
"status_change",
"downtime",
"maintenance",
"setup",
"changeover"
],
},
status: {
type: DataTypes.ENUM,
values: [
"running",
"idle",
"down",
"maintenance",
"offline"
],
},
started_at: {
type: DataTypes.DATE,
},
ended_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
machine_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_events.belongsTo(db.machines, {
as: 'machine',
foreignKey: {
name: 'machineId',
},
constraints: false,
});
db.machine_events.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.machine_events.belongsTo(db.reason_codes, {
as: 'reason_code',
foreignKey: {
name: 'reason_codeId',
},
constraints: false,
});
db.machine_events.belongsTo(db.users, {
as: 'reported_by',
foreignKey: {
name: 'reported_byId',
},
constraints: false,
});
db.machine_events.belongsTo(db.users, {
as: 'createdBy',
});
db.machine_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return machine_events;
};

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 machines = sequelize.define(
'machines',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
machine_name: {
type: DataTypes.TEXT,
},
machine_code: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"running",
"idle",
"down",
"maintenance",
"offline"
],
},
commissioned_on: {
type: DataTypes.DATE,
},
manufacturer: {
type: DataTypes.TEXT,
},
model: {
type: DataTypes.TEXT,
},
serial_number: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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_events, {
as: 'machine_events_machine',
foreignKey: {
name: 'machineId',
},
constraints: false,
});
db.machines.hasMany(db.work_order_operations, {
as: 'work_order_operations_machine',
foreignKey: {
name: 'machineId',
},
constraints: false,
});
//end loop
db.machines.belongsTo(db.work_centers, {
as: 'work_center',
foreignKey: {
name: 'work_centerId',
},
constraints: false,
});
db.machines.belongsTo(db.users, {
as: 'createdBy',
});
db.machines.belongsTo(db.users, {
as: 'updatedBy',
});
};
return machines;
};

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 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",
"internal_audit"
],
},
severity: {
type: DataTypes.ENUM,
values: [
"minor",
"major",
"critical"
],
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"under_review",
"containment",
"capa_required",
"closed",
"void"
],
},
reported_at: {
type: DataTypes.DATE,
},
problem_description: {
type: DataTypes.TEXT,
},
containment_actions: {
type: DataTypes.TEXT,
},
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.capa_actions, {
as: 'capa_actions_nonconformance',
foreignKey: {
name: 'nonconformanceId',
},
constraints: false,
});
//end loop
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.serials, {
as: 'serial',
foreignKey: {
name: 'serialId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.inspections, {
as: 'inspection',
foreignKey: {
name: 'inspectionId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.users, {
as: 'reported_by',
foreignKey: {
name: 'reported_byId',
},
constraints: false,
});
db.nonconformances.belongsTo(db.disposition_codes, {
as: 'disposition_code',
foreignKey: {
name: 'disposition_codeId',
},
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,99 @@
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,158 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const purchase_order_lines = sequelize.define(
'purchase_order_lines',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
line_no: {
type: DataTypes.INTEGER,
},
ordered_quantity: {
type: DataTypes.DECIMAL,
},
received_quantity: {
type: DataTypes.DECIMAL,
},
unit_price: {
type: DataTypes.DECIMAL,
},
need_by: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
purchase_order_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.purchase_order_lines.belongsTo(db.purchase_orders, {
as: 'purchase_order',
foreignKey: {
name: 'purchase_orderId',
},
constraints: false,
});
db.purchase_order_lines.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.purchase_order_lines.belongsTo(db.uoms, {
as: 'uom',
foreignKey: {
name: 'uomId',
},
constraints: false,
});
db.purchase_order_lines.belongsTo(db.users, {
as: 'createdBy',
});
db.purchase_order_lines.belongsTo(db.users, {
as: 'updatedBy',
});
};
return purchase_order_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 purchase_orders = sequelize.define(
'purchase_orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
purchase_order_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"submitted",
"approved",
"partially_received",
"received",
"closed",
"cancelled"
],
},
ordered_at: {
type: DataTypes.DATE,
},
expected_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
purchase_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.purchase_orders.hasMany(db.purchase_order_lines, {
as: 'purchase_order_lines_purchase_order',
foreignKey: {
name: 'purchase_orderId',
},
constraints: false,
});
//end loop
db.purchase_orders.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.purchase_orders.belongsTo(db.users, {
as: 'created_by_user',
foreignKey: {
name: 'created_by_userId',
},
constraints: false,
});
db.purchase_orders.belongsTo(db.users, {
as: 'createdBy',
});
db.purchase_orders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return purchase_orders;
};

View File

@ -0,0 +1,157 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const reason_codes = sequelize.define(
'reason_codes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
reason_name: {
type: DataTypes.TEXT,
},
reason_code: {
type: DataTypes.TEXT,
},
category: {
type: DataTypes.ENUM,
values: [
"downtime",
"scrap",
"quality",
"inventory_adjustment",
"maintenance"
],
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
reason_codes.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.reason_codes.hasMany(db.machine_events, {
as: 'machine_events_reason_code',
foreignKey: {
name: 'reason_codeId',
},
constraints: false,
});
db.reason_codes.hasMany(db.inventory_movements, {
as: 'inventory_movements_reason_code',
foreignKey: {
name: 'reason_codeId',
},
constraints: false,
});
//end loop
db.reason_codes.belongsTo(db.users, {
as: 'createdBy',
});
db.reason_codes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reason_codes;
};

View File

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

View File

@ -0,0 +1,153 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const routing_operations = sequelize.define(
'routing_operations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
operation_no: {
type: DataTypes.INTEGER,
},
operation_name: {
type: DataTypes.TEXT,
},
setup_minutes: {
type: DataTypes.DECIMAL,
},
run_minutes_per_unit: {
type: DataTypes.DECIMAL,
},
work_instructions: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
routing_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.routing_operations.belongsTo(db.routings, {
as: 'routing',
foreignKey: {
name: 'routingId',
},
constraints: false,
});
db.routing_operations.belongsTo(db.work_centers, {
as: 'work_center',
foreignKey: {
name: 'work_centerId',
},
constraints: false,
});
db.routing_operations.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.routing_operations.getTableName(),
belongsToColumn: 'attachments',
},
});
db.routing_operations.belongsTo(db.users, {
as: 'createdBy',
});
db.routing_operations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return routing_operations;
};

View File

@ -0,0 +1,156 @@
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 routings = sequelize.define(
'routings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
routing_name: {
type: DataTypes.TEXT,
},
routing_code: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"active",
"obsolete"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
routings.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.routings.hasMany(db.routing_operations, {
as: 'routing_operations_routing',
foreignKey: {
name: 'routingId',
},
constraints: false,
});
db.routings.hasMany(db.work_orders, {
as: 'work_orders_routing',
foreignKey: {
name: 'routingId',
},
constraints: false,
});
//end loop
db.routings.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.routings.belongsTo(db.users, {
as: 'createdBy',
});
db.routings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return routings;
};

View File

@ -0,0 +1,189 @@
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 serials = sequelize.define(
'serials',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
serial_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"available",
"quarantined",
"released",
"consumed",
"scrapped",
"shipped"
],
},
manufactured_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
serials.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.serials.hasMany(db.inventory_balances, {
as: 'inventory_balances_serial',
foreignKey: {
name: 'serialId',
},
constraints: false,
});
db.serials.hasMany(db.inventory_movements, {
as: 'inventory_movements_serial',
foreignKey: {
name: 'serialId',
},
constraints: false,
});
db.serials.hasMany(db.inspections, {
as: 'inspections_serial',
foreignKey: {
name: 'serialId',
},
constraints: false,
});
db.serials.hasMany(db.nonconformances, {
as: 'nonconformances_serial',
foreignKey: {
name: 'serialId',
},
constraints: false,
});
//end loop
db.serials.belongsTo(db.items, {
as: 'item',
foreignKey: {
name: 'itemId',
},
constraints: false,
});
db.serials.belongsTo(db.lots, {
as: 'lot',
foreignKey: {
name: 'lotId',
},
constraints: false,
});
db.serials.belongsTo(db.users, {
as: 'createdBy',
});
db.serials.belongsTo(db.users, {
as: 'updatedBy',
});
};
return serials;
};

View File

@ -0,0 +1,177 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const suppliers = sequelize.define(
'suppliers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
supplier_name: {
type: DataTypes.TEXT,
},
supplier_code: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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.approved_vendors, {
as: 'approved_vendors_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.suppliers.hasMany(db.lots, {
as: 'lots_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.suppliers.hasMany(db.inventory_movements, {
as: 'inventory_movements_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.suppliers.hasMany(db.purchase_orders, {
as: 'purchase_orders_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.suppliers.hasMany(db.inspections, {
as: 'inspections_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
//end loop
db.suppliers.belongsTo(db.users, {
as: 'createdBy',
});
db.suppliers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return suppliers;
};

View File

@ -0,0 +1,155 @@
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 uoms = sequelize.define(
'uoms',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
uom_name: {
type: DataTypes.TEXT,
},
uom_code: {
type: DataTypes.TEXT,
},
base_multiplier: {
type: DataTypes.DECIMAL,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
uoms.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.uoms.hasMany(db.items, {
as: 'items_default_uom',
foreignKey: {
name: 'default_uomId',
},
constraints: false,
});
db.uoms.hasMany(db.bom_lines, {
as: 'bom_lines_uom',
foreignKey: {
name: 'uomId',
},
constraints: false,
});
db.uoms.hasMany(db.inventory_movements, {
as: 'inventory_movements_uom',
foreignKey: {
name: 'uomId',
},
constraints: false,
});
db.uoms.hasMany(db.purchase_order_lines, {
as: 'purchase_order_lines_uom',
foreignKey: {
name: 'uomId',
},
constraints: false,
});
//end loop
db.uoms.belongsTo(db.users, {
as: 'createdBy',
});
db.uoms.belongsTo(db.users, {
as: 'updatedBy',
});
};
return uoms;
};

View File

@ -0,0 +1,321 @@
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.machine_events, {
as: 'machine_events_reported_by',
foreignKey: {
name: 'reported_byId',
},
constraints: false,
});
db.users.hasMany(db.work_order_operations, {
as: 'work_order_operations_performed_by',
foreignKey: {
name: 'performed_byId',
},
constraints: false,
});
db.users.hasMany(db.inventory_movements, {
as: 'inventory_movements_performed_by',
foreignKey: {
name: 'performed_byId',
},
constraints: false,
});
db.users.hasMany(db.purchase_orders, {
as: 'purchase_orders_created_by_user',
foreignKey: {
name: 'created_by_userId',
},
constraints: false,
});
db.users.hasMany(db.inspections, {
as: 'inspections_inspected_by',
foreignKey: {
name: 'inspected_byId',
},
constraints: false,
});
db.users.hasMany(db.nonconformances, {
as: 'nonconformances_reported_by',
foreignKey: {
name: 'reported_byId',
},
constraints: false,
});
db.users.hasMany(db.capa_actions, {
as: 'capa_actions_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.audit_logs, {
as: 'audit_logs_actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

View File

@ -0,0 +1,131 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const warehouses = sequelize.define(
'warehouses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
warehouse_name: {
type: DataTypes.TEXT,
},
warehouse_code: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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.users, {
as: 'createdBy',
});
db.warehouses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return warehouses;
};

View File

@ -0,0 +1,154 @@
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_centers = sequelize.define(
'work_centers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
work_center_name: {
type: DataTypes.TEXT,
},
work_center_code: {
type: DataTypes.TEXT,
},
default_labor_rate: {
type: DataTypes.DECIMAL,
},
default_machine_rate: {
type: DataTypes.DECIMAL,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
work_centers.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_centers.hasMany(db.routing_operations, {
as: 'routing_operations_work_center',
foreignKey: {
name: 'work_centerId',
},
constraints: false,
});
db.work_centers.hasMany(db.machines, {
as: 'machines_work_center',
foreignKey: {
name: 'work_centerId',
},
constraints: false,
});
db.work_centers.hasMany(db.work_order_operations, {
as: 'work_order_operations_work_center',
foreignKey: {
name: 'work_centerId',
},
constraints: false,
});
//end loop
db.work_centers.belongsTo(db.users, {
as: 'createdBy',
});
db.work_centers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return work_centers;
};

View File

@ -0,0 +1,201 @@
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_order_operations = sequelize.define(
'work_order_operations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
operation_no: {
type: DataTypes.INTEGER,
},
operation_name: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"ready",
"in_progress",
"paused",
"done",
"skipped"
],
},
started_at: {
type: DataTypes.DATE,
},
ended_at: {
type: DataTypes.DATE,
},
good_quantity: {
type: DataTypes.DECIMAL,
},
scrap_quantity: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
work_order_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.work_order_operations.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.work_order_operations.belongsTo(db.work_centers, {
as: 'work_center',
foreignKey: {
name: 'work_centerId',
},
constraints: false,
});
db.work_order_operations.belongsTo(db.machines, {
as: 'machine',
foreignKey: {
name: 'machineId',
},
constraints: false,
});
db.work_order_operations.belongsTo(db.users, {
as: 'performed_by',
foreignKey: {
name: 'performed_byId',
},
constraints: false,
});
db.work_order_operations.belongsTo(db.users, {
as: 'createdBy',
});
db.work_order_operations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return work_order_operations;
};

View File

@ -0,0 +1,265 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const work_orders = sequelize.define(
'work_orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
work_order_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"planned",
"released",
"in_progress",
"on_hold",
"completed",
"closed",
"cancelled"
],
},
planned_quantity: {
type: DataTypes.DECIMAL,
},
completed_quantity: {
type: DataTypes.DECIMAL,
},
scrap_quantity: {
type: DataTypes.DECIMAL,
},
scheduled_start: {
type: DataTypes.DATE,
},
scheduled_end: {
type: DataTypes.DATE,
},
released_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
priority: {
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.machine_events, {
as: 'machine_events_work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.work_orders.hasMany(db.work_order_operations, {
as: 'work_order_operations_work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.work_orders.hasMany(db.inventory_movements, {
as: 'inventory_movements_work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.work_orders.hasMany(db.inspections, {
as: '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.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.routings, {
as: 'routing',
foreignKey: {
name: 'routingId',
},
constraints: false,
});
db.work_orders.belongsTo(db.customers, {
as: 'customer',
foreignKey: {
name: 'customerId',
},
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,66 @@
'use strict';
const bcrypt = require("bcrypt");
const config = require("../../config");
const ids = [
'193bf4b5-9f07-4bd5-9a43-e7e41f3e96af',
'af5a87be-8f9c-4630-902a-37a60b7005ba',
'5bc531ab-611f-41f3-9373-b7cc5d09c93d',
]
module.exports = {
up: async (queryInterface, Sequelize) => {
let admin_hash = bcrypt.hashSync(config.admin_pass, config.bcrypt.saltRounds);
let user_hash = bcrypt.hashSync(config.user_pass, config.bcrypt.saltRounds);
try {
await queryInterface.bulkInsert('users', [
{
id: ids[0],
firstName: 'Admin',
email: config.admin_email,
emailVerified: true,
provider: config.providers.LOCAL,
password: admin_hash,
createdAt: new Date(),
updatedAt: new Date()
},
{
id: ids[1],
firstName: 'John',
email: 'john@doe.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: user_hash,
createdAt: new Date(),
updatedAt: new Date()
},
{
id: ids[2],
firstName: 'Client',
email: 'client@hello.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: user_hash,
createdAt: new Date(),
updatedAt: new Date()
},
]);
} catch (error) {
console.error('Error during bulkInsert:', error);
throw error;
}
},
down: async (queryInterface, Sequelize) => {
try {
await queryInterface.bulkDelete('users', {
id: {
[Sequelize.Op.in]: ids,
},
}, {});
} catch (error) {
console.error('Error during bulkDelete:', error);
throw error;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

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

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

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

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