Initial version

This commit is contained in:
Flatlogic Bot 2026-05-10 18:34:32 +00:00
commit 20700117f2
721 changed files with 266519 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>WWF-DRC ProcureFlow v2</h2>
<p>Plateforme multi-tenant de gestion des achats: requisitions, validations, sourcing, reception, archives et audit.</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 @@
# WWF-DRC ProcureFlow v2
## 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 @@
#WWF-DRC ProcureFlow v2 - 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_wwf_drc_procureflow_v2;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_wwf_drc_procureflow_v2 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": "wwfdrcprocureflowv2",
"description": "WWF-DRC ProcureFlow v2 - template backend",
"scripts": {
"start": "npm run db:migrate && npm run db:seed && npm run watch",
"lint": "eslint . --ext .js",
"db:migrate": "sequelize-cli db:migrate",
"db:seed": "sequelize-cli db:seed:all",
"db:drop": "sequelize-cli db:drop",
"db:create": "sequelize-cli db:create",
"watch": "node watcher.js"
},
"dependencies": {
"@google-cloud/storage": "^5.18.2",
"axios": "^1.6.7",
"bcrypt": "5.1.1",
"chokidar": "^4.0.3",
"cors": "2.8.5",
"csv-parser": "^3.0.0",
"express": "4.18.2",
"formidable": "1.2.2",
"helmet": "4.1.1",
"json2csv": "^5.0.7",
"jsonwebtoken": "8.5.1",
"lodash": "4.17.21",
"moment": "2.30.1",
"multer": "^1.4.4",
"mysql2": "2.2.5",
"nodemailer": "6.9.9",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
"passport-jwt": "^4.0.1",
"passport-microsoft": "^0.1.0",
"pg": "8.4.1",
"pg-hstore": "2.3.4",
"sequelize": "6.35.2",
"sequelize-json-schema": "^2.1.1",
"sqlite": "4.0.15",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0",
"tedious": "^18.2.4"
},
"engines": {
"node": ">=18"
},
"private": true,
"devDependencies": {
"cross-env": "7.0.3",
"eslint": "^8.23.1",
"eslint-plugin-import": "^2.29.1",
"mocha": "8.1.3",
"node-mocks-http": "1.9.0",
"nodemon": "2.0.5",
"sequelize-cli": "6.6.2"
}
}

View File

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

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

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

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

@ -0,0 +1,81 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "09f479bd",
user_pass: "87027312d8b1",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '09f479bd-250b-4cf8-a5fe-87027312d8b1',
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: 'WWF-DRC ProcureFlow v2 <app@flatlogic.app>',
host: 'email-smtp.us-east-1.amazonaws.com',
port: 587,
auth: {
user: process.env.EMAIL_USER || '',
pass: process.env.EMAIL_PASS,
},
tls: {
rejectUnauthorized: false
}
},
roles: {
super_admin: 'Super Administrator',
admin: 'Administrator',
user: 'Audit Viewer',
},
project_uuid: '09f479bd-250b-4cf8-a5fe-87027312d8b1',
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 = 'River journey through forest';
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,612 @@
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 Access_logsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const access_logs = await db.access_logs.create(
{
id: data.id || undefined,
action: data.action
||
null
,
resource_type: data.resource_type
||
null
,
resource_reference: data.resource_reference
||
null
,
ip_address: data.ip_address
||
null
,
user_agent: data.user_agent
||
null
,
occurred_at: data.occurred_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await access_logs.setTenant( data.tenant || null, {
transaction,
});
await access_logs.setUser( data.user || null, {
transaction,
});
await access_logs.setOrganizations( data.organizations || null, {
transaction,
});
return access_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 access_logsData = data.map((item, index) => ({
id: item.id || undefined,
action: item.action
||
null
,
resource_type: item.resource_type
||
null
,
resource_reference: item.resource_reference
||
null
,
ip_address: item.ip_address
||
null
,
user_agent: item.user_agent
||
null
,
occurred_at: item.occurred_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const access_logs = await db.access_logs.bulkCreate(access_logsData, { transaction });
// For each item created, replace relation files
return access_logs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const access_logs = await db.access_logs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.action !== undefined) updatePayload.action = data.action;
if (data.resource_type !== undefined) updatePayload.resource_type = data.resource_type;
if (data.resource_reference !== undefined) updatePayload.resource_reference = data.resource_reference;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
updatePayload.updatedById = currentUser.id;
await access_logs.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await access_logs.setTenant(
data.tenant,
{ transaction }
);
}
if (data.user !== undefined) {
await access_logs.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await access_logs.setOrganizations(
data.organizations,
{ transaction }
);
}
return access_logs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const access_logs = await db.access_logs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of access_logs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of access_logs) {
await record.destroy({transaction});
}
});
return access_logs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const access_logs = await db.access_logs.findByPk(id, options);
await access_logs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await access_logs.destroy({
transaction
});
return access_logs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const access_logs = await db.access_logs.findOne(
{ where },
{ transaction },
);
if (!access_logs) {
return access_logs;
}
const output = access_logs.get({plain: true});
output.tenant = await access_logs.getTenant({
transaction
});
output.user = await access_logs.getUser({
transaction
});
output.organizations = await access_logs.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.resource_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'access_logs',
'resource_reference',
filter.resource_reference,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'access_logs',
'ip_address',
filter.ip_address,
),
};
}
if (filter.user_agent) {
where = {
...where,
[Op.and]: Utils.ilike(
'access_logs',
'user_agent',
filter.user_agent,
),
};
}
if (filter.occurred_atRange) {
const [start, end] = filter.occurred_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.action) {
where = {
...where,
action: filter.action,
};
}
if (filter.resource_type) {
where = {
...where,
resource_type: filter.resource_type,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.access_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'access_logs',
'action',
query,
),
],
};
}
const records = await db.access_logs.findAll({
attributes: [ 'id', 'action' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['action', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.action,
}));
}
};

View File

@ -0,0 +1,697 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Approval_stepsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.create(
{
id: data.id || undefined,
level: data.level
||
null
,
decision: data.decision
||
null
,
comment: data.comment
||
null
,
assigned_at: data.assigned_at
||
null
,
decided_at: data.decided_at
||
null
,
sla_due_at: data.sla_due_at
||
null
,
sla_breached: data.sla_breached
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await approval_steps.setTenant( data.tenant || null, {
transaction,
});
await approval_steps.setRequisition( data.requisition || null, {
transaction,
});
await approval_steps.setAssigned_approver( data.assigned_approver || null, {
transaction,
});
await approval_steps.setOrganizations( data.organizations || null, {
transaction,
});
return approval_steps;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const approval_stepsData = data.map((item, index) => ({
id: item.id || undefined,
level: item.level
||
null
,
decision: item.decision
||
null
,
comment: item.comment
||
null
,
assigned_at: item.assigned_at
||
null
,
decided_at: item.decided_at
||
null
,
sla_due_at: item.sla_due_at
||
null
,
sla_breached: item.sla_breached
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const approval_steps = await db.approval_steps.bulkCreate(approval_stepsData, { transaction });
// For each item created, replace relation files
return approval_steps;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const approval_steps = await db.approval_steps.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.level !== undefined) updatePayload.level = data.level;
if (data.decision !== undefined) updatePayload.decision = data.decision;
if (data.comment !== undefined) updatePayload.comment = data.comment;
if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
if (data.decided_at !== undefined) updatePayload.decided_at = data.decided_at;
if (data.sla_due_at !== undefined) updatePayload.sla_due_at = data.sla_due_at;
if (data.sla_breached !== undefined) updatePayload.sla_breached = data.sla_breached;
updatePayload.updatedById = currentUser.id;
await approval_steps.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await approval_steps.setTenant(
data.tenant,
{ transaction }
);
}
if (data.requisition !== undefined) {
await approval_steps.setRequisition(
data.requisition,
{ transaction }
);
}
if (data.assigned_approver !== undefined) {
await approval_steps.setAssigned_approver(
data.assigned_approver,
{ transaction }
);
}
if (data.organizations !== undefined) {
await approval_steps.setOrganizations(
data.organizations,
{ transaction }
);
}
return approval_steps;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of approval_steps) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of approval_steps) {
await record.destroy({transaction});
}
});
return approval_steps;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.findByPk(id, options);
await approval_steps.update({
deletedBy: currentUser.id
}, {
transaction,
});
await approval_steps.destroy({
transaction
});
return approval_steps;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.findOne(
{ where },
{ transaction },
);
if (!approval_steps) {
return approval_steps;
}
const output = approval_steps.get({plain: true});
output.tenant = await approval_steps.getTenant({
transaction
});
output.requisition = await approval_steps.getRequisition({
transaction
});
output.assigned_approver = await approval_steps.getAssigned_approver({
transaction
});
output.organizations = await approval_steps.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.requisitions,
as: 'requisition',
where: filter.requisition ? {
[Op.or]: [
{ id: { [Op.in]: filter.requisition.split('|').map(term => Utils.uuid(term)) } },
{
req_number: {
[Op.or]: filter.requisition.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assigned_approver',
where: filter.assigned_approver ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_approver.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assigned_approver.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.comment) {
where = {
...where,
[Op.and]: Utils.ilike(
'approval_steps',
'comment',
filter.comment,
),
};
}
if (filter.assigned_atRange) {
const [start, end] = filter.assigned_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.lte]: end,
},
};
}
}
if (filter.decided_atRange) {
const [start, end] = filter.decided_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
decided_at: {
...where.decided_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
decided_at: {
...where.decided_at,
[Op.lte]: end,
},
};
}
}
if (filter.sla_due_atRange) {
const [start, end] = filter.sla_due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sla_due_at: {
...where.sla_due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sla_due_at: {
...where.sla_due_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.level) {
where = {
...where,
level: filter.level,
};
}
if (filter.decision) {
where = {
...where,
decision: filter.decision,
};
}
if (filter.sla_breached) {
where = {
...where,
sla_breached: filter.sla_breached,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.approval_steps.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'approval_steps',
'level',
query,
),
],
};
}
const records = await db.approval_steps.findAll({
attributes: [ 'id', 'level' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['level', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.level,
}));
}
};

View File

@ -0,0 +1,711 @@
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 Archive_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const archive_items = await db.archive_items.create(
{
id: data.id || undefined,
resource_type: data.resource_type
||
null
,
resource_reference: data.resource_reference
||
null
,
visibility_scope: data.visibility_scope
||
null
,
title: data.title
||
null
,
keywords: data.keywords
||
null
,
amount_usd: data.amount_usd
||
null
,
status: data.status
||
null
,
archived_at: data.archived_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await archive_items.setTenant( data.tenant || null, {
transaction,
});
await archive_items.setArchived_by( data.archived_by || null, {
transaction,
});
await archive_items.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.archive_items.getTableName(),
belongsToColumn: 'files',
belongsToId: archive_items.id,
},
data.files,
options,
);
return archive_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 archive_itemsData = data.map((item, index) => ({
id: item.id || undefined,
resource_type: item.resource_type
||
null
,
resource_reference: item.resource_reference
||
null
,
visibility_scope: item.visibility_scope
||
null
,
title: item.title
||
null
,
keywords: item.keywords
||
null
,
amount_usd: item.amount_usd
||
null
,
status: item.status
||
null
,
archived_at: item.archived_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const archive_items = await db.archive_items.bulkCreate(archive_itemsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < archive_items.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.archive_items.getTableName(),
belongsToColumn: 'files',
belongsToId: archive_items[i].id,
},
data[i].files,
options,
);
}
return archive_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const archive_items = await db.archive_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.resource_type !== undefined) updatePayload.resource_type = data.resource_type;
if (data.resource_reference !== undefined) updatePayload.resource_reference = data.resource_reference;
if (data.visibility_scope !== undefined) updatePayload.visibility_scope = data.visibility_scope;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.keywords !== undefined) updatePayload.keywords = data.keywords;
if (data.amount_usd !== undefined) updatePayload.amount_usd = data.amount_usd;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.archived_at !== undefined) updatePayload.archived_at = data.archived_at;
updatePayload.updatedById = currentUser.id;
await archive_items.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await archive_items.setTenant(
data.tenant,
{ transaction }
);
}
if (data.archived_by !== undefined) {
await archive_items.setArchived_by(
data.archived_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await archive_items.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.archive_items.getTableName(),
belongsToColumn: 'files',
belongsToId: archive_items.id,
},
data.files,
options,
);
return archive_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const archive_items = await db.archive_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of archive_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of archive_items) {
await record.destroy({transaction});
}
});
return archive_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const archive_items = await db.archive_items.findByPk(id, options);
await archive_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await archive_items.destroy({
transaction
});
return archive_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const archive_items = await db.archive_items.findOne(
{ where },
{ transaction },
);
if (!archive_items) {
return archive_items;
}
const output = archive_items.get({plain: true});
output.tenant = await archive_items.getTenant({
transaction
});
output.archived_by = await archive_items.getArchived_by({
transaction
});
output.files = await archive_items.getFiles({
transaction
});
output.organizations = await archive_items.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'archived_by',
where: filter.archived_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.archived_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.archived_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.resource_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'archive_items',
'resource_reference',
filter.resource_reference,
),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'archive_items',
'title',
filter.title,
),
};
}
if (filter.keywords) {
where = {
...where,
[Op.and]: Utils.ilike(
'archive_items',
'keywords',
filter.keywords,
),
};
}
if (filter.amount_usdRange) {
const [start, end] = filter.amount_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount_usd: {
...where.amount_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount_usd: {
...where.amount_usd,
[Op.lte]: end,
},
};
}
}
if (filter.archived_atRange) {
const [start, end] = filter.archived_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
archived_at: {
...where.archived_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
archived_at: {
...where.archived_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.resource_type) {
where = {
...where,
resource_type: filter.resource_type,
};
}
if (filter.visibility_scope) {
where = {
...where,
visibility_scope: filter.visibility_scope,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.archive_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'archive_items',
'title',
query,
),
],
};
}
const records = await db.archive_items.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,684 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Audit_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.create(
{
id: data.id || undefined,
event_id: data.event_id
||
null
,
occurred_at: data.occurred_at
||
null
,
event_type: data.event_type
||
null
,
resource_type: data.resource_type
||
null
,
resource_reference: data.resource_reference
||
null
,
summary: data.summary
||
null
,
ip_address: data.ip_address
||
null
,
integrity_hash: data.integrity_hash
||
null
,
previous_hash: data.previous_hash
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audit_events.setTenant( data.tenant || null, {
transaction,
});
await audit_events.setActor( data.actor || null, {
transaction,
});
await audit_events.setOrganizations( data.organizations || null, {
transaction,
});
return audit_events;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const audit_eventsData = data.map((item, index) => ({
id: item.id || undefined,
event_id: item.event_id
||
null
,
occurred_at: item.occurred_at
||
null
,
event_type: item.event_type
||
null
,
resource_type: item.resource_type
||
null
,
resource_reference: item.resource_reference
||
null
,
summary: item.summary
||
null
,
ip_address: item.ip_address
||
null
,
integrity_hash: item.integrity_hash
||
null
,
previous_hash: item.previous_hash
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const audit_events = await db.audit_events.bulkCreate(audit_eventsData, { transaction });
// For each item created, replace relation files
return audit_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const audit_events = await db.audit_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.event_id !== undefined) updatePayload.event_id = data.event_id;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
if (data.resource_type !== undefined) updatePayload.resource_type = data.resource_type;
if (data.resource_reference !== undefined) updatePayload.resource_reference = data.resource_reference;
if (data.summary !== undefined) updatePayload.summary = data.summary;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
if (data.integrity_hash !== undefined) updatePayload.integrity_hash = data.integrity_hash;
if (data.previous_hash !== undefined) updatePayload.previous_hash = data.previous_hash;
updatePayload.updatedById = currentUser.id;
await audit_events.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await audit_events.setTenant(
data.tenant,
{ transaction }
);
}
if (data.actor !== undefined) {
await audit_events.setActor(
data.actor,
{ transaction }
);
}
if (data.organizations !== undefined) {
await audit_events.setOrganizations(
data.organizations,
{ transaction }
);
}
return audit_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of audit_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of audit_events) {
await record.destroy({transaction});
}
});
return audit_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findByPk(id, options);
await audit_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await audit_events.destroy({
transaction
});
return audit_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findOne(
{ where },
{ transaction },
);
if (!audit_events) {
return audit_events;
}
const output = audit_events.get({plain: true});
output.tenant = await audit_events.getTenant({
transaction
});
output.actor = await audit_events.getActor({
transaction
});
output.organizations = await audit_events.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
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}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.event_id) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'event_id',
filter.event_id,
),
};
}
if (filter.resource_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'resource_reference',
filter.resource_reference,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'summary',
filter.summary,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'ip_address',
filter.ip_address,
),
};
}
if (filter.integrity_hash) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'integrity_hash',
filter.integrity_hash,
),
};
}
if (filter.previous_hash) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'previous_hash',
filter.previous_hash,
),
};
}
if (filter.occurred_atRange) {
const [start, end] = filter.occurred_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.event_type) {
where = {
...where,
event_type: filter.event_type,
};
}
if (filter.resource_type) {
where = {
...where,
resource_type: filter.resource_type,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.audit_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'audit_events',
'event_id',
query,
),
],
};
}
const records = await db.audit_events.findAll({
attributes: [ 'id', 'event_id' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['event_id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.event_id,
}));
}
};

View File

@ -0,0 +1,714 @@
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 AwardsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const awards = await db.awards.create(
{
id: data.id || undefined,
awarded_amount_usd: data.awarded_amount_usd
||
null
,
award_rationale: data.award_rationale
||
null
,
awarded_at: data.awarded_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await awards.setTenant( data.tenant || null, {
transaction,
});
await awards.setProcurement_case( data.procurement_case || null, {
transaction,
});
await awards.setWinning_offer( data.winning_offer || null, {
transaction,
});
await awards.setAwarded_supplier( data.awarded_supplier || null, {
transaction,
});
await awards.setAwarded_by( data.awarded_by || null, {
transaction,
});
await awards.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.awards.getTableName(),
belongsToColumn: 'award_documents',
belongsToId: awards.id,
},
data.award_documents,
options,
);
return awards;
}
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 awardsData = data.map((item, index) => ({
id: item.id || undefined,
awarded_amount_usd: item.awarded_amount_usd
||
null
,
award_rationale: item.award_rationale
||
null
,
awarded_at: item.awarded_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const awards = await db.awards.bulkCreate(awardsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < awards.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.awards.getTableName(),
belongsToColumn: 'award_documents',
belongsToId: awards[i].id,
},
data[i].award_documents,
options,
);
}
return awards;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const awards = await db.awards.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.awarded_amount_usd !== undefined) updatePayload.awarded_amount_usd = data.awarded_amount_usd;
if (data.award_rationale !== undefined) updatePayload.award_rationale = data.award_rationale;
if (data.awarded_at !== undefined) updatePayload.awarded_at = data.awarded_at;
updatePayload.updatedById = currentUser.id;
await awards.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await awards.setTenant(
data.tenant,
{ transaction }
);
}
if (data.procurement_case !== undefined) {
await awards.setProcurement_case(
data.procurement_case,
{ transaction }
);
}
if (data.winning_offer !== undefined) {
await awards.setWinning_offer(
data.winning_offer,
{ transaction }
);
}
if (data.awarded_supplier !== undefined) {
await awards.setAwarded_supplier(
data.awarded_supplier,
{ transaction }
);
}
if (data.awarded_by !== undefined) {
await awards.setAwarded_by(
data.awarded_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await awards.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.awards.getTableName(),
belongsToColumn: 'award_documents',
belongsToId: awards.id,
},
data.award_documents,
options,
);
return awards;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const awards = await db.awards.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of awards) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of awards) {
await record.destroy({transaction});
}
});
return awards;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const awards = await db.awards.findByPk(id, options);
await awards.update({
deletedBy: currentUser.id
}, {
transaction,
});
await awards.destroy({
transaction
});
return awards;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const awards = await db.awards.findOne(
{ where },
{ transaction },
);
if (!awards) {
return awards;
}
const output = awards.get({plain: true});
output.tenant = await awards.getTenant({
transaction
});
output.procurement_case = await awards.getProcurement_case({
transaction
});
output.winning_offer = await awards.getWinning_offer({
transaction
});
output.awarded_supplier = await awards.getAwarded_supplier({
transaction
});
output.awarded_by = await awards.getAwarded_by({
transaction
});
output.award_documents = await awards.getAward_documents({
transaction
});
output.organizations = await awards.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.procurement_cases,
as: 'procurement_case',
where: filter.procurement_case ? {
[Op.or]: [
{ id: { [Op.in]: filter.procurement_case.split('|').map(term => Utils.uuid(term)) } },
{
pipeline_stage: {
[Op.or]: filter.procurement_case.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.supplier_offers,
as: 'winning_offer',
where: filter.winning_offer ? {
[Op.or]: [
{ id: { [Op.in]: filter.winning_offer.split('|').map(term => Utils.uuid(term)) } },
{
status: {
[Op.or]: filter.winning_offer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.suppliers,
as: 'awarded_supplier',
where: filter.awarded_supplier ? {
[Op.or]: [
{ id: { [Op.in]: filter.awarded_supplier.split('|').map(term => Utils.uuid(term)) } },
{
legal_name: {
[Op.or]: filter.awarded_supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'awarded_by',
where: filter.awarded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.awarded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.awarded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'award_documents',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.award_rationale) {
where = {
...where,
[Op.and]: Utils.ilike(
'awards',
'award_rationale',
filter.award_rationale,
),
};
}
if (filter.awarded_amount_usdRange) {
const [start, end] = filter.awarded_amount_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
awarded_amount_usd: {
...where.awarded_amount_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
awarded_amount_usd: {
...where.awarded_amount_usd,
[Op.lte]: end,
},
};
}
}
if (filter.awarded_atRange) {
const [start, end] = filter.awarded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
awarded_at: {
...where.awarded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
awarded_at: {
...where.awarded_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.awards.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'awards',
'award_rationale',
query,
),
],
};
}
const records = await db.awards.findAll({
attributes: [ 'id', 'award_rationale' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['award_rationale', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.award_rationale,
}));
}
};

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 Bid_criteriaDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bid_criteria = await db.bid_criteria.create(
{
id: data.id || undefined,
name: data.name
||
null
,
weight: data.weight
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await bid_criteria.setTenant( data.tenant || null, {
transaction,
});
await bid_criteria.setProcurement_case( data.procurement_case || null, {
transaction,
});
await bid_criteria.setOrganizations( data.organizations || null, {
transaction,
});
return bid_criteria;
}
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 bid_criteriaData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
weight: item.weight
||
null
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const bid_criteria = await db.bid_criteria.bulkCreate(bid_criteriaData, { transaction });
// For each item created, replace relation files
return bid_criteria;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const bid_criteria = await db.bid_criteria.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.weight !== undefined) updatePayload.weight = data.weight;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await bid_criteria.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await bid_criteria.setTenant(
data.tenant,
{ transaction }
);
}
if (data.procurement_case !== undefined) {
await bid_criteria.setProcurement_case(
data.procurement_case,
{ transaction }
);
}
if (data.organizations !== undefined) {
await bid_criteria.setOrganizations(
data.organizations,
{ transaction }
);
}
return bid_criteria;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bid_criteria = await db.bid_criteria.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of bid_criteria) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of bid_criteria) {
await record.destroy({transaction});
}
});
return bid_criteria;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const bid_criteria = await db.bid_criteria.findByPk(id, options);
await bid_criteria.update({
deletedBy: currentUser.id
}, {
transaction,
});
await bid_criteria.destroy({
transaction
});
return bid_criteria;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const bid_criteria = await db.bid_criteria.findOne(
{ where },
{ transaction },
);
if (!bid_criteria) {
return bid_criteria;
}
const output = bid_criteria.get({plain: true});
output.offer_scores_bid_criterion = await bid_criteria.getOffer_scores_bid_criterion({
transaction
});
output.tenant = await bid_criteria.getTenant({
transaction
});
output.procurement_case = await bid_criteria.getProcurement_case({
transaction
});
output.organizations = await bid_criteria.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.procurement_cases,
as: 'procurement_case',
where: filter.procurement_case ? {
[Op.or]: [
{ id: { [Op.in]: filter.procurement_case.split('|').map(term => Utils.uuid(term)) } },
{
pipeline_stage: {
[Op.or]: filter.procurement_case.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'bid_criteria',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'bid_criteria',
'description',
filter.description,
),
};
}
if (filter.weightRange) {
const [start, end] = filter.weightRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
weight: {
...where.weight,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
weight: {
...where.weight,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.bid_criteria.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'bid_criteria',
'name',
query,
),
],
};
}
const records = await db.bid_criteria.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,500 @@
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 Budget_linesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const budget_lines = await db.budget_lines.create(
{
id: data.id || undefined,
code: data.code
||
null
,
name: data.name
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await budget_lines.setTenant( data.tenant || null, {
transaction,
});
await budget_lines.setOrganizations( data.organizations || null, {
transaction,
});
return budget_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 budget_linesData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
name: item.name
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const budget_lines = await db.budget_lines.bulkCreate(budget_linesData, { transaction });
// For each item created, replace relation files
return budget_lines;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const budget_lines = await db.budget_lines.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await budget_lines.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await budget_lines.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await budget_lines.setOrganizations(
data.organizations,
{ transaction }
);
}
return budget_lines;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const budget_lines = await db.budget_lines.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of budget_lines) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of budget_lines) {
await record.destroy({transaction});
}
});
return budget_lines;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const budget_lines = await db.budget_lines.findByPk(id, options);
await budget_lines.update({
deletedBy: currentUser.id
}, {
transaction,
});
await budget_lines.destroy({
transaction
});
return budget_lines;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const budget_lines = await db.budget_lines.findOne(
{ where },
{ transaction },
);
if (!budget_lines) {
return budget_lines;
}
const output = budget_lines.get({plain: true});
output.requisitions_budget_line = await budget_lines.getRequisitions_budget_line({
transaction
});
output.tenant = await budget_lines.getTenant({
transaction
});
output.organizations = await budget_lines.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'budget_lines',
'code',
filter.code,
),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'budget_lines',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.budget_lines.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'budget_lines',
'name',
query,
),
],
};
}
const records = await db.budget_lines.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,540 @@
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 Currency_ratesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const currency_rates = await db.currency_rates.create(
{
id: data.id || undefined,
base_currency: data.base_currency
||
null
,
quote_currency: data.quote_currency
||
null
,
rate: data.rate
||
null
,
effective_at: data.effective_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await currency_rates.setTenant( data.tenant || null, {
transaction,
});
await currency_rates.setOrganizations( data.organizations || null, {
transaction,
});
return currency_rates;
}
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 currency_ratesData = data.map((item, index) => ({
id: item.id || undefined,
base_currency: item.base_currency
||
null
,
quote_currency: item.quote_currency
||
null
,
rate: item.rate
||
null
,
effective_at: item.effective_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const currency_rates = await db.currency_rates.bulkCreate(currency_ratesData, { transaction });
// For each item created, replace relation files
return currency_rates;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const currency_rates = await db.currency_rates.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.base_currency !== undefined) updatePayload.base_currency = data.base_currency;
if (data.quote_currency !== undefined) updatePayload.quote_currency = data.quote_currency;
if (data.rate !== undefined) updatePayload.rate = data.rate;
if (data.effective_at !== undefined) updatePayload.effective_at = data.effective_at;
updatePayload.updatedById = currentUser.id;
await currency_rates.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await currency_rates.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await currency_rates.setOrganizations(
data.organizations,
{ transaction }
);
}
return currency_rates;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const currency_rates = await db.currency_rates.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of currency_rates) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of currency_rates) {
await record.destroy({transaction});
}
});
return currency_rates;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const currency_rates = await db.currency_rates.findByPk(id, options);
await currency_rates.update({
deletedBy: currentUser.id
}, {
transaction,
});
await currency_rates.destroy({
transaction
});
return currency_rates;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const currency_rates = await db.currency_rates.findOne(
{ where },
{ transaction },
);
if (!currency_rates) {
return currency_rates;
}
const output = currency_rates.get({plain: true});
output.tenant = await currency_rates.getTenant({
transaction
});
output.organizations = await currency_rates.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.rateRange) {
const [start, end] = filter.rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rate: {
...where.rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rate: {
...where.rate,
[Op.lte]: end,
},
};
}
}
if (filter.effective_atRange) {
const [start, end] = filter.effective_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_at: {
...where.effective_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_at: {
...where.effective_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.base_currency) {
where = {
...where,
base_currency: filter.base_currency,
};
}
if (filter.quote_currency) {
where = {
...where,
quote_currency: filter.quote_currency,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.currency_rates.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'currency_rates',
'base_currency',
query,
),
],
};
}
const records = await db.currency_rates.findAll({
attributes: [ 'id', 'base_currency' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['base_currency', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.base_currency,
}));
}
};

View File

@ -0,0 +1,504 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class DepartmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.create(
{
id: data.id || undefined,
code: data.code
||
null
,
name: data.name
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await departments.setTenant( data.tenant || null, {
transaction,
});
await departments.setOrganizations( data.organizations || null, {
transaction,
});
return departments;
}
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 departmentsData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
name: item.name
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const departments = await db.departments.bulkCreate(departmentsData, { transaction });
// For each item created, replace relation files
return departments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const departments = await db.departments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await departments.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await departments.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await departments.setOrganizations(
data.organizations,
{ transaction }
);
}
return departments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of departments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of departments) {
await record.destroy({transaction});
}
});
return departments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.findByPk(id, options);
await departments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await departments.destroy({
transaction
});
return departments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.findOne(
{ where },
{ transaction },
);
if (!departments) {
return departments;
}
const output = departments.get({plain: true});
output.projects_department = await departments.getProjects_department({
transaction
});
output.requisitions_department = await departments.getRequisitions_department({
transaction
});
output.tenant = await departments.getTenant({
transaction
});
output.organizations = await departments.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'departments',
'code',
filter.code,
),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'departments',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.departments.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'departments',
'name',
query,
),
],
};
}
const records = await db.departments.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,741 @@
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 Discrepancy_casesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const discrepancy_cases = await db.discrepancy_cases.create(
{
id: data.id || undefined,
type: data.type
||
null
,
description: data.description
||
null
,
status: data.status
||
null
,
reported_at: data.reported_at
||
null
,
resolved_at: data.resolved_at
||
null
,
resolution_notes: data.resolution_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await discrepancy_cases.setTenant( data.tenant || null, {
transaction,
});
await discrepancy_cases.setPurchase_order( data.purchase_order || null, {
transaction,
});
await discrepancy_cases.setGoods_receipt_note( data.goods_receipt_note || null, {
transaction,
});
await discrepancy_cases.setReported_by( data.reported_by || null, {
transaction,
});
await discrepancy_cases.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.discrepancy_cases.getTableName(),
belongsToColumn: 'photos',
belongsToId: discrepancy_cases.id,
},
data.photos,
options,
);
return discrepancy_cases;
}
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 discrepancy_casesData = data.map((item, index) => ({
id: item.id || undefined,
type: item.type
||
null
,
description: item.description
||
null
,
status: item.status
||
null
,
reported_at: item.reported_at
||
null
,
resolved_at: item.resolved_at
||
null
,
resolution_notes: item.resolution_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const discrepancy_cases = await db.discrepancy_cases.bulkCreate(discrepancy_casesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < discrepancy_cases.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.discrepancy_cases.getTableName(),
belongsToColumn: 'photos',
belongsToId: discrepancy_cases[i].id,
},
data[i].photos,
options,
);
}
return discrepancy_cases;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const discrepancy_cases = await db.discrepancy_cases.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.type !== undefined) updatePayload.type = data.type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
if (data.resolution_notes !== undefined) updatePayload.resolution_notes = data.resolution_notes;
updatePayload.updatedById = currentUser.id;
await discrepancy_cases.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await discrepancy_cases.setTenant(
data.tenant,
{ transaction }
);
}
if (data.purchase_order !== undefined) {
await discrepancy_cases.setPurchase_order(
data.purchase_order,
{ transaction }
);
}
if (data.goods_receipt_note !== undefined) {
await discrepancy_cases.setGoods_receipt_note(
data.goods_receipt_note,
{ transaction }
);
}
if (data.reported_by !== undefined) {
await discrepancy_cases.setReported_by(
data.reported_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await discrepancy_cases.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.discrepancy_cases.getTableName(),
belongsToColumn: 'photos',
belongsToId: discrepancy_cases.id,
},
data.photos,
options,
);
return discrepancy_cases;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const discrepancy_cases = await db.discrepancy_cases.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of discrepancy_cases) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of discrepancy_cases) {
await record.destroy({transaction});
}
});
return discrepancy_cases;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const discrepancy_cases = await db.discrepancy_cases.findByPk(id, options);
await discrepancy_cases.update({
deletedBy: currentUser.id
}, {
transaction,
});
await discrepancy_cases.destroy({
transaction
});
return discrepancy_cases;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const discrepancy_cases = await db.discrepancy_cases.findOne(
{ where },
{ transaction },
);
if (!discrepancy_cases) {
return discrepancy_cases;
}
const output = discrepancy_cases.get({plain: true});
output.tenant = await discrepancy_cases.getTenant({
transaction
});
output.purchase_order = await discrepancy_cases.getPurchase_order({
transaction
});
output.goods_receipt_note = await discrepancy_cases.getGoods_receipt_note({
transaction
});
output.photos = await discrepancy_cases.getPhotos({
transaction
});
output.reported_by = await discrepancy_cases.getReported_by({
transaction
});
output.organizations = await discrepancy_cases.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
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)) } },
{
po_number: {
[Op.or]: filter.purchase_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.goods_receipt_notes,
as: 'goods_receipt_note',
where: filter.goods_receipt_note ? {
[Op.or]: [
{ id: { [Op.in]: filter.goods_receipt_note.split('|').map(term => Utils.uuid(term)) } },
{
grn_number: {
[Op.or]: filter.goods_receipt_note.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.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'photos',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'discrepancy_cases',
'description',
filter.description,
),
};
}
if (filter.resolution_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'discrepancy_cases',
'resolution_notes',
filter.resolution_notes,
),
};
}
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.resolved_atRange) {
const [start, end] = filter.resolved_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
resolved_at: {
...where.resolved_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
resolved_at: {
...where.resolved_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.type) {
where = {
...where,
type: filter.type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.discrepancy_cases.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'discrepancy_cases',
'status',
query,
),
],
};
}
const records = await db.discrepancy_cases.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,643 @@
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 Export_jobsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const export_jobs = await db.export_jobs.create(
{
id: data.id || undefined,
type: data.type
||
null
,
status: data.status
||
null
,
parameters_json: data.parameters_json
||
null
,
requested_at: data.requested_at
||
null
,
completed_at: data.completed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await export_jobs.setTenant( data.tenant || null, {
transaction,
});
await export_jobs.setRequested_by( data.requested_by || null, {
transaction,
});
await export_jobs.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.export_jobs.getTableName(),
belongsToColumn: 'result_files',
belongsToId: export_jobs.id,
},
data.result_files,
options,
);
return export_jobs;
}
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 export_jobsData = data.map((item, index) => ({
id: item.id || undefined,
type: item.type
||
null
,
status: item.status
||
null
,
parameters_json: item.parameters_json
||
null
,
requested_at: item.requested_at
||
null
,
completed_at: item.completed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const export_jobs = await db.export_jobs.bulkCreate(export_jobsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < export_jobs.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.export_jobs.getTableName(),
belongsToColumn: 'result_files',
belongsToId: export_jobs[i].id,
},
data[i].result_files,
options,
);
}
return export_jobs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const export_jobs = await db.export_jobs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.type !== undefined) updatePayload.type = data.type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.parameters_json !== undefined) updatePayload.parameters_json = data.parameters_json;
if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
updatePayload.updatedById = currentUser.id;
await export_jobs.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await export_jobs.setTenant(
data.tenant,
{ transaction }
);
}
if (data.requested_by !== undefined) {
await export_jobs.setRequested_by(
data.requested_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await export_jobs.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.export_jobs.getTableName(),
belongsToColumn: 'result_files',
belongsToId: export_jobs.id,
},
data.result_files,
options,
);
return export_jobs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const export_jobs = await db.export_jobs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of export_jobs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of export_jobs) {
await record.destroy({transaction});
}
});
return export_jobs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const export_jobs = await db.export_jobs.findByPk(id, options);
await export_jobs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await export_jobs.destroy({
transaction
});
return export_jobs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const export_jobs = await db.export_jobs.findOne(
{ where },
{ transaction },
);
if (!export_jobs) {
return export_jobs;
}
const output = export_jobs.get({plain: true});
output.tenant = await export_jobs.getTenant({
transaction
});
output.requested_by = await export_jobs.getRequested_by({
transaction
});
output.result_files = await export_jobs.getResult_files({
transaction
});
output.organizations = await export_jobs.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'result_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.parameters_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'export_jobs',
'parameters_json',
filter.parameters_json,
),
};
}
if (filter.requested_atRange) {
const [start, end] = filter.requested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.type) {
where = {
...where,
type: filter.type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.export_jobs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'export_jobs',
'type',
query,
),
],
};
}
const records = await db.export_jobs.findAll({
attributes: [ 'id', 'type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.type,
}));
}
};

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,699 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Goods_receipt_notesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const goods_receipt_notes = await db.goods_receipt_notes.create(
{
id: data.id || undefined,
grn_number: data.grn_number
||
null
,
received_at: data.received_at
||
null
,
quality_check: data.quality_check
||
null
,
observations: data.observations
||
null
,
receiver_signature: data.receiver_signature
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await goods_receipt_notes.setTenant( data.tenant || null, {
transaction,
});
await goods_receipt_notes.setPurchase_order( data.purchase_order || null, {
transaction,
});
await goods_receipt_notes.setReceived_by( data.received_by || null, {
transaction,
});
await goods_receipt_notes.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.goods_receipt_notes.getTableName(),
belongsToColumn: 'photos',
belongsToId: goods_receipt_notes.id,
},
data.photos,
options,
);
return goods_receipt_notes;
}
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 goods_receipt_notesData = data.map((item, index) => ({
id: item.id || undefined,
grn_number: item.grn_number
||
null
,
received_at: item.received_at
||
null
,
quality_check: item.quality_check
||
null
,
observations: item.observations
||
null
,
receiver_signature: item.receiver_signature
||
null
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const goods_receipt_notes = await db.goods_receipt_notes.bulkCreate(goods_receipt_notesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < goods_receipt_notes.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.goods_receipt_notes.getTableName(),
belongsToColumn: 'photos',
belongsToId: goods_receipt_notes[i].id,
},
data[i].photos,
options,
);
}
return goods_receipt_notes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const goods_receipt_notes = await db.goods_receipt_notes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.grn_number !== undefined) updatePayload.grn_number = data.grn_number;
if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
if (data.quality_check !== undefined) updatePayload.quality_check = data.quality_check;
if (data.observations !== undefined) updatePayload.observations = data.observations;
if (data.receiver_signature !== undefined) updatePayload.receiver_signature = data.receiver_signature;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await goods_receipt_notes.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await goods_receipt_notes.setTenant(
data.tenant,
{ transaction }
);
}
if (data.purchase_order !== undefined) {
await goods_receipt_notes.setPurchase_order(
data.purchase_order,
{ transaction }
);
}
if (data.received_by !== undefined) {
await goods_receipt_notes.setReceived_by(
data.received_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await goods_receipt_notes.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.goods_receipt_notes.getTableName(),
belongsToColumn: 'photos',
belongsToId: goods_receipt_notes.id,
},
data.photos,
options,
);
return goods_receipt_notes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const goods_receipt_notes = await db.goods_receipt_notes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of goods_receipt_notes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of goods_receipt_notes) {
await record.destroy({transaction});
}
});
return goods_receipt_notes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const goods_receipt_notes = await db.goods_receipt_notes.findByPk(id, options);
await goods_receipt_notes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await goods_receipt_notes.destroy({
transaction
});
return goods_receipt_notes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const goods_receipt_notes = await db.goods_receipt_notes.findOne(
{ where },
{ transaction },
);
if (!goods_receipt_notes) {
return goods_receipt_notes;
}
const output = goods_receipt_notes.get({plain: true});
output.grn_lines_goods_receipt_note = await goods_receipt_notes.getGrn_lines_goods_receipt_note({
transaction
});
output.discrepancy_cases_goods_receipt_note = await goods_receipt_notes.getDiscrepancy_cases_goods_receipt_note({
transaction
});
output.tenant = await goods_receipt_notes.getTenant({
transaction
});
output.purchase_order = await goods_receipt_notes.getPurchase_order({
transaction
});
output.received_by = await goods_receipt_notes.getReceived_by({
transaction
});
output.photos = await goods_receipt_notes.getPhotos({
transaction
});
output.organizations = await goods_receipt_notes.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
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)) } },
{
po_number: {
[Op.or]: filter.purchase_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'received_by',
where: filter.received_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.received_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.received_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'photos',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.grn_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'goods_receipt_notes',
'grn_number',
filter.grn_number,
),
};
}
if (filter.observations) {
where = {
...where,
[Op.and]: Utils.ilike(
'goods_receipt_notes',
'observations',
filter.observations,
),
};
}
if (filter.receiver_signature) {
where = {
...where,
[Op.and]: Utils.ilike(
'goods_receipt_notes',
'receiver_signature',
filter.receiver_signature,
),
};
}
if (filter.received_atRange) {
const [start, end] = filter.received_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
received_at: {
...where.received_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
received_at: {
...where.received_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.quality_check) {
where = {
...where,
quality_check: filter.quality_check,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.goods_receipt_notes.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'goods_receipt_notes',
'grn_number',
query,
),
],
};
}
const records = await db.goods_receipt_notes.findAll({
attributes: [ 'id', 'grn_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['grn_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.grn_number,
}));
}
};

View File

@ -0,0 +1,598 @@
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 Grn_linesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const grn_lines = await db.grn_lines.create(
{
id: data.id || undefined,
quantity_received: data.quantity_received
||
null
,
quantity_rejected: data.quantity_rejected
||
null
,
remarks: data.remarks
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await grn_lines.setTenant( data.tenant || null, {
transaction,
});
await grn_lines.setGoods_receipt_note( data.goods_receipt_note || null, {
transaction,
});
await grn_lines.setPo_line( data.po_line || null, {
transaction,
});
await grn_lines.setOrganizations( data.organizations || null, {
transaction,
});
return grn_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 grn_linesData = data.map((item, index) => ({
id: item.id || undefined,
quantity_received: item.quantity_received
||
null
,
quantity_rejected: item.quantity_rejected
||
null
,
remarks: item.remarks
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const grn_lines = await db.grn_lines.bulkCreate(grn_linesData, { transaction });
// For each item created, replace relation files
return grn_lines;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const grn_lines = await db.grn_lines.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.quantity_received !== undefined) updatePayload.quantity_received = data.quantity_received;
if (data.quantity_rejected !== undefined) updatePayload.quantity_rejected = data.quantity_rejected;
if (data.remarks !== undefined) updatePayload.remarks = data.remarks;
updatePayload.updatedById = currentUser.id;
await grn_lines.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await grn_lines.setTenant(
data.tenant,
{ transaction }
);
}
if (data.goods_receipt_note !== undefined) {
await grn_lines.setGoods_receipt_note(
data.goods_receipt_note,
{ transaction }
);
}
if (data.po_line !== undefined) {
await grn_lines.setPo_line(
data.po_line,
{ transaction }
);
}
if (data.organizations !== undefined) {
await grn_lines.setOrganizations(
data.organizations,
{ transaction }
);
}
return grn_lines;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const grn_lines = await db.grn_lines.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of grn_lines) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of grn_lines) {
await record.destroy({transaction});
}
});
return grn_lines;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const grn_lines = await db.grn_lines.findByPk(id, options);
await grn_lines.update({
deletedBy: currentUser.id
}, {
transaction,
});
await grn_lines.destroy({
transaction
});
return grn_lines;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const grn_lines = await db.grn_lines.findOne(
{ where },
{ transaction },
);
if (!grn_lines) {
return grn_lines;
}
const output = grn_lines.get({plain: true});
output.tenant = await grn_lines.getTenant({
transaction
});
output.goods_receipt_note = await grn_lines.getGoods_receipt_note({
transaction
});
output.po_line = await grn_lines.getPo_line({
transaction
});
output.organizations = await grn_lines.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.goods_receipt_notes,
as: 'goods_receipt_note',
where: filter.goods_receipt_note ? {
[Op.or]: [
{ id: { [Op.in]: filter.goods_receipt_note.split('|').map(term => Utils.uuid(term)) } },
{
grn_number: {
[Op.or]: filter.goods_receipt_note.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.po_lines,
as: 'po_line',
where: filter.po_line ? {
[Op.or]: [
{ id: { [Op.in]: filter.po_line.split('|').map(term => Utils.uuid(term)) } },
{
item_name: {
[Op.or]: filter.po_line.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.remarks) {
where = {
...where,
[Op.and]: Utils.ilike(
'grn_lines',
'remarks',
filter.remarks,
),
};
}
if (filter.quantity_receivedRange) {
const [start, end] = filter.quantity_receivedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_received: {
...where.quantity_received,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_received: {
...where.quantity_received,
[Op.lte]: end,
},
};
}
}
if (filter.quantity_rejectedRange) {
const [start, end] = filter.quantity_rejectedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_rejected: {
...where.quantity_rejected,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_rejected: {
...where.quantity_rejected,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.grn_lines.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'grn_lines',
'remarks',
query,
),
],
};
}
const records = await db.grn_lines.findAll({
attributes: [ 'id', 'remarks' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['remarks', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.remarks,
}));
}
};

View File

@ -0,0 +1,649 @@
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 NotificationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.create(
{
id: data.id || undefined,
channel: data.channel
||
null
,
subject: data.subject
||
null
,
message: data.message
||
null
,
status: data.status
||
null
,
sent_at: data.sent_at
||
null
,
read_at: data.read_at
||
null
,
related_reference: data.related_reference
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notifications.setTenant( data.tenant || null, {
transaction,
});
await notifications.setUser( data.user || null, {
transaction,
});
await notifications.setOrganizations( data.organizations || null, {
transaction,
});
return notifications;
}
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 notificationsData = data.map((item, index) => ({
id: item.id || undefined,
channel: item.channel
||
null
,
subject: item.subject
||
null
,
message: item.message
||
null
,
status: item.status
||
null
,
sent_at: item.sent_at
||
null
,
read_at: item.read_at
||
null
,
related_reference: item.related_reference
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const notifications = await db.notifications.bulkCreate(notificationsData, { transaction });
// For each item created, replace relation files
return notifications;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const notifications = await db.notifications.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.subject !== undefined) updatePayload.subject = data.subject;
if (data.message !== undefined) updatePayload.message = data.message;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.read_at !== undefined) updatePayload.read_at = data.read_at;
if (data.related_reference !== undefined) updatePayload.related_reference = data.related_reference;
updatePayload.updatedById = currentUser.id;
await notifications.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await notifications.setTenant(
data.tenant,
{ transaction }
);
}
if (data.user !== undefined) {
await notifications.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await notifications.setOrganizations(
data.organizations,
{ transaction }
);
}
return notifications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notifications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notifications) {
await record.destroy({transaction});
}
});
return notifications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findByPk(id, options);
await notifications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notifications.destroy({
transaction
});
return notifications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findOne(
{ where },
{ transaction },
);
if (!notifications) {
return notifications;
}
const output = notifications.get({plain: true});
output.tenant = await notifications.getTenant({
transaction
});
output.user = await notifications.getUser({
transaction
});
output.organizations = await notifications.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.subject) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'subject',
filter.subject,
),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'message',
filter.message,
),
};
}
if (filter.related_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'related_reference',
filter.related_reference,
),
};
}
if (filter.sent_atRange) {
const [start, end] = filter.sent_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.lte]: end,
},
};
}
}
if (filter.read_atRange) {
const [start, end] = filter.read_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
read_at: {
...where.read_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
read_at: {
...where.read_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.channel) {
where = {
...where,
channel: filter.channel,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.notifications.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'notifications',
'subject',
query,
),
],
};
}
const records = await db.notifications.findAll({
attributes: [ 'id', 'subject' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['subject', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.subject,
}));
}
};

View File

@ -0,0 +1,635 @@
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 Offer_scoresDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const offer_scores = await db.offer_scores.create(
{
id: data.id || undefined,
score: data.score
||
null
,
comment: data.comment
||
null
,
scored_at: data.scored_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await offer_scores.setTenant( data.tenant || null, {
transaction,
});
await offer_scores.setSupplier_offer( data.supplier_offer || null, {
transaction,
});
await offer_scores.setBid_criterion( data.bid_criterion || null, {
transaction,
});
await offer_scores.setScored_by( data.scored_by || null, {
transaction,
});
await offer_scores.setOrganizations( data.organizations || null, {
transaction,
});
return offer_scores;
}
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 offer_scoresData = data.map((item, index) => ({
id: item.id || undefined,
score: item.score
||
null
,
comment: item.comment
||
null
,
scored_at: item.scored_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const offer_scores = await db.offer_scores.bulkCreate(offer_scoresData, { transaction });
// For each item created, replace relation files
return offer_scores;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const offer_scores = await db.offer_scores.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.score !== undefined) updatePayload.score = data.score;
if (data.comment !== undefined) updatePayload.comment = data.comment;
if (data.scored_at !== undefined) updatePayload.scored_at = data.scored_at;
updatePayload.updatedById = currentUser.id;
await offer_scores.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await offer_scores.setTenant(
data.tenant,
{ transaction }
);
}
if (data.supplier_offer !== undefined) {
await offer_scores.setSupplier_offer(
data.supplier_offer,
{ transaction }
);
}
if (data.bid_criterion !== undefined) {
await offer_scores.setBid_criterion(
data.bid_criterion,
{ transaction }
);
}
if (data.scored_by !== undefined) {
await offer_scores.setScored_by(
data.scored_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await offer_scores.setOrganizations(
data.organizations,
{ transaction }
);
}
return offer_scores;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const offer_scores = await db.offer_scores.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of offer_scores) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of offer_scores) {
await record.destroy({transaction});
}
});
return offer_scores;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const offer_scores = await db.offer_scores.findByPk(id, options);
await offer_scores.update({
deletedBy: currentUser.id
}, {
transaction,
});
await offer_scores.destroy({
transaction
});
return offer_scores;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const offer_scores = await db.offer_scores.findOne(
{ where },
{ transaction },
);
if (!offer_scores) {
return offer_scores;
}
const output = offer_scores.get({plain: true});
output.tenant = await offer_scores.getTenant({
transaction
});
output.supplier_offer = await offer_scores.getSupplier_offer({
transaction
});
output.bid_criterion = await offer_scores.getBid_criterion({
transaction
});
output.scored_by = await offer_scores.getScored_by({
transaction
});
output.organizations = await offer_scores.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.supplier_offers,
as: 'supplier_offer',
where: filter.supplier_offer ? {
[Op.or]: [
{ id: { [Op.in]: filter.supplier_offer.split('|').map(term => Utils.uuid(term)) } },
{
status: {
[Op.or]: filter.supplier_offer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.bid_criteria,
as: 'bid_criterion',
where: filter.bid_criterion ? {
[Op.or]: [
{ id: { [Op.in]: filter.bid_criterion.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.bid_criterion.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'scored_by',
where: filter.scored_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.scored_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.scored_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.comment) {
where = {
...where,
[Op.and]: Utils.ilike(
'offer_scores',
'comment',
filter.comment,
),
};
}
if (filter.scoreRange) {
const [start, end] = filter.scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score: {
...where.score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score: {
...where.score,
[Op.lte]: end,
},
};
}
}
if (filter.scored_atRange) {
const [start, end] = filter.scored_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scored_at: {
...where.scored_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scored_at: {
...where.scored_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.offer_scores.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'offer_scores',
'comment',
query,
),
],
};
}
const records = await db.offer_scores.findAll({
attributes: [ 'id', 'comment' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['comment', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.comment,
}));
}
};

View File

@ -0,0 +1,496 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class OrganizationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return organizations;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const organizationsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const organizations = await db.organizations.bulkCreate(organizationsData, { transaction });
// For each item created, replace relation files
return organizations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const organizations = await db.organizations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await organizations.update(updatePayload, {transaction});
return organizations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of organizations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of organizations) {
await record.destroy({transaction});
}
});
return organizations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findByPk(id, options);
await organizations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await organizations.destroy({
transaction
});
return organizations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findOne(
{ where },
{ transaction },
);
if (!organizations) {
return organizations;
}
const output = organizations.get({plain: true});
output.users_organizations = await organizations.getUsers_organizations({
transaction
});
output.tenants_organizations = await organizations.getTenants_organizations({
transaction
});
output.departments_organizations = await organizations.getDepartments_organizations({
transaction
});
output.projects_organizations = await organizations.getProjects_organizations({
transaction
});
output.budget_lines_organizations = await organizations.getBudget_lines_organizations({
transaction
});
output.workflow_rules_organizations = await organizations.getWorkflow_rules_organizations({
transaction
});
output.currency_rates_organizations = await organizations.getCurrency_rates_organizations({
transaction
});
output.requisitions_organizations = await organizations.getRequisitions_organizations({
transaction
});
output.approval_steps_organizations = await organizations.getApproval_steps_organizations({
transaction
});
output.procurement_cases_organizations = await organizations.getProcurement_cases_organizations({
transaction
});
output.suppliers_organizations = await organizations.getSuppliers_organizations({
transaction
});
output.supplier_categories_organizations = await organizations.getSupplier_categories_organizations({
transaction
});
output.supplier_diligence_checks_organizations = await organizations.getSupplier_diligence_checks_organizations({
transaction
});
output.tender_events_organizations = await organizations.getTender_events_organizations({
transaction
});
output.supplier_offers_organizations = await organizations.getSupplier_offers_organizations({
transaction
});
output.bid_criteria_organizations = await organizations.getBid_criteria_organizations({
transaction
});
output.offer_scores_organizations = await organizations.getOffer_scores_organizations({
transaction
});
output.awards_organizations = await organizations.getAwards_organizations({
transaction
});
output.purchase_orders_organizations = await organizations.getPurchase_orders_organizations({
transaction
});
output.po_lines_organizations = await organizations.getPo_lines_organizations({
transaction
});
output.goods_receipt_notes_organizations = await organizations.getGoods_receipt_notes_organizations({
transaction
});
output.grn_lines_organizations = await organizations.getGrn_lines_organizations({
transaction
});
output.service_acceptance_notes_organizations = await organizations.getService_acceptance_notes_organizations({
transaction
});
output.discrepancy_cases_organizations = await organizations.getDiscrepancy_cases_organizations({
transaction
});
output.archive_items_organizations = await organizations.getArchive_items_organizations({
transaction
});
output.access_logs_organizations = await organizations.getAccess_logs_organizations({
transaction
});
output.notifications_organizations = await organizations.getNotifications_organizations({
transaction
});
output.audit_events_organizations = await organizations.getAudit_events_organizations({
transaction
});
output.export_jobs_organizations = await organizations.getExport_jobs_organizations({
transaction
});
output.sessions_organizations = await organizations.getSessions_organizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'organizations',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.organizations.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'organizations',
'name',
query,
),
],
};
}
const records = await db.organizations.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

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

View File

@ -0,0 +1,626 @@
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 Po_linesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const po_lines = await db.po_lines.create(
{
id: data.id || undefined,
item_name: data.item_name
||
null
,
description: data.description
||
null
,
quantity_ordered: data.quantity_ordered
||
null
,
unit_price: data.unit_price
||
null
,
line_total: data.line_total
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await po_lines.setTenant( data.tenant || null, {
transaction,
});
await po_lines.setPurchase_order( data.purchase_order || null, {
transaction,
});
await po_lines.setOrganizations( data.organizations || null, {
transaction,
});
return po_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 po_linesData = data.map((item, index) => ({
id: item.id || undefined,
item_name: item.item_name
||
null
,
description: item.description
||
null
,
quantity_ordered: item.quantity_ordered
||
null
,
unit_price: item.unit_price
||
null
,
line_total: item.line_total
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const po_lines = await db.po_lines.bulkCreate(po_linesData, { transaction });
// For each item created, replace relation files
return po_lines;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const po_lines = await db.po_lines.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.item_name !== undefined) updatePayload.item_name = data.item_name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.quantity_ordered !== undefined) updatePayload.quantity_ordered = data.quantity_ordered;
if (data.unit_price !== undefined) updatePayload.unit_price = data.unit_price;
if (data.line_total !== undefined) updatePayload.line_total = data.line_total;
updatePayload.updatedById = currentUser.id;
await po_lines.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await po_lines.setTenant(
data.tenant,
{ transaction }
);
}
if (data.purchase_order !== undefined) {
await po_lines.setPurchase_order(
data.purchase_order,
{ transaction }
);
}
if (data.organizations !== undefined) {
await po_lines.setOrganizations(
data.organizations,
{ transaction }
);
}
return po_lines;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const po_lines = await db.po_lines.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of po_lines) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of po_lines) {
await record.destroy({transaction});
}
});
return po_lines;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const po_lines = await db.po_lines.findByPk(id, options);
await po_lines.update({
deletedBy: currentUser.id
}, {
transaction,
});
await po_lines.destroy({
transaction
});
return po_lines;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const po_lines = await db.po_lines.findOne(
{ where },
{ transaction },
);
if (!po_lines) {
return po_lines;
}
const output = po_lines.get({plain: true});
output.grn_lines_po_line = await po_lines.getGrn_lines_po_line({
transaction
});
output.tenant = await po_lines.getTenant({
transaction
});
output.purchase_order = await po_lines.getPurchase_order({
transaction
});
output.organizations = await po_lines.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
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)) } },
{
po_number: {
[Op.or]: filter.purchase_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.item_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'po_lines',
'item_name',
filter.item_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'po_lines',
'description',
filter.description,
),
};
}
if (filter.quantity_orderedRange) {
const [start, end] = filter.quantity_orderedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity_ordered: {
...where.quantity_ordered,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity_ordered: {
...where.quantity_ordered,
[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.line_totalRange) {
const [start, end] = filter.line_totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
line_total: {
...where.line_total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
line_total: {
...where.line_total,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.po_lines.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'po_lines',
'item_name',
query,
),
],
};
}
const records = await db.po_lines.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,750 @@
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 Procurement_casesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const procurement_cases = await db.procurement_cases.create(
{
id: data.id || undefined,
classification: data.classification
||
null
,
classification_justification: data.classification_justification
||
null
,
pipeline_stage: data.pipeline_stage
||
null
,
started_at: data.started_at
||
null
,
sla_due_at: data.sla_due_at
||
null
,
awarded_at: data.awarded_at
||
null
,
closed_at: data.closed_at
||
null
,
admin_override_single_source: data.admin_override_single_source
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await procurement_cases.setTenant( data.tenant || null, {
transaction,
});
await procurement_cases.setRequisition( data.requisition || null, {
transaction,
});
await procurement_cases.setOwner( data.owner || null, {
transaction,
});
await procurement_cases.setOrganizations( data.organizations || null, {
transaction,
});
return procurement_cases;
}
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 procurement_casesData = data.map((item, index) => ({
id: item.id || undefined,
classification: item.classification
||
null
,
classification_justification: item.classification_justification
||
null
,
pipeline_stage: item.pipeline_stage
||
null
,
started_at: item.started_at
||
null
,
sla_due_at: item.sla_due_at
||
null
,
awarded_at: item.awarded_at
||
null
,
closed_at: item.closed_at
||
null
,
admin_override_single_source: item.admin_override_single_source
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const procurement_cases = await db.procurement_cases.bulkCreate(procurement_casesData, { transaction });
// For each item created, replace relation files
return procurement_cases;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const procurement_cases = await db.procurement_cases.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.classification !== undefined) updatePayload.classification = data.classification;
if (data.classification_justification !== undefined) updatePayload.classification_justification = data.classification_justification;
if (data.pipeline_stage !== undefined) updatePayload.pipeline_stage = data.pipeline_stage;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.sla_due_at !== undefined) updatePayload.sla_due_at = data.sla_due_at;
if (data.awarded_at !== undefined) updatePayload.awarded_at = data.awarded_at;
if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
if (data.admin_override_single_source !== undefined) updatePayload.admin_override_single_source = data.admin_override_single_source;
updatePayload.updatedById = currentUser.id;
await procurement_cases.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await procurement_cases.setTenant(
data.tenant,
{ transaction }
);
}
if (data.requisition !== undefined) {
await procurement_cases.setRequisition(
data.requisition,
{ transaction }
);
}
if (data.owner !== undefined) {
await procurement_cases.setOwner(
data.owner,
{ transaction }
);
}
if (data.organizations !== undefined) {
await procurement_cases.setOrganizations(
data.organizations,
{ transaction }
);
}
return procurement_cases;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const procurement_cases = await db.procurement_cases.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of procurement_cases) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of procurement_cases) {
await record.destroy({transaction});
}
});
return procurement_cases;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const procurement_cases = await db.procurement_cases.findByPk(id, options);
await procurement_cases.update({
deletedBy: currentUser.id
}, {
transaction,
});
await procurement_cases.destroy({
transaction
});
return procurement_cases;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const procurement_cases = await db.procurement_cases.findOne(
{ where },
{ transaction },
);
if (!procurement_cases) {
return procurement_cases;
}
const output = procurement_cases.get({plain: true});
output.tender_events_procurement_case = await procurement_cases.getTender_events_procurement_case({
transaction
});
output.supplier_offers_procurement_case = await procurement_cases.getSupplier_offers_procurement_case({
transaction
});
output.bid_criteria_procurement_case = await procurement_cases.getBid_criteria_procurement_case({
transaction
});
output.awards_procurement_case = await procurement_cases.getAwards_procurement_case({
transaction
});
output.tenant = await procurement_cases.getTenant({
transaction
});
output.requisition = await procurement_cases.getRequisition({
transaction
});
output.owner = await procurement_cases.getOwner({
transaction
});
output.organizations = await procurement_cases.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.requisitions,
as: 'requisition',
where: filter.requisition ? {
[Op.or]: [
{ id: { [Op.in]: filter.requisition.split('|').map(term => Utils.uuid(term)) } },
{
req_number: {
[Op.or]: filter.requisition.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.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.classification_justification) {
where = {
...where,
[Op.and]: Utils.ilike(
'procurement_cases',
'classification_justification',
filter.classification_justification,
),
};
}
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.sla_due_atRange) {
const [start, end] = filter.sla_due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sla_due_at: {
...where.sla_due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sla_due_at: {
...where.sla_due_at,
[Op.lte]: end,
},
};
}
}
if (filter.awarded_atRange) {
const [start, end] = filter.awarded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
awarded_at: {
...where.awarded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
awarded_at: {
...where.awarded_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.classification) {
where = {
...where,
classification: filter.classification,
};
}
if (filter.pipeline_stage) {
where = {
...where,
pipeline_stage: filter.pipeline_stage,
};
}
if (filter.admin_override_single_source) {
where = {
...where,
admin_override_single_source: filter.admin_override_single_source,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.procurement_cases.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'procurement_cases',
'pipeline_stage',
query,
),
],
};
}
const records = await db.procurement_cases.findAll({
attributes: [ 'id', 'pipeline_stage' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['pipeline_stage', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.pipeline_stage,
}));
}
};

View File

@ -0,0 +1,537 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ProjectsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.create(
{
id: data.id || undefined,
code: data.code
||
null
,
name: data.name
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await projects.setTenant( data.tenant || null, {
transaction,
});
await projects.setDepartment( data.department || null, {
transaction,
});
await projects.setOrganizations( data.organizations || null, {
transaction,
});
return projects;
}
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 projectsData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
name: item.name
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const projects = await db.projects.bulkCreate(projectsData, { transaction });
// For each item created, replace relation files
return projects;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const projects = await db.projects.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await projects.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await projects.setTenant(
data.tenant,
{ transaction }
);
}
if (data.department !== undefined) {
await projects.setDepartment(
data.department,
{ transaction }
);
}
if (data.organizations !== undefined) {
await projects.setOrganizations(
data.organizations,
{ transaction }
);
}
return projects;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of projects) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of projects) {
await record.destroy({transaction});
}
});
return projects;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findByPk(id, options);
await projects.update({
deletedBy: currentUser.id
}, {
transaction,
});
await projects.destroy({
transaction
});
return projects;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findOne(
{ where },
{ transaction },
);
if (!projects) {
return projects;
}
const output = projects.get({plain: true});
output.requisitions_project = await projects.getRequisitions_project({
transaction
});
output.tenant = await projects.getTenant({
transaction
});
output.department = await projects.getDepartment({
transaction
});
output.organizations = await projects.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.departments,
as: 'department',
where: filter.department ? {
[Op.or]: [
{ id: { [Op.in]: filter.department.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.department.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'code',
filter.code,
),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.projects.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'projects',
'name',
query,
),
],
};
}
const records = await db.projects.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,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 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,
po_number: data.po_number
||
null
,
total_amount_usd: data.total_amount_usd
||
null
,
currency: data.currency
||
null
,
total_amount_original: data.total_amount_original
||
null
,
issued_at: data.issued_at
||
null
,
expected_delivery_at: data.expected_delivery_at
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await purchase_orders.setTenant( data.tenant || null, {
transaction,
});
await purchase_orders.setRequisition( data.requisition || null, {
transaction,
});
await purchase_orders.setSupplier( data.supplier || null, {
transaction,
});
await purchase_orders.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.purchase_orders.getTableName(),
belongsToColumn: 'po_documents',
belongsToId: purchase_orders.id,
},
data.po_documents,
options,
);
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,
po_number: item.po_number
||
null
,
total_amount_usd: item.total_amount_usd
||
null
,
currency: item.currency
||
null
,
total_amount_original: item.total_amount_original
||
null
,
issued_at: item.issued_at
||
null
,
expected_delivery_at: item.expected_delivery_at
||
null
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const purchase_orders = await db.purchase_orders.bulkCreate(purchase_ordersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < purchase_orders.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.purchase_orders.getTableName(),
belongsToColumn: 'po_documents',
belongsToId: purchase_orders[i].id,
},
data[i].po_documents,
options,
);
}
return purchase_orders;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const purchase_orders = await db.purchase_orders.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.po_number !== undefined) updatePayload.po_number = data.po_number;
if (data.total_amount_usd !== undefined) updatePayload.total_amount_usd = data.total_amount_usd;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.total_amount_original !== undefined) updatePayload.total_amount_original = data.total_amount_original;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.expected_delivery_at !== undefined) updatePayload.expected_delivery_at = data.expected_delivery_at;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await purchase_orders.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await purchase_orders.setTenant(
data.tenant,
{ transaction }
);
}
if (data.requisition !== undefined) {
await purchase_orders.setRequisition(
data.requisition,
{ transaction }
);
}
if (data.supplier !== undefined) {
await purchase_orders.setSupplier(
data.supplier,
{ transaction }
);
}
if (data.organizations !== undefined) {
await purchase_orders.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.purchase_orders.getTableName(),
belongsToColumn: 'po_documents',
belongsToId: purchase_orders.id,
},
data.po_documents,
options,
);
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.po_lines_purchase_order = await purchase_orders.getPo_lines_purchase_order({
transaction
});
output.goods_receipt_notes_purchase_order = await purchase_orders.getGoods_receipt_notes_purchase_order({
transaction
});
output.service_acceptance_notes_purchase_order = await purchase_orders.getService_acceptance_notes_purchase_order({
transaction
});
output.discrepancy_cases_purchase_order = await purchase_orders.getDiscrepancy_cases_purchase_order({
transaction
});
output.tenant = await purchase_orders.getTenant({
transaction
});
output.requisition = await purchase_orders.getRequisition({
transaction
});
output.supplier = await purchase_orders.getSupplier({
transaction
});
output.po_documents = await purchase_orders.getPo_documents({
transaction
});
output.organizations = await purchase_orders.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.requisitions,
as: 'requisition',
where: filter.requisition ? {
[Op.or]: [
{ id: { [Op.in]: filter.requisition.split('|').map(term => Utils.uuid(term)) } },
{
req_number: {
[Op.or]: filter.requisition.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)) } },
{
legal_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'po_documents',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.po_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'purchase_orders',
'po_number',
filter.po_number,
),
};
}
if (filter.total_amount_usdRange) {
const [start, end] = filter.total_amount_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_amount_usd: {
...where.total_amount_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_amount_usd: {
...where.total_amount_usd,
[Op.lte]: end,
},
};
}
}
if (filter.total_amount_originalRange) {
const [start, end] = filter.total_amount_originalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_amount_original: {
...where.total_amount_original,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_amount_original: {
...where.total_amount_original,
[Op.lte]: end,
},
};
}
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.lte]: end,
},
};
}
}
if (filter.expected_delivery_atRange) {
const [start, end] = filter.expected_delivery_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expected_delivery_at: {
...where.expected_delivery_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expected_delivery_at: {
...where.expected_delivery_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.currency) {
where = {
...where,
currency: filter.currency,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'purchase_orders',
'po_number',
query,
),
],
};
}
const records = await db.purchase_orders.findAll({
attributes: [ 'id', 'po_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['po_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.po_number,
}));
}
};

File diff suppressed because it is too large Load Diff

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

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

View File

@ -0,0 +1,671 @@
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 Service_acceptance_notesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_acceptance_notes = await db.service_acceptance_notes.create(
{
id: data.id || undefined,
san_number: data.san_number
||
null
,
acceptance_date: data.acceptance_date
||
null
,
deliverable_checklist: data.deliverable_checklist
||
null
,
acceptance_criteria: data.acceptance_criteria
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await service_acceptance_notes.setTenant( data.tenant || null, {
transaction,
});
await service_acceptance_notes.setPurchase_order( data.purchase_order || null, {
transaction,
});
await service_acceptance_notes.setAccepted_by( data.accepted_by || null, {
transaction,
});
await service_acceptance_notes.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.service_acceptance_notes.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: service_acceptance_notes.id,
},
data.evidence_files,
options,
);
return service_acceptance_notes;
}
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 service_acceptance_notesData = data.map((item, index) => ({
id: item.id || undefined,
san_number: item.san_number
||
null
,
acceptance_date: item.acceptance_date
||
null
,
deliverable_checklist: item.deliverable_checklist
||
null
,
acceptance_criteria: item.acceptance_criteria
||
null
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const service_acceptance_notes = await db.service_acceptance_notes.bulkCreate(service_acceptance_notesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < service_acceptance_notes.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.service_acceptance_notes.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: service_acceptance_notes[i].id,
},
data[i].evidence_files,
options,
);
}
return service_acceptance_notes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const service_acceptance_notes = await db.service_acceptance_notes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.san_number !== undefined) updatePayload.san_number = data.san_number;
if (data.acceptance_date !== undefined) updatePayload.acceptance_date = data.acceptance_date;
if (data.deliverable_checklist !== undefined) updatePayload.deliverable_checklist = data.deliverable_checklist;
if (data.acceptance_criteria !== undefined) updatePayload.acceptance_criteria = data.acceptance_criteria;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await service_acceptance_notes.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await service_acceptance_notes.setTenant(
data.tenant,
{ transaction }
);
}
if (data.purchase_order !== undefined) {
await service_acceptance_notes.setPurchase_order(
data.purchase_order,
{ transaction }
);
}
if (data.accepted_by !== undefined) {
await service_acceptance_notes.setAccepted_by(
data.accepted_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await service_acceptance_notes.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.service_acceptance_notes.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: service_acceptance_notes.id,
},
data.evidence_files,
options,
);
return service_acceptance_notes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_acceptance_notes = await db.service_acceptance_notes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of service_acceptance_notes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of service_acceptance_notes) {
await record.destroy({transaction});
}
});
return service_acceptance_notes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const service_acceptance_notes = await db.service_acceptance_notes.findByPk(id, options);
await service_acceptance_notes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await service_acceptance_notes.destroy({
transaction
});
return service_acceptance_notes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const service_acceptance_notes = await db.service_acceptance_notes.findOne(
{ where },
{ transaction },
);
if (!service_acceptance_notes) {
return service_acceptance_notes;
}
const output = service_acceptance_notes.get({plain: true});
output.tenant = await service_acceptance_notes.getTenant({
transaction
});
output.purchase_order = await service_acceptance_notes.getPurchase_order({
transaction
});
output.accepted_by = await service_acceptance_notes.getAccepted_by({
transaction
});
output.evidence_files = await service_acceptance_notes.getEvidence_files({
transaction
});
output.organizations = await service_acceptance_notes.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
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)) } },
{
po_number: {
[Op.or]: filter.purchase_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'accepted_by',
where: filter.accepted_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.accepted_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.accepted_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'evidence_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.san_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_acceptance_notes',
'san_number',
filter.san_number,
),
};
}
if (filter.deliverable_checklist) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_acceptance_notes',
'deliverable_checklist',
filter.deliverable_checklist,
),
};
}
if (filter.acceptance_criteria) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_acceptance_notes',
'acceptance_criteria',
filter.acceptance_criteria,
),
};
}
if (filter.acceptance_dateRange) {
const [start, end] = filter.acceptance_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
acceptance_date: {
...where.acceptance_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
acceptance_date: {
...where.acceptance_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.service_acceptance_notes.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'service_acceptance_notes',
'san_number',
query,
),
],
};
}
const records = await db.service_acceptance_notes.findAll({
attributes: [ 'id', 'san_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['san_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.san_number,
}));
}
};

View File

@ -0,0 +1,646 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class SessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sessions = await db.sessions.create(
{
id: data.id || undefined,
refresh_token_hash: data.refresh_token_hash
||
null
,
created_at_time: data.created_at_time
||
null
,
expires_at: data.expires_at
||
null
,
revoked_at: data.revoked_at
||
null
,
ip_address: data.ip_address
||
null
,
user_agent: data.user_agent
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await sessions.setTenant( data.tenant || null, {
transaction,
});
await sessions.setUser( data.user || null, {
transaction,
});
await sessions.setOrganizations( data.organizations || null, {
transaction,
});
return sessions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const sessionsData = data.map((item, index) => ({
id: item.id || undefined,
refresh_token_hash: item.refresh_token_hash
||
null
,
created_at_time: item.created_at_time
||
null
,
expires_at: item.expires_at
||
null
,
revoked_at: item.revoked_at
||
null
,
ip_address: item.ip_address
||
null
,
user_agent: item.user_agent
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const sessions = await db.sessions.bulkCreate(sessionsData, { transaction });
// For each item created, replace relation files
return sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const sessions = await db.sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.refresh_token_hash !== undefined) updatePayload.refresh_token_hash = data.refresh_token_hash;
if (data.created_at_time !== undefined) updatePayload.created_at_time = data.created_at_time;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.revoked_at !== undefined) updatePayload.revoked_at = data.revoked_at;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
updatePayload.updatedById = currentUser.id;
await sessions.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await sessions.setTenant(
data.tenant,
{ transaction }
);
}
if (data.user !== undefined) {
await sessions.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await sessions.setOrganizations(
data.organizations,
{ transaction }
);
}
return sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sessions = await db.sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of sessions) {
await record.destroy({transaction});
}
});
return sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const sessions = await db.sessions.findByPk(id, options);
await sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await sessions.destroy({
transaction
});
return sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const sessions = await db.sessions.findOne(
{ where },
{ transaction },
);
if (!sessions) {
return sessions;
}
const output = sessions.get({plain: true});
output.tenant = await sessions.getTenant({
transaction
});
output.user = await sessions.getUser({
transaction
});
output.organizations = await sessions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.refresh_token_hash) {
where = {
...where,
[Op.and]: Utils.ilike(
'sessions',
'refresh_token_hash',
filter.refresh_token_hash,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'sessions',
'ip_address',
filter.ip_address,
),
};
}
if (filter.user_agent) {
where = {
...where,
[Op.and]: Utils.ilike(
'sessions',
'user_agent',
filter.user_agent,
),
};
}
if (filter.created_at_timeRange) {
const [start, end] = filter.created_at_timeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_time: {
...where.created_at_time,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_time: {
...where.created_at_time,
[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.revoked_atRange) {
const [start, end] = filter.revoked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.sessions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'sessions',
'ip_address',
query,
),
],
};
}
const records = await db.sessions.findAll({
attributes: [ 'id', 'ip_address' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['ip_address', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.ip_address,
}));
}
};

View File

@ -0,0 +1,474 @@
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 Supplier_categoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const supplier_categories = await db.supplier_categories.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await supplier_categories.setTenant( data.tenant || null, {
transaction,
});
await supplier_categories.setOrganizations( data.organizations || null, {
transaction,
});
return supplier_categories;
}
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 supplier_categoriesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const supplier_categories = await db.supplier_categories.bulkCreate(supplier_categoriesData, { transaction });
// For each item created, replace relation files
return supplier_categories;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const supplier_categories = await db.supplier_categories.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await supplier_categories.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await supplier_categories.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await supplier_categories.setOrganizations(
data.organizations,
{ transaction }
);
}
return supplier_categories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const supplier_categories = await db.supplier_categories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of supplier_categories) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of supplier_categories) {
await record.destroy({transaction});
}
});
return supplier_categories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const supplier_categories = await db.supplier_categories.findByPk(id, options);
await supplier_categories.update({
deletedBy: currentUser.id
}, {
transaction,
});
await supplier_categories.destroy({
transaction
});
return supplier_categories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const supplier_categories = await db.supplier_categories.findOne(
{ where },
{ transaction },
);
if (!supplier_categories) {
return supplier_categories;
}
const output = supplier_categories.get({plain: true});
output.tenant = await supplier_categories.getTenant({
transaction
});
output.organizations = await supplier_categories.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'supplier_categories',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'supplier_categories',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.supplier_categories.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'supplier_categories',
'name',
query,
),
],
};
}
const records = await db.supplier_categories.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,643 @@
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 Supplier_diligence_checksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const supplier_diligence_checks = await db.supplier_diligence_checks.create(
{
id: data.id || undefined,
check_type: data.check_type
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
checked_at: data.checked_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await supplier_diligence_checks.setTenant( data.tenant || null, {
transaction,
});
await supplier_diligence_checks.setSupplier( data.supplier || null, {
transaction,
});
await supplier_diligence_checks.setChecked_by( data.checked_by || null, {
transaction,
});
await supplier_diligence_checks.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.supplier_diligence_checks.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: supplier_diligence_checks.id,
},
data.evidence_files,
options,
);
return supplier_diligence_checks;
}
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 supplier_diligence_checksData = data.map((item, index) => ({
id: item.id || undefined,
check_type: item.check_type
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
checked_at: item.checked_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const supplier_diligence_checks = await db.supplier_diligence_checks.bulkCreate(supplier_diligence_checksData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < supplier_diligence_checks.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.supplier_diligence_checks.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: supplier_diligence_checks[i].id,
},
data[i].evidence_files,
options,
);
}
return supplier_diligence_checks;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const supplier_diligence_checks = await db.supplier_diligence_checks.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.check_type !== undefined) updatePayload.check_type = data.check_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.checked_at !== undefined) updatePayload.checked_at = data.checked_at;
updatePayload.updatedById = currentUser.id;
await supplier_diligence_checks.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await supplier_diligence_checks.setTenant(
data.tenant,
{ transaction }
);
}
if (data.supplier !== undefined) {
await supplier_diligence_checks.setSupplier(
data.supplier,
{ transaction }
);
}
if (data.checked_by !== undefined) {
await supplier_diligence_checks.setChecked_by(
data.checked_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await supplier_diligence_checks.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.supplier_diligence_checks.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: supplier_diligence_checks.id,
},
data.evidence_files,
options,
);
return supplier_diligence_checks;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const supplier_diligence_checks = await db.supplier_diligence_checks.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of supplier_diligence_checks) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of supplier_diligence_checks) {
await record.destroy({transaction});
}
});
return supplier_diligence_checks;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const supplier_diligence_checks = await db.supplier_diligence_checks.findByPk(id, options);
await supplier_diligence_checks.update({
deletedBy: currentUser.id
}, {
transaction,
});
await supplier_diligence_checks.destroy({
transaction
});
return supplier_diligence_checks;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const supplier_diligence_checks = await db.supplier_diligence_checks.findOne(
{ where },
{ transaction },
);
if (!supplier_diligence_checks) {
return supplier_diligence_checks;
}
const output = supplier_diligence_checks.get({plain: true});
output.tenant = await supplier_diligence_checks.getTenant({
transaction
});
output.supplier = await supplier_diligence_checks.getSupplier({
transaction
});
output.evidence_files = await supplier_diligence_checks.getEvidence_files({
transaction
});
output.checked_by = await supplier_diligence_checks.getChecked_by({
transaction
});
output.organizations = await supplier_diligence_checks.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.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)) } },
{
legal_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'checked_by',
where: filter.checked_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.checked_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.checked_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'evidence_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'supplier_diligence_checks',
'notes',
filter.notes,
),
};
}
if (filter.checked_atRange) {
const [start, end] = filter.checked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
checked_at: {
...where.checked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
checked_at: {
...where.checked_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.check_type) {
where = {
...where,
check_type: filter.check_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.supplier_diligence_checks.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'supplier_diligence_checks',
'check_type',
query,
),
],
};
}
const records = await db.supplier_diligence_checks.findAll({
attributes: [ 'id', 'check_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['check_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.check_type,
}));
}
};

View File

@ -0,0 +1,749 @@
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 Supplier_offersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const supplier_offers = await db.supplier_offers.create(
{
id: data.id || undefined,
amount: data.amount
||
null
,
currency: data.currency
||
null
,
amount_usd: data.amount_usd
||
null
,
delivery_lead_time: data.delivery_lead_time
||
null
,
warranty_terms: data.warranty_terms
||
null
,
status: data.status
||
null
,
received_at: data.received_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await supplier_offers.setTenant( data.tenant || null, {
transaction,
});
await supplier_offers.setProcurement_case( data.procurement_case || null, {
transaction,
});
await supplier_offers.setSupplier( data.supplier || null, {
transaction,
});
await supplier_offers.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.supplier_offers.getTableName(),
belongsToColumn: 'offer_files',
belongsToId: supplier_offers.id,
},
data.offer_files,
options,
);
return supplier_offers;
}
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 supplier_offersData = data.map((item, index) => ({
id: item.id || undefined,
amount: item.amount
||
null
,
currency: item.currency
||
null
,
amount_usd: item.amount_usd
||
null
,
delivery_lead_time: item.delivery_lead_time
||
null
,
warranty_terms: item.warranty_terms
||
null
,
status: item.status
||
null
,
received_at: item.received_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const supplier_offers = await db.supplier_offers.bulkCreate(supplier_offersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < supplier_offers.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.supplier_offers.getTableName(),
belongsToColumn: 'offer_files',
belongsToId: supplier_offers[i].id,
},
data[i].offer_files,
options,
);
}
return supplier_offers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const supplier_offers = await db.supplier_offers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.amount_usd !== undefined) updatePayload.amount_usd = data.amount_usd;
if (data.delivery_lead_time !== undefined) updatePayload.delivery_lead_time = data.delivery_lead_time;
if (data.warranty_terms !== undefined) updatePayload.warranty_terms = data.warranty_terms;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
updatePayload.updatedById = currentUser.id;
await supplier_offers.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await supplier_offers.setTenant(
data.tenant,
{ transaction }
);
}
if (data.procurement_case !== undefined) {
await supplier_offers.setProcurement_case(
data.procurement_case,
{ transaction }
);
}
if (data.supplier !== undefined) {
await supplier_offers.setSupplier(
data.supplier,
{ transaction }
);
}
if (data.organizations !== undefined) {
await supplier_offers.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.supplier_offers.getTableName(),
belongsToColumn: 'offer_files',
belongsToId: supplier_offers.id,
},
data.offer_files,
options,
);
return supplier_offers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const supplier_offers = await db.supplier_offers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of supplier_offers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of supplier_offers) {
await record.destroy({transaction});
}
});
return supplier_offers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const supplier_offers = await db.supplier_offers.findByPk(id, options);
await supplier_offers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await supplier_offers.destroy({
transaction
});
return supplier_offers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const supplier_offers = await db.supplier_offers.findOne(
{ where },
{ transaction },
);
if (!supplier_offers) {
return supplier_offers;
}
const output = supplier_offers.get({plain: true});
output.offer_scores_supplier_offer = await supplier_offers.getOffer_scores_supplier_offer({
transaction
});
output.awards_winning_offer = await supplier_offers.getAwards_winning_offer({
transaction
});
output.tenant = await supplier_offers.getTenant({
transaction
});
output.procurement_case = await supplier_offers.getProcurement_case({
transaction
});
output.supplier = await supplier_offers.getSupplier({
transaction
});
output.offer_files = await supplier_offers.getOffer_files({
transaction
});
output.organizations = await supplier_offers.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.procurement_cases,
as: 'procurement_case',
where: filter.procurement_case ? {
[Op.or]: [
{ id: { [Op.in]: filter.procurement_case.split('|').map(term => Utils.uuid(term)) } },
{
pipeline_stage: {
[Op.or]: filter.procurement_case.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)) } },
{
legal_name: {
[Op.or]: filter.supplier.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'offer_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.delivery_lead_time) {
where = {
...where,
[Op.and]: Utils.ilike(
'supplier_offers',
'delivery_lead_time',
filter.delivery_lead_time,
),
};
}
if (filter.warranty_terms) {
where = {
...where,
[Op.and]: Utils.ilike(
'supplier_offers',
'warranty_terms',
filter.warranty_terms,
),
};
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.amount_usdRange) {
const [start, end] = filter.amount_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount_usd: {
...where.amount_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount_usd: {
...where.amount_usd,
[Op.lte]: end,
},
};
}
}
if (filter.received_atRange) {
const [start, end] = filter.received_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
received_at: {
...where.received_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
received_at: {
...where.received_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.currency) {
where = {
...where,
currency: filter.currency,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.supplier_offers.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'supplier_offers',
'status',
query,
),
],
};
}
const records = await db.supplier_offers.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,845 @@
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,
legal_name: data.legal_name
||
null
,
commercial_name: data.commercial_name
||
null
,
rccm_number: data.rccm_number
||
null
,
tax_id: data.tax_id
||
null
,
country: data.country
||
null
,
address: data.address
||
null
,
primary_contact_name: data.primary_contact_name
||
null
,
primary_contact_email: data.primary_contact_email
||
null
,
primary_contact_phone: data.primary_contact_phone
||
null
,
bank_name: data.bank_name
||
null
,
bank_account_number: data.bank_account_number
||
null
,
bank_swift: data.bank_swift
||
null
,
status: data.status
||
null
,
prequalification_status: data.prequalification_status
||
null
,
performance_score: data.performance_score
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await suppliers.setTenant( data.tenant || null, {
transaction,
});
await suppliers.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.suppliers.getTableName(),
belongsToColumn: 'documents',
belongsToId: suppliers.id,
},
data.documents,
options,
);
return suppliers;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const suppliersData = data.map((item, index) => ({
id: item.id || undefined,
legal_name: item.legal_name
||
null
,
commercial_name: item.commercial_name
||
null
,
rccm_number: item.rccm_number
||
null
,
tax_id: item.tax_id
||
null
,
country: item.country
||
null
,
address: item.address
||
null
,
primary_contact_name: item.primary_contact_name
||
null
,
primary_contact_email: item.primary_contact_email
||
null
,
primary_contact_phone: item.primary_contact_phone
||
null
,
bank_name: item.bank_name
||
null
,
bank_account_number: item.bank_account_number
||
null
,
bank_swift: item.bank_swift
||
null
,
status: item.status
||
null
,
prequalification_status: item.prequalification_status
||
null
,
performance_score: item.performance_score
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const suppliers = await db.suppliers.bulkCreate(suppliersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < suppliers.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.suppliers.getTableName(),
belongsToColumn: 'documents',
belongsToId: suppliers[i].id,
},
data[i].documents,
options,
);
}
return suppliers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const suppliers = await db.suppliers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
if (data.commercial_name !== undefined) updatePayload.commercial_name = data.commercial_name;
if (data.rccm_number !== undefined) updatePayload.rccm_number = data.rccm_number;
if (data.tax_id !== undefined) updatePayload.tax_id = data.tax_id;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.primary_contact_name !== undefined) updatePayload.primary_contact_name = data.primary_contact_name;
if (data.primary_contact_email !== undefined) updatePayload.primary_contact_email = data.primary_contact_email;
if (data.primary_contact_phone !== undefined) updatePayload.primary_contact_phone = data.primary_contact_phone;
if (data.bank_name !== undefined) updatePayload.bank_name = data.bank_name;
if (data.bank_account_number !== undefined) updatePayload.bank_account_number = data.bank_account_number;
if (data.bank_swift !== undefined) updatePayload.bank_swift = data.bank_swift;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.prequalification_status !== undefined) updatePayload.prequalification_status = data.prequalification_status;
if (data.performance_score !== undefined) updatePayload.performance_score = data.performance_score;
updatePayload.updatedById = currentUser.id;
await suppliers.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await suppliers.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await suppliers.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.suppliers.getTableName(),
belongsToColumn: 'documents',
belongsToId: suppliers.id,
},
data.documents,
options,
);
return suppliers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of suppliers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of suppliers) {
await record.destroy({transaction});
}
});
return suppliers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findByPk(id, options);
await suppliers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await suppliers.destroy({
transaction
});
return suppliers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findOne(
{ where },
{ transaction },
);
if (!suppliers) {
return suppliers;
}
const output = suppliers.get({plain: true});
output.supplier_diligence_checks_supplier = await suppliers.getSupplier_diligence_checks_supplier({
transaction
});
output.supplier_offers_supplier = await suppliers.getSupplier_offers_supplier({
transaction
});
output.awards_awarded_supplier = await suppliers.getAwards_awarded_supplier({
transaction
});
output.purchase_orders_supplier = await suppliers.getPurchase_orders_supplier({
transaction
});
output.tenant = await suppliers.getTenant({
transaction
});
output.documents = await suppliers.getDocuments({
transaction
});
output.organizations = await suppliers.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'documents',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.legal_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'legal_name',
filter.legal_name,
),
};
}
if (filter.commercial_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'commercial_name',
filter.commercial_name,
),
};
}
if (filter.rccm_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'rccm_number',
filter.rccm_number,
),
};
}
if (filter.tax_id) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'tax_id',
filter.tax_id,
),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'address',
filter.address,
),
};
}
if (filter.primary_contact_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'primary_contact_name',
filter.primary_contact_name,
),
};
}
if (filter.primary_contact_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'primary_contact_email',
filter.primary_contact_email,
),
};
}
if (filter.primary_contact_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'primary_contact_phone',
filter.primary_contact_phone,
),
};
}
if (filter.bank_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'bank_name',
filter.bank_name,
),
};
}
if (filter.bank_account_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'bank_account_number',
filter.bank_account_number,
),
};
}
if (filter.bank_swift) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'bank_swift',
filter.bank_swift,
),
};
}
if (filter.performance_scoreRange) {
const [start, end] = filter.performance_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
performance_score: {
...where.performance_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
performance_score: {
...where.performance_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.country) {
where = {
...where,
country: filter.country,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.prequalification_status) {
where = {
...where,
prequalification_status: filter.prequalification_status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.suppliers.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'suppliers',
'legal_name',
query,
),
],
};
}
const records = await db.suppliers.findAll({
attributes: [ 'id', 'legal_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['legal_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.legal_name,
}));
}
};

View File

@ -0,0 +1,826 @@
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 TenantsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.create(
{
id: data.id || undefined,
name: data.name
||
null
,
subdomain: data.subdomain
||
null
,
status: data.status
||
null
,
tagline: data.tagline
||
null
,
primary_color: data.primary_color
||
null
,
secondary_color: data.secondary_color
||
null
,
default_language: data.default_language
||
null
,
primary_currency: data.primary_currency
||
null
,
secondary_currency: data.secondary_currency
||
null
,
sso_enabled: data.sso_enabled
||
false
,
suspended_on: data.suspended_on
||
null
,
data_retention_policy: data.data_retention_policy
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tenants.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tenants.getTableName(),
belongsToColumn: 'logo',
belongsToId: tenants.id,
},
data.logo,
options,
);
return tenants;
}
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 tenantsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
subdomain: item.subdomain
||
null
,
status: item.status
||
null
,
tagline: item.tagline
||
null
,
primary_color: item.primary_color
||
null
,
secondary_color: item.secondary_color
||
null
,
default_language: item.default_language
||
null
,
primary_currency: item.primary_currency
||
null
,
secondary_currency: item.secondary_currency
||
null
,
sso_enabled: item.sso_enabled
||
false
,
suspended_on: item.suspended_on
||
null
,
data_retention_policy: item.data_retention_policy
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tenants = await db.tenants.bulkCreate(tenantsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < tenants.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tenants.getTableName(),
belongsToColumn: 'logo',
belongsToId: tenants[i].id,
},
data[i].logo,
options,
);
}
return tenants;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const tenants = await db.tenants.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.subdomain !== undefined) updatePayload.subdomain = data.subdomain;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.tagline !== undefined) updatePayload.tagline = data.tagline;
if (data.primary_color !== undefined) updatePayload.primary_color = data.primary_color;
if (data.secondary_color !== undefined) updatePayload.secondary_color = data.secondary_color;
if (data.default_language !== undefined) updatePayload.default_language = data.default_language;
if (data.primary_currency !== undefined) updatePayload.primary_currency = data.primary_currency;
if (data.secondary_currency !== undefined) updatePayload.secondary_currency = data.secondary_currency;
if (data.sso_enabled !== undefined) updatePayload.sso_enabled = data.sso_enabled;
if (data.suspended_on !== undefined) updatePayload.suspended_on = data.suspended_on;
if (data.data_retention_policy !== undefined) updatePayload.data_retention_policy = data.data_retention_policy;
updatePayload.updatedById = currentUser.id;
await tenants.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await tenants.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tenants.getTableName(),
belongsToColumn: 'logo',
belongsToId: tenants.id,
},
data.logo,
options,
);
return tenants;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tenants) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tenants) {
await record.destroy({transaction});
}
});
return tenants;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.findByPk(id, options);
await tenants.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tenants.destroy({
transaction
});
return tenants;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.findOne(
{ where },
{ transaction },
);
if (!tenants) {
return tenants;
}
const output = tenants.get({plain: true});
output.departments_tenant = await tenants.getDepartments_tenant({
transaction
});
output.projects_tenant = await tenants.getProjects_tenant({
transaction
});
output.budget_lines_tenant = await tenants.getBudget_lines_tenant({
transaction
});
output.workflow_rules_tenant = await tenants.getWorkflow_rules_tenant({
transaction
});
output.currency_rates_tenant = await tenants.getCurrency_rates_tenant({
transaction
});
output.requisitions_tenant = await tenants.getRequisitions_tenant({
transaction
});
output.approval_steps_tenant = await tenants.getApproval_steps_tenant({
transaction
});
output.procurement_cases_tenant = await tenants.getProcurement_cases_tenant({
transaction
});
output.suppliers_tenant = await tenants.getSuppliers_tenant({
transaction
});
output.supplier_categories_tenant = await tenants.getSupplier_categories_tenant({
transaction
});
output.supplier_diligence_checks_tenant = await tenants.getSupplier_diligence_checks_tenant({
transaction
});
output.tender_events_tenant = await tenants.getTender_events_tenant({
transaction
});
output.supplier_offers_tenant = await tenants.getSupplier_offers_tenant({
transaction
});
output.bid_criteria_tenant = await tenants.getBid_criteria_tenant({
transaction
});
output.offer_scores_tenant = await tenants.getOffer_scores_tenant({
transaction
});
output.awards_tenant = await tenants.getAwards_tenant({
transaction
});
output.purchase_orders_tenant = await tenants.getPurchase_orders_tenant({
transaction
});
output.po_lines_tenant = await tenants.getPo_lines_tenant({
transaction
});
output.goods_receipt_notes_tenant = await tenants.getGoods_receipt_notes_tenant({
transaction
});
output.grn_lines_tenant = await tenants.getGrn_lines_tenant({
transaction
});
output.service_acceptance_notes_tenant = await tenants.getService_acceptance_notes_tenant({
transaction
});
output.discrepancy_cases_tenant = await tenants.getDiscrepancy_cases_tenant({
transaction
});
output.archive_items_tenant = await tenants.getArchive_items_tenant({
transaction
});
output.access_logs_tenant = await tenants.getAccess_logs_tenant({
transaction
});
output.notifications_tenant = await tenants.getNotifications_tenant({
transaction
});
output.audit_events_tenant = await tenants.getAudit_events_tenant({
transaction
});
output.export_jobs_tenant = await tenants.getExport_jobs_tenant({
transaction
});
output.sessions_tenant = await tenants.getSessions_tenant({
transaction
});
output.logo = await tenants.getLogo({
transaction
});
output.organizations = await tenants.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'logo',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'name',
filter.name,
),
};
}
if (filter.subdomain) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'subdomain',
filter.subdomain,
),
};
}
if (filter.tagline) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'tagline',
filter.tagline,
),
};
}
if (filter.primary_color) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'primary_color',
filter.primary_color,
),
};
}
if (filter.secondary_color) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'secondary_color',
filter.secondary_color,
),
};
}
if (filter.data_retention_policy) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'data_retention_policy',
filter.data_retention_policy,
),
};
}
if (filter.suspended_onRange) {
const [start, end] = filter.suspended_onRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
suspended_on: {
...where.suspended_on,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
suspended_on: {
...where.suspended_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.default_language) {
where = {
...where,
default_language: filter.default_language,
};
}
if (filter.primary_currency) {
where = {
...where,
primary_currency: filter.primary_currency,
};
}
if (filter.secondary_currency) {
where = {
...where,
secondary_currency: filter.secondary_currency,
};
}
if (filter.sso_enabled) {
where = {
...where,
sso_enabled: filter.sso_enabled,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.tenants.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'tenants',
'name',
query,
),
],
};
}
const records = await db.tenants.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,684 @@
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 Tender_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tender_events = await db.tender_events.create(
{
id: data.id || undefined,
reference: data.reference
||
null
,
title: data.title
||
null
,
status: data.status
||
null
,
published_at: data.published_at
||
null
,
submission_deadline: data.submission_deadline
||
null
,
opened_at: data.opened_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tender_events.setTenant( data.tenant || null, {
transaction,
});
await tender_events.setProcurement_case( data.procurement_case || null, {
transaction,
});
await tender_events.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tender_events.getTableName(),
belongsToColumn: 'tender_documents',
belongsToId: tender_events.id,
},
data.tender_documents,
options,
);
return tender_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 tender_eventsData = data.map((item, index) => ({
id: item.id || undefined,
reference: item.reference
||
null
,
title: item.title
||
null
,
status: item.status
||
null
,
published_at: item.published_at
||
null
,
submission_deadline: item.submission_deadline
||
null
,
opened_at: item.opened_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tender_events = await db.tender_events.bulkCreate(tender_eventsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < tender_events.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tender_events.getTableName(),
belongsToColumn: 'tender_documents',
belongsToId: tender_events[i].id,
},
data[i].tender_documents,
options,
);
}
return tender_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const tender_events = await db.tender_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.reference !== undefined) updatePayload.reference = data.reference;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
if (data.submission_deadline !== undefined) updatePayload.submission_deadline = data.submission_deadline;
if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
updatePayload.updatedById = currentUser.id;
await tender_events.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await tender_events.setTenant(
data.tenant,
{ transaction }
);
}
if (data.procurement_case !== undefined) {
await tender_events.setProcurement_case(
data.procurement_case,
{ transaction }
);
}
if (data.organizations !== undefined) {
await tender_events.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tender_events.getTableName(),
belongsToColumn: 'tender_documents',
belongsToId: tender_events.id,
},
data.tender_documents,
options,
);
return tender_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tender_events = await db.tender_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tender_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tender_events) {
await record.destroy({transaction});
}
});
return tender_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tender_events = await db.tender_events.findByPk(id, options);
await tender_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tender_events.destroy({
transaction
});
return tender_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tender_events = await db.tender_events.findOne(
{ where },
{ transaction },
);
if (!tender_events) {
return tender_events;
}
const output = tender_events.get({plain: true});
output.tenant = await tender_events.getTenant({
transaction
});
output.procurement_case = await tender_events.getProcurement_case({
transaction
});
output.tender_documents = await tender_events.getTender_documents({
transaction
});
output.organizations = await tender_events.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.procurement_cases,
as: 'procurement_case',
where: filter.procurement_case ? {
[Op.or]: [
{ id: { [Op.in]: filter.procurement_case.split('|').map(term => Utils.uuid(term)) } },
{
pipeline_stage: {
[Op.or]: filter.procurement_case.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'tender_documents',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'tender_events',
'reference',
filter.reference,
),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'tender_events',
'title',
filter.title,
),
};
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.submission_deadlineRange) {
const [start, end] = filter.submission_deadlineRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submission_deadline: {
...where.submission_deadline,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submission_deadline: {
...where.submission_deadline,
[Op.lte]: end,
},
};
}
}
if (filter.opened_atRange) {
const [start, end] = filter.opened_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.tender_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'tender_events',
'reference',
query,
),
],
};
}
const records = await db.tender_events.findAll({
attributes: [ 'id', 'reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reference,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,749 @@
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 Workflow_rulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const workflow_rules = await db.workflow_rules.create(
{
id: data.id || undefined,
l1_threshold_usd: data.l1_threshold_usd
||
null
,
l2_threshold_usd: data.l2_threshold_usd
||
null
,
l3_threshold_usd: data.l3_threshold_usd
||
null
,
l4_threshold_usd: data.l4_threshold_usd
||
null
,
sla_approval_hours: data.sla_approval_hours
||
null
,
sla_procurement_hours: data.sla_procurement_hours
||
null
,
sla_reception_hours: data.sla_reception_hours
||
null
,
rate_limit_profile: data.rate_limit_profile
||
null
,
require_reject_reason: data.require_reject_reason
||
false
,
require_return_comment: data.require_return_comment
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await workflow_rules.setTenant( data.tenant || null, {
transaction,
});
await workflow_rules.setOrganizations( data.organizations || null, {
transaction,
});
return workflow_rules;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const workflow_rulesData = data.map((item, index) => ({
id: item.id || undefined,
l1_threshold_usd: item.l1_threshold_usd
||
null
,
l2_threshold_usd: item.l2_threshold_usd
||
null
,
l3_threshold_usd: item.l3_threshold_usd
||
null
,
l4_threshold_usd: item.l4_threshold_usd
||
null
,
sla_approval_hours: item.sla_approval_hours
||
null
,
sla_procurement_hours: item.sla_procurement_hours
||
null
,
sla_reception_hours: item.sla_reception_hours
||
null
,
rate_limit_profile: item.rate_limit_profile
||
null
,
require_reject_reason: item.require_reject_reason
||
false
,
require_return_comment: item.require_return_comment
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const workflow_rules = await db.workflow_rules.bulkCreate(workflow_rulesData, { transaction });
// For each item created, replace relation files
return workflow_rules;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const workflow_rules = await db.workflow_rules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.l1_threshold_usd !== undefined) updatePayload.l1_threshold_usd = data.l1_threshold_usd;
if (data.l2_threshold_usd !== undefined) updatePayload.l2_threshold_usd = data.l2_threshold_usd;
if (data.l3_threshold_usd !== undefined) updatePayload.l3_threshold_usd = data.l3_threshold_usd;
if (data.l4_threshold_usd !== undefined) updatePayload.l4_threshold_usd = data.l4_threshold_usd;
if (data.sla_approval_hours !== undefined) updatePayload.sla_approval_hours = data.sla_approval_hours;
if (data.sla_procurement_hours !== undefined) updatePayload.sla_procurement_hours = data.sla_procurement_hours;
if (data.sla_reception_hours !== undefined) updatePayload.sla_reception_hours = data.sla_reception_hours;
if (data.rate_limit_profile !== undefined) updatePayload.rate_limit_profile = data.rate_limit_profile;
if (data.require_reject_reason !== undefined) updatePayload.require_reject_reason = data.require_reject_reason;
if (data.require_return_comment !== undefined) updatePayload.require_return_comment = data.require_return_comment;
updatePayload.updatedById = currentUser.id;
await workflow_rules.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await workflow_rules.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await workflow_rules.setOrganizations(
data.organizations,
{ transaction }
);
}
return workflow_rules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const workflow_rules = await db.workflow_rules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of workflow_rules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of workflow_rules) {
await record.destroy({transaction});
}
});
return workflow_rules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const workflow_rules = await db.workflow_rules.findByPk(id, options);
await workflow_rules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await workflow_rules.destroy({
transaction
});
return workflow_rules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const workflow_rules = await db.workflow_rules.findOne(
{ where },
{ transaction },
);
if (!workflow_rules) {
return workflow_rules;
}
const output = workflow_rules.get({plain: true});
output.tenant = await workflow_rules.getTenant({
transaction
});
output.organizations = await workflow_rules.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.l1_threshold_usdRange) {
const [start, end] = filter.l1_threshold_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
l1_threshold_usd: {
...where.l1_threshold_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
l1_threshold_usd: {
...where.l1_threshold_usd,
[Op.lte]: end,
},
};
}
}
if (filter.l2_threshold_usdRange) {
const [start, end] = filter.l2_threshold_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
l2_threshold_usd: {
...where.l2_threshold_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
l2_threshold_usd: {
...where.l2_threshold_usd,
[Op.lte]: end,
},
};
}
}
if (filter.l3_threshold_usdRange) {
const [start, end] = filter.l3_threshold_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
l3_threshold_usd: {
...where.l3_threshold_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
l3_threshold_usd: {
...where.l3_threshold_usd,
[Op.lte]: end,
},
};
}
}
if (filter.l4_threshold_usdRange) {
const [start, end] = filter.l4_threshold_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
l4_threshold_usd: {
...where.l4_threshold_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
l4_threshold_usd: {
...where.l4_threshold_usd,
[Op.lte]: end,
},
};
}
}
if (filter.sla_approval_hoursRange) {
const [start, end] = filter.sla_approval_hoursRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sla_approval_hours: {
...where.sla_approval_hours,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sla_approval_hours: {
...where.sla_approval_hours,
[Op.lte]: end,
},
};
}
}
if (filter.sla_procurement_hoursRange) {
const [start, end] = filter.sla_procurement_hoursRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sla_procurement_hours: {
...where.sla_procurement_hours,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sla_procurement_hours: {
...where.sla_procurement_hours,
[Op.lte]: end,
},
};
}
}
if (filter.sla_reception_hoursRange) {
const [start, end] = filter.sla_reception_hoursRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sla_reception_hours: {
...where.sla_reception_hours,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sla_reception_hours: {
...where.sla_reception_hours,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.rate_limit_profile) {
where = {
...where,
rate_limit_profile: filter.rate_limit_profile,
};
}
if (filter.require_reject_reason) {
where = {
...where,
require_reject_reason: filter.require_reject_reason,
};
}
if (filter.require_return_comment) {
where = {
...where,
require_return_comment: filter.require_return_comment,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.workflow_rules.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'workflow_rules',
'rate_limit_profile',
query,
),
],
};
}
const records = await db.workflow_rules.findAll({
attributes: [ 'id', 'rate_limit_profile' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['rate_limit_profile', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.rate_limit_profile,
}));
}
};

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_wwf_drc_procureflow_v2',
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,190 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const access_logs = sequelize.define(
'access_logs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
action: {
type: DataTypes.ENUM,
values: [
"view",
"download",
"export_zip",
"search"
],
},
resource_type: {
type: DataTypes.ENUM,
values: [
"archive_item",
"requisition",
"purchase_order",
"supplier",
"audit_pack"
],
},
resource_reference: {
type: DataTypes.TEXT,
},
ip_address: {
type: DataTypes.TEXT,
},
user_agent: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
access_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.access_logs.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.access_logs.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.access_logs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.access_logs.belongsTo(db.users, {
as: 'createdBy',
});
db.access_logs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return access_logs;
};

View File

@ -0,0 +1,205 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const approval_steps = sequelize.define(
'approval_steps',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
level: {
type: DataTypes.ENUM,
values: [
"L1",
"L2",
"L3",
"L4"
],
},
decision: {
type: DataTypes.ENUM,
values: [
"pending",
"approved",
"rejected",
"returned"
],
},
comment: {
type: DataTypes.TEXT,
},
assigned_at: {
type: DataTypes.DATE,
},
decided_at: {
type: DataTypes.DATE,
},
sla_due_at: {
type: DataTypes.DATE,
},
sla_breached: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
approval_steps.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.approval_steps.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.approval_steps.belongsTo(db.requisitions, {
as: 'requisition',
foreignKey: {
name: 'requisitionId',
},
constraints: false,
});
db.approval_steps.belongsTo(db.users, {
as: 'assigned_approver',
foreignKey: {
name: 'assigned_approverId',
},
constraints: false,
});
db.approval_steps.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.approval_steps.belongsTo(db.users, {
as: 'createdBy',
});
db.approval_steps.belongsTo(db.users, {
as: 'updatedBy',
});
};
return approval_steps;
};

View File

@ -0,0 +1,244 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const archive_items = sequelize.define(
'archive_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
resource_type: {
type: DataTypes.ENUM,
values: [
"requisition",
"approval_step",
"procurement_case",
"tender_event",
"supplier",
"purchase_order",
"grn",
"san",
"discrepancy",
"award",
"offer"
],
},
resource_reference: {
type: DataTypes.TEXT,
},
visibility_scope: {
type: DataTypes.ENUM,
values: [
"role",
"project",
"department",
"restricted"
],
},
title: {
type: DataTypes.TEXT,
},
keywords: {
type: DataTypes.TEXT,
},
amount_usd: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"archived",
"sealed"
],
},
archived_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
archive_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.archive_items.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.archive_items.belongsTo(db.users, {
as: 'archived_by',
foreignKey: {
name: 'archived_byId',
},
constraints: false,
});
db.archive_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.archive_items.hasMany(db.file, {
as: 'files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.archive_items.getTableName(),
belongsToColumn: 'files',
},
});
db.archive_items.belongsTo(db.users, {
as: 'createdBy',
});
db.archive_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return archive_items;
};

View File

@ -0,0 +1,289 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_events = sequelize.define(
'audit_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_id: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
event_type: {
type: DataTypes.ENUM,
values: [
"auth_login",
"auth_logout",
"auth_failed_login",
"user_created",
"user_disabled",
"role_changed",
"requisition_created",
"requisition_submitted",
"requisition_returned",
"requisition_rejected",
"requisition_approved",
"procurement_classified",
"offer_received",
"offer_scored",
"award_made",
"po_issued",
"grn_created",
"san_created",
"discrepancy_reported",
"file_uploaded",
"file_downloaded",
"export_generated",
"settings_changed"
],
},
resource_type: {
type: DataTypes.ENUM,
values: [
"tenant",
"user",
"requisition",
"approval_step",
"procurement_case",
"supplier",
"purchase_order",
"grn",
"san",
"archive_item",
"report",
"settings"
],
},
resource_reference: {
type: DataTypes.TEXT,
},
summary: {
type: DataTypes.TEXT,
},
ip_address: {
type: DataTypes.TEXT,
},
integrity_hash: {
type: DataTypes.TEXT,
},
previous_hash: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
audit_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.audit_events.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.audit_events.belongsTo(db.users, {
as: 'actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.audit_events.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.audit_events.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_events;
};

View File

@ -0,0 +1,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 awards = sequelize.define(
'awards',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
awarded_amount_usd: {
type: DataTypes.DECIMAL,
},
award_rationale: {
type: DataTypes.TEXT,
},
awarded_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
awards.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.awards.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.awards.belongsTo(db.procurement_cases, {
as: 'procurement_case',
foreignKey: {
name: 'procurement_caseId',
},
constraints: false,
});
db.awards.belongsTo(db.supplier_offers, {
as: 'winning_offer',
foreignKey: {
name: 'winning_offerId',
},
constraints: false,
});
db.awards.belongsTo(db.suppliers, {
as: 'awarded_supplier',
foreignKey: {
name: 'awarded_supplierId',
},
constraints: false,
});
db.awards.belongsTo(db.users, {
as: 'awarded_by',
foreignKey: {
name: 'awarded_byId',
},
constraints: false,
});
db.awards.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.awards.hasMany(db.file, {
as: 'award_documents',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.awards.getTableName(),
belongsToColumn: 'award_documents',
},
});
db.awards.belongsTo(db.users, {
as: 'createdBy',
});
db.awards.belongsTo(db.users, {
as: 'updatedBy',
});
};
return awards;
};

View File

@ -0,0 +1,144 @@
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 bid_criteria = sequelize.define(
'bid_criteria',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
weight: {
type: DataTypes.DECIMAL,
},
description: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
bid_criteria.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.bid_criteria.hasMany(db.offer_scores, {
as: 'offer_scores_bid_criterion',
foreignKey: {
name: 'bid_criterionId',
},
constraints: false,
});
//end loop
db.bid_criteria.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.bid_criteria.belongsTo(db.procurement_cases, {
as: 'procurement_case',
foreignKey: {
name: 'procurement_caseId',
},
constraints: false,
});
db.bid_criteria.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.bid_criteria.belongsTo(db.users, {
as: 'createdBy',
});
db.bid_criteria.belongsTo(db.users, {
as: 'updatedBy',
});
};
return bid_criteria;
};

View File

@ -0,0 +1,139 @@
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 budget_lines = sequelize.define(
'budget_lines',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
budget_lines.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.budget_lines.hasMany(db.requisitions, {
as: 'requisitions_budget_line',
foreignKey: {
name: 'budget_lineId',
},
constraints: false,
});
//end loop
db.budget_lines.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.budget_lines.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.budget_lines.belongsTo(db.users, {
as: 'createdBy',
});
db.budget_lines.belongsTo(db.users, {
as: 'updatedBy',
});
};
return budget_lines;
};

View File

@ -0,0 +1,165 @@
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 currency_rates = sequelize.define(
'currency_rates',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
base_currency: {
type: DataTypes.ENUM,
values: [
"USD",
"CDF",
"EUR",
"GBP"
],
},
quote_currency: {
type: DataTypes.ENUM,
values: [
"USD",
"CDF",
"EUR",
"GBP"
],
},
rate: {
type: DataTypes.DECIMAL,
},
effective_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
currency_rates.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.currency_rates.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.currency_rates.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.currency_rates.belongsTo(db.users, {
as: 'createdBy',
});
db.currency_rates.belongsTo(db.users, {
as: 'updatedBy',
});
};
return currency_rates;
};

View File

@ -0,0 +1,147 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const departments = sequelize.define(
'departments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
departments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.departments.hasMany(db.projects, {
as: 'projects_department',
foreignKey: {
name: 'departmentId',
},
constraints: false,
});
db.departments.hasMany(db.requisitions, {
as: 'requisitions_department',
foreignKey: {
name: 'departmentId',
},
constraints: false,
});
//end loop
db.departments.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.departments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.departments.belongsTo(db.users, {
as: 'createdBy',
});
db.departments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return departments;
};

View File

@ -0,0 +1,219 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const discrepancy_cases = sequelize.define(
'discrepancy_cases',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
type: {
type: DataTypes.ENUM,
values: [
"damage",
"missing_quantity",
"wrong_item",
"quality_issue",
"documentation_issue",
"other"
],
},
description: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"in_review",
"resolved",
"cancelled"
],
},
reported_at: {
type: DataTypes.DATE,
},
resolved_at: {
type: DataTypes.DATE,
},
resolution_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
discrepancy_cases.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.discrepancy_cases.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.discrepancy_cases.belongsTo(db.purchase_orders, {
as: 'purchase_order',
foreignKey: {
name: 'purchase_orderId',
},
constraints: false,
});
db.discrepancy_cases.belongsTo(db.goods_receipt_notes, {
as: 'goods_receipt_note',
foreignKey: {
name: 'goods_receipt_noteId',
},
constraints: false,
});
db.discrepancy_cases.belongsTo(db.users, {
as: 'reported_by',
foreignKey: {
name: 'reported_byId',
},
constraints: false,
});
db.discrepancy_cases.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.discrepancy_cases.hasMany(db.file, {
as: 'photos',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.discrepancy_cases.getTableName(),
belongsToColumn: 'photos',
},
});
db.discrepancy_cases.belongsTo(db.users, {
as: 'createdBy',
});
db.discrepancy_cases.belongsTo(db.users, {
as: 'updatedBy',
});
};
return discrepancy_cases;
};

View File

@ -0,0 +1,190 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const export_jobs = sequelize.define(
'export_jobs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
type: {
type: DataTypes.ENUM,
values: [
"excel",
"pdf",
"zip",
"audit_pack"
],
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"completed",
"failed"
],
},
parameters_json: {
type: DataTypes.TEXT,
},
requested_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
export_jobs.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.export_jobs.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.export_jobs.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.export_jobs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.export_jobs.hasMany(db.file, {
as: 'result_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.export_jobs.getTableName(),
belongsToColumn: 'result_files',
},
});
db.export_jobs.belongsTo(db.users, {
as: 'createdBy',
});
db.export_jobs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return export_jobs;
};

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,221 @@
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 goods_receipt_notes = sequelize.define(
'goods_receipt_notes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
grn_number: {
type: DataTypes.TEXT,
},
received_at: {
type: DataTypes.DATE,
},
quality_check: {
type: DataTypes.ENUM,
values: [
"pass",
"partial",
"fail"
],
},
observations: {
type: DataTypes.TEXT,
},
receiver_signature: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"submitted",
"discrepancy_reported",
"accepted",
"rejected"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
goods_receipt_notes.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.goods_receipt_notes.hasMany(db.grn_lines, {
as: 'grn_lines_goods_receipt_note',
foreignKey: {
name: 'goods_receipt_noteId',
},
constraints: false,
});
db.goods_receipt_notes.hasMany(db.discrepancy_cases, {
as: 'discrepancy_cases_goods_receipt_note',
foreignKey: {
name: 'goods_receipt_noteId',
},
constraints: false,
});
//end loop
db.goods_receipt_notes.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.goods_receipt_notes.belongsTo(db.purchase_orders, {
as: 'purchase_order',
foreignKey: {
name: 'purchase_orderId',
},
constraints: false,
});
db.goods_receipt_notes.belongsTo(db.users, {
as: 'received_by',
foreignKey: {
name: 'received_byId',
},
constraints: false,
});
db.goods_receipt_notes.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.goods_receipt_notes.hasMany(db.file, {
as: 'photos',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.goods_receipt_notes.getTableName(),
belongsToColumn: 'photos',
},
});
db.goods_receipt_notes.belongsTo(db.users, {
as: 'createdBy',
});
db.goods_receipt_notes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return goods_receipt_notes;
};

View File

@ -0,0 +1,144 @@
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 grn_lines = sequelize.define(
'grn_lines',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
quantity_received: {
type: DataTypes.INTEGER,
},
quantity_rejected: {
type: DataTypes.INTEGER,
},
remarks: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
grn_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.grn_lines.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.grn_lines.belongsTo(db.goods_receipt_notes, {
as: 'goods_receipt_note',
foreignKey: {
name: 'goods_receipt_noteId',
},
constraints: false,
});
db.grn_lines.belongsTo(db.po_lines, {
as: 'po_line',
foreignKey: {
name: 'po_lineId',
},
constraints: false,
});
db.grn_lines.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.grn_lines.belongsTo(db.users, {
as: 'createdBy',
});
db.grn_lines.belongsTo(db.users, {
as: 'updatedBy',
});
};
return grn_lines;
};

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,188 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const notifications = sequelize.define(
'notifications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
channel: {
type: DataTypes.ENUM,
values: [
"in_app",
"email"
],
},
subject: {
type: DataTypes.TEXT,
},
message: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"sent",
"failed",
"read"
],
},
sent_at: {
type: DataTypes.DATE,
},
read_at: {
type: DataTypes.DATE,
},
related_reference: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notifications.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.notifications.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.notifications.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.notifications.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.notifications.belongsTo(db.users, {
as: 'createdBy',
});
db.notifications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notifications;
};

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 offer_scores = sequelize.define(
'offer_scores',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
score: {
type: DataTypes.DECIMAL,
},
comment: {
type: DataTypes.TEXT,
},
scored_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
offer_scores.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.offer_scores.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.offer_scores.belongsTo(db.supplier_offers, {
as: 'supplier_offer',
foreignKey: {
name: 'supplier_offerId',
},
constraints: false,
});
db.offer_scores.belongsTo(db.bid_criteria, {
as: 'bid_criterion',
foreignKey: {
name: 'bid_criterionId',
},
constraints: false,
});
db.offer_scores.belongsTo(db.users, {
as: 'scored_by',
foreignKey: {
name: 'scored_byId',
},
constraints: false,
});
db.offer_scores.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.offer_scores.belongsTo(db.users, {
as: 'createdBy',
});
db.offer_scores.belongsTo(db.users, {
as: 'updatedBy',
});
};
return offer_scores;
};

View File

@ -0,0 +1,338 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const organizations = sequelize.define(
'organizations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
organizations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.organizations.hasMany(db.users, {
as: 'users_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.tenants, {
as: 'tenants_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.departments, {
as: 'departments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.projects, {
as: 'projects_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.budget_lines, {
as: 'budget_lines_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.workflow_rules, {
as: 'workflow_rules_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.currency_rates, {
as: 'currency_rates_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.requisitions, {
as: 'requisitions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.approval_steps, {
as: 'approval_steps_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.procurement_cases, {
as: 'procurement_cases_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.suppliers, {
as: 'suppliers_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.supplier_categories, {
as: 'supplier_categories_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.supplier_diligence_checks, {
as: 'supplier_diligence_checks_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.tender_events, {
as: 'tender_events_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.supplier_offers, {
as: 'supplier_offers_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.bid_criteria, {
as: 'bid_criteria_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.offer_scores, {
as: 'offer_scores_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.awards, {
as: 'awards_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.purchase_orders, {
as: 'purchase_orders_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.po_lines, {
as: 'po_lines_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.goods_receipt_notes, {
as: 'goods_receipt_notes_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.grn_lines, {
as: 'grn_lines_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.service_acceptance_notes, {
as: 'service_acceptance_notes_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.discrepancy_cases, {
as: 'discrepancy_cases_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.archive_items, {
as: 'archive_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.access_logs, {
as: 'access_logs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.notifications, {
as: 'notifications_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.audit_events, {
as: 'audit_events_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.export_jobs, {
as: 'export_jobs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.sessions, {
as: 'sessions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
//end loop
db.organizations.belongsTo(db.users, {
as: 'createdBy',
});
db.organizations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return organizations;
};

View File

@ -0,0 +1,98 @@
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 po_lines = sequelize.define(
'po_lines',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
item_name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
quantity_ordered: {
type: DataTypes.INTEGER,
},
unit_price: {
type: DataTypes.DECIMAL,
},
line_total: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
po_lines.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.po_lines.hasMany(db.grn_lines, {
as: 'grn_lines_po_line',
foreignKey: {
name: 'po_lineId',
},
constraints: false,
});
//end loop
db.po_lines.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.po_lines.belongsTo(db.purchase_orders, {
as: 'purchase_order',
foreignKey: {
name: 'purchase_orderId',
},
constraints: false,
});
db.po_lines.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.po_lines.belongsTo(db.users, {
as: 'createdBy',
});
db.po_lines.belongsTo(db.users, {
as: 'updatedBy',
});
};
return po_lines;
};

View File

@ -0,0 +1,250 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const procurement_cases = sequelize.define(
'procurement_cases',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
classification: {
type: DataTypes.ENUM,
values: [
"direct_purchase",
"pre_qualified",
"multiple_quotations",
"public_tender",
"single_source"
],
},
classification_justification: {
type: DataTypes.TEXT,
},
pipeline_stage: {
type: DataTypes.ENUM,
values: [
"a_classifier",
"sourcing",
"analyse_offres",
"attribuee",
"cloturee"
],
},
started_at: {
type: DataTypes.DATE,
},
sla_due_at: {
type: DataTypes.DATE,
},
awarded_at: {
type: DataTypes.DATE,
},
closed_at: {
type: DataTypes.DATE,
},
admin_override_single_source: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
procurement_cases.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.procurement_cases.hasMany(db.tender_events, {
as: 'tender_events_procurement_case',
foreignKey: {
name: 'procurement_caseId',
},
constraints: false,
});
db.procurement_cases.hasMany(db.supplier_offers, {
as: 'supplier_offers_procurement_case',
foreignKey: {
name: 'procurement_caseId',
},
constraints: false,
});
db.procurement_cases.hasMany(db.bid_criteria, {
as: 'bid_criteria_procurement_case',
foreignKey: {
name: 'procurement_caseId',
},
constraints: false,
});
db.procurement_cases.hasMany(db.awards, {
as: 'awards_procurement_case',
foreignKey: {
name: 'procurement_caseId',
},
constraints: false,
});
//end loop
db.procurement_cases.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.procurement_cases.belongsTo(db.requisitions, {
as: 'requisition',
foreignKey: {
name: 'requisitionId',
},
constraints: false,
});
db.procurement_cases.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.procurement_cases.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.procurement_cases.belongsTo(db.users, {
as: 'createdBy',
});
db.procurement_cases.belongsTo(db.users, {
as: 'updatedBy',
});
};
return procurement_cases;
};

View File

@ -0,0 +1,147 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const projects = sequelize.define(
'projects',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
projects.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.projects.hasMany(db.requisitions, {
as: 'requisitions_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
//end loop
db.projects.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.projects.belongsTo(db.departments, {
as: 'department',
foreignKey: {
name: 'departmentId',
},
constraints: false,
});
db.projects.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.projects.belongsTo(db.users, {
as: 'createdBy',
});
db.projects.belongsTo(db.users, {
as: 'updatedBy',
});
};
return projects;
};

View File

@ -0,0 +1,247 @@
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,
},
po_number: {
type: DataTypes.TEXT,
},
total_amount_usd: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.ENUM,
values: [
"USD",
"CDF",
"EUR",
"GBP"
],
},
total_amount_original: {
type: DataTypes.DECIMAL,
},
issued_at: {
type: DataTypes.DATE,
},
expected_delivery_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"issued",
"partially_received",
"received",
"cancelled"
],
},
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.po_lines, {
as: 'po_lines_purchase_order',
foreignKey: {
name: 'purchase_orderId',
},
constraints: false,
});
db.purchase_orders.hasMany(db.goods_receipt_notes, {
as: 'goods_receipt_notes_purchase_order',
foreignKey: {
name: 'purchase_orderId',
},
constraints: false,
});
db.purchase_orders.hasMany(db.service_acceptance_notes, {
as: 'service_acceptance_notes_purchase_order',
foreignKey: {
name: 'purchase_orderId',
},
constraints: false,
});
db.purchase_orders.hasMany(db.discrepancy_cases, {
as: 'discrepancy_cases_purchase_order',
foreignKey: {
name: 'purchase_orderId',
},
constraints: false,
});
//end loop
db.purchase_orders.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.purchase_orders.belongsTo(db.requisitions, {
as: 'requisition',
foreignKey: {
name: 'requisitionId',
},
constraints: false,
});
db.purchase_orders.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.purchase_orders.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.purchase_orders.hasMany(db.file, {
as: 'po_documents',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.purchase_orders.getTableName(),
belongsToColumn: 'po_documents',
},
});
db.purchase_orders.belongsTo(db.users, {
as: 'createdBy',
});
db.purchase_orders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return purchase_orders;
};

View File

@ -0,0 +1,332 @@
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 requisitions = sequelize.define(
'requisitions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
req_number: {
type: DataTypes.TEXT,
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
quantity: {
type: DataTypes.INTEGER,
},
estimated_budget_usd: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.ENUM,
values: [
"USD",
"CDF",
"EUR",
"GBP"
],
},
estimated_budget_original: {
type: DataTypes.DECIMAL,
},
fx_rate_to_usd: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"submitted",
"in_approval",
"approved",
"rejected",
"in_procurement",
"awarded",
"in_delivery",
"received",
"closed",
"returned"
],
},
submitted_at: {
type: DataTypes.DATE,
},
approved_at: {
type: DataTypes.DATE,
},
closed_at: {
type: DataTypes.DATE,
},
return_reason: {
type: DataTypes.TEXT,
},
reject_reason: {
type: DataTypes.TEXT,
},
is_high_value: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
requisitions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.requisitions.hasMany(db.approval_steps, {
as: 'approval_steps_requisition',
foreignKey: {
name: 'requisitionId',
},
constraints: false,
});
db.requisitions.hasMany(db.procurement_cases, {
as: 'procurement_cases_requisition',
foreignKey: {
name: 'requisitionId',
},
constraints: false,
});
db.requisitions.hasMany(db.purchase_orders, {
as: 'purchase_orders_requisition',
foreignKey: {
name: 'requisitionId',
},
constraints: false,
});
//end loop
db.requisitions.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.requisitions.belongsTo(db.users, {
as: 'requester',
foreignKey: {
name: 'requesterId',
},
constraints: false,
});
db.requisitions.belongsTo(db.departments, {
as: 'department',
foreignKey: {
name: 'departmentId',
},
constraints: false,
});
db.requisitions.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.requisitions.belongsTo(db.budget_lines, {
as: 'budget_line',
foreignKey: {
name: 'budget_lineId',
},
constraints: false,
});
db.requisitions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.requisitions.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.requisitions.getTableName(),
belongsToColumn: 'attachments',
},
});
db.requisitions.belongsTo(db.users, {
as: 'createdBy',
});
db.requisitions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return requisitions;
};

View File

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

View File

@ -0,0 +1,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 service_acceptance_notes = sequelize.define(
'service_acceptance_notes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
san_number: {
type: DataTypes.TEXT,
},
acceptance_date: {
type: DataTypes.DATE,
},
deliverable_checklist: {
type: DataTypes.TEXT,
},
acceptance_criteria: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"submitted",
"accepted",
"rejected"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
service_acceptance_notes.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.service_acceptance_notes.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.service_acceptance_notes.belongsTo(db.purchase_orders, {
as: 'purchase_order',
foreignKey: {
name: 'purchase_orderId',
},
constraints: false,
});
db.service_acceptance_notes.belongsTo(db.users, {
as: 'accepted_by',
foreignKey: {
name: 'accepted_byId',
},
constraints: false,
});
db.service_acceptance_notes.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.service_acceptance_notes.hasMany(db.file, {
as: 'evidence_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.service_acceptance_notes.getTableName(),
belongsToColumn: 'evidence_files',
},
});
db.service_acceptance_notes.belongsTo(db.users, {
as: 'createdBy',
});
db.service_acceptance_notes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return service_acceptance_notes;
};

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 sessions = sequelize.define(
'sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
refresh_token_hash: {
type: DataTypes.TEXT,
},
created_at_time: {
type: DataTypes.DATE,
},
expires_at: {
type: DataTypes.DATE,
},
revoked_at: {
type: DataTypes.DATE,
},
ip_address: {
type: DataTypes.TEXT,
},
user_agent: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
sessions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.sessions.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.sessions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.sessions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return sessions;
};

View File

@ -0,0 +1,121 @@
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 supplier_categories = sequelize.define(
'supplier_categories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
supplier_categories.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.supplier_categories.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.supplier_categories.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.supplier_categories.belongsTo(db.users, {
as: 'createdBy',
});
db.supplier_categories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return supplier_categories;
};

View File

@ -0,0 +1,191 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const supplier_diligence_checks = sequelize.define(
'supplier_diligence_checks',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
check_type: {
type: DataTypes.ENUM,
values: [
"sanctions",
"financial_health",
"references",
"legal_documents",
"site_visit"
],
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"passed",
"failed"
],
},
notes: {
type: DataTypes.TEXT,
},
checked_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
supplier_diligence_checks.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.supplier_diligence_checks.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.supplier_diligence_checks.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.supplier_diligence_checks.belongsTo(db.users, {
as: 'checked_by',
foreignKey: {
name: 'checked_byId',
},
constraints: false,
});
db.supplier_diligence_checks.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.supplier_diligence_checks.hasMany(db.file, {
as: 'evidence_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.supplier_diligence_checks.getTableName(),
belongsToColumn: 'evidence_files',
},
});
db.supplier_diligence_checks.belongsTo(db.users, {
as: 'createdBy',
});
db.supplier_diligence_checks.belongsTo(db.users, {
as: 'updatedBy',
});
};
return supplier_diligence_checks;
};

View File

@ -0,0 +1,231 @@
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 supplier_offers = sequelize.define(
'supplier_offers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.ENUM,
values: [
"USD",
"CDF",
"EUR",
"GBP"
],
},
amount_usd: {
type: DataTypes.DECIMAL,
},
delivery_lead_time: {
type: DataTypes.TEXT,
},
warranty_terms: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"received",
"evaluated",
"shortlisted",
"rejected",
"awarded"
],
},
received_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
supplier_offers.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.supplier_offers.hasMany(db.offer_scores, {
as: 'offer_scores_supplier_offer',
foreignKey: {
name: 'supplier_offerId',
},
constraints: false,
});
db.supplier_offers.hasMany(db.awards, {
as: 'awards_winning_offer',
foreignKey: {
name: 'winning_offerId',
},
constraints: false,
});
//end loop
db.supplier_offers.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.supplier_offers.belongsTo(db.procurement_cases, {
as: 'procurement_case',
foreignKey: {
name: 'procurement_caseId',
},
constraints: false,
});
db.supplier_offers.belongsTo(db.suppliers, {
as: 'supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.supplier_offers.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.supplier_offers.hasMany(db.file, {
as: 'offer_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.supplier_offers.getTableName(),
belongsToColumn: 'offer_files',
},
});
db.supplier_offers.belongsTo(db.users, {
as: 'createdBy',
});
db.supplier_offers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return supplier_offers;
};

View File

@ -0,0 +1,317 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const suppliers = sequelize.define(
'suppliers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
legal_name: {
type: DataTypes.TEXT,
},
commercial_name: {
type: DataTypes.TEXT,
},
rccm_number: {
type: DataTypes.TEXT,
},
tax_id: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.ENUM,
values: [
"CD",
"CM",
"GA",
"MG",
"KE",
"TZ",
"FR",
"BE",
"US",
"UK",
"OTHER"
],
},
address: {
type: DataTypes.TEXT,
},
primary_contact_name: {
type: DataTypes.TEXT,
},
primary_contact_email: {
type: DataTypes.TEXT,
},
primary_contact_phone: {
type: DataTypes.TEXT,
},
bank_name: {
type: DataTypes.TEXT,
},
bank_account_number: {
type: DataTypes.TEXT,
},
bank_swift: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"active",
"blocked"
],
},
prequalification_status: {
type: DataTypes.ENUM,
values: [
"not_started",
"in_review",
"validated",
"rejected"
],
},
performance_score: {
type: DataTypes.DECIMAL,
},
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.supplier_diligence_checks, {
as: 'supplier_diligence_checks_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.suppliers.hasMany(db.supplier_offers, {
as: 'supplier_offers_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
db.suppliers.hasMany(db.awards, {
as: 'awards_awarded_supplier',
foreignKey: {
name: 'awarded_supplierId',
},
constraints: false,
});
db.suppliers.hasMany(db.purchase_orders, {
as: 'purchase_orders_supplier',
foreignKey: {
name: 'supplierId',
},
constraints: false,
});
//end loop
db.suppliers.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.suppliers.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.suppliers.hasMany(db.file, {
as: 'documents',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.suppliers.getTableName(),
belongsToColumn: 'documents',
},
});
db.suppliers.belongsTo(db.users, {
as: 'createdBy',
});
db.suppliers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return suppliers;
};

View File

@ -0,0 +1,474 @@
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 tenants = sequelize.define(
'tenants',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
subdomain: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"suspended",
"pending_setup"
],
},
tagline: {
type: DataTypes.TEXT,
},
primary_color: {
type: DataTypes.TEXT,
},
secondary_color: {
type: DataTypes.TEXT,
},
default_language: {
type: DataTypes.ENUM,
values: [
"fr",
"en"
],
},
primary_currency: {
type: DataTypes.ENUM,
values: [
"USD",
"CDF",
"EUR",
"GBP"
],
},
secondary_currency: {
type: DataTypes.ENUM,
values: [
"none",
"USD",
"CDF",
"EUR",
"GBP"
],
},
sso_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
suspended_on: {
type: DataTypes.DATE,
},
data_retention_policy: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tenants.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.tenants.hasMany(db.departments, {
as: 'departments_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.projects, {
as: 'projects_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.budget_lines, {
as: 'budget_lines_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.workflow_rules, {
as: 'workflow_rules_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.currency_rates, {
as: 'currency_rates_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.requisitions, {
as: 'requisitions_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.approval_steps, {
as: 'approval_steps_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.procurement_cases, {
as: 'procurement_cases_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.suppliers, {
as: 'suppliers_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.supplier_categories, {
as: 'supplier_categories_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.supplier_diligence_checks, {
as: 'supplier_diligence_checks_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.tender_events, {
as: 'tender_events_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.supplier_offers, {
as: 'supplier_offers_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.bid_criteria, {
as: 'bid_criteria_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.offer_scores, {
as: 'offer_scores_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.awards, {
as: 'awards_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.purchase_orders, {
as: 'purchase_orders_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.po_lines, {
as: 'po_lines_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.goods_receipt_notes, {
as: 'goods_receipt_notes_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.grn_lines, {
as: 'grn_lines_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.service_acceptance_notes, {
as: 'service_acceptance_notes_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.discrepancy_cases, {
as: 'discrepancy_cases_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.archive_items, {
as: 'archive_items_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.access_logs, {
as: 'access_logs_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.notifications, {
as: 'notifications_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.audit_events, {
as: 'audit_events_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.export_jobs, {
as: 'export_jobs_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.sessions, {
as: 'sessions_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
//end loop
db.tenants.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.tenants.hasMany(db.file, {
as: 'logo',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.tenants.getTableName(),
belongsToColumn: 'logo',
},
});
db.tenants.belongsTo(db.users, {
as: 'createdBy',
});
db.tenants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tenants;
};

View File

@ -0,0 +1,182 @@
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 tender_events = sequelize.define(
'tender_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
reference: {
type: DataTypes.TEXT,
},
title: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"closed",
"cancelled"
],
},
published_at: {
type: DataTypes.DATE,
},
submission_deadline: {
type: DataTypes.DATE,
},
opened_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tender_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.tender_events.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tender_events.belongsTo(db.procurement_cases, {
as: 'procurement_case',
foreignKey: {
name: 'procurement_caseId',
},
constraints: false,
});
db.tender_events.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.tender_events.hasMany(db.file, {
as: 'tender_documents',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.tender_events.getTableName(),
belongsToColumn: 'tender_documents',
},
});
db.tender_events.belongsTo(db.users, {
as: 'createdBy',
});
db.tender_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tender_events;
};

View File

@ -0,0 +1,384 @@
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.requisitions, {
as: 'requisitions_requester',
foreignKey: {
name: 'requesterId',
},
constraints: false,
});
db.users.hasMany(db.approval_steps, {
as: 'approval_steps_assigned_approver',
foreignKey: {
name: 'assigned_approverId',
},
constraints: false,
});
db.users.hasMany(db.procurement_cases, {
as: 'procurement_cases_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.supplier_diligence_checks, {
as: 'supplier_diligence_checks_checked_by',
foreignKey: {
name: 'checked_byId',
},
constraints: false,
});
db.users.hasMany(db.offer_scores, {
as: 'offer_scores_scored_by',
foreignKey: {
name: 'scored_byId',
},
constraints: false,
});
db.users.hasMany(db.awards, {
as: 'awards_awarded_by',
foreignKey: {
name: 'awarded_byId',
},
constraints: false,
});
db.users.hasMany(db.goods_receipt_notes, {
as: 'goods_receipt_notes_received_by',
foreignKey: {
name: 'received_byId',
},
constraints: false,
});
db.users.hasMany(db.service_acceptance_notes, {
as: 'service_acceptance_notes_accepted_by',
foreignKey: {
name: 'accepted_byId',
},
constraints: false,
});
db.users.hasMany(db.discrepancy_cases, {
as: 'discrepancy_cases_reported_by',
foreignKey: {
name: 'reported_byId',
},
constraints: false,
});
db.users.hasMany(db.archive_items, {
as: 'archive_items_archived_by',
foreignKey: {
name: 'archived_byId',
},
constraints: false,
});
db.users.hasMany(db.access_logs, {
as: 'access_logs_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.notifications, {
as: 'notifications_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.audit_events, {
as: 'audit_events_actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.users.hasMany(db.export_jobs, {
as: 'export_jobs_requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.users.hasMany(db.sessions, {
as: 'sessions_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

View File

@ -0,0 +1,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 workflow_rules = sequelize.define(
'workflow_rules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
l1_threshold_usd: {
type: DataTypes.DECIMAL,
},
l2_threshold_usd: {
type: DataTypes.DECIMAL,
},
l3_threshold_usd: {
type: DataTypes.DECIMAL,
},
l4_threshold_usd: {
type: DataTypes.DECIMAL,
},
sla_approval_hours: {
type: DataTypes.INTEGER,
},
sla_procurement_hours: {
type: DataTypes.INTEGER,
},
sla_reception_hours: {
type: DataTypes.INTEGER,
},
rate_limit_profile: {
type: DataTypes.ENUM,
values: [
"standard",
"strict",
"custom"
],
},
require_reject_reason: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
require_return_comment: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
workflow_rules.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.workflow_rules.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.workflow_rules.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.workflow_rules.belongsTo(db.users, {
as: 'createdBy',
});
db.workflow_rules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return workflow_rules;
};

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

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

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

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

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

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

@ -0,0 +1,263 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const organizationForAuthRoutes = require('./routes/organizationLogin');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const organizationsRoutes = require('./routes/organizations');
const tenantsRoutes = require('./routes/tenants');
const departmentsRoutes = require('./routes/departments');
const projectsRoutes = require('./routes/projects');
const budget_linesRoutes = require('./routes/budget_lines');
const workflow_rulesRoutes = require('./routes/workflow_rules');
const currency_ratesRoutes = require('./routes/currency_rates');
const requisitionsRoutes = require('./routes/requisitions');
const approval_stepsRoutes = require('./routes/approval_steps');
const procurement_casesRoutes = require('./routes/procurement_cases');
const suppliersRoutes = require('./routes/suppliers');
const supplier_categoriesRoutes = require('./routes/supplier_categories');
const supplier_diligence_checksRoutes = require('./routes/supplier_diligence_checks');
const tender_eventsRoutes = require('./routes/tender_events');
const supplier_offersRoutes = require('./routes/supplier_offers');
const bid_criteriaRoutes = require('./routes/bid_criteria');
const offer_scoresRoutes = require('./routes/offer_scores');
const awardsRoutes = require('./routes/awards');
const purchase_ordersRoutes = require('./routes/purchase_orders');
const po_linesRoutes = require('./routes/po_lines');
const goods_receipt_notesRoutes = require('./routes/goods_receipt_notes');
const grn_linesRoutes = require('./routes/grn_lines');
const service_acceptance_notesRoutes = require('./routes/service_acceptance_notes');
const discrepancy_casesRoutes = require('./routes/discrepancy_cases');
const archive_itemsRoutes = require('./routes/archive_items');
const access_logsRoutes = require('./routes/access_logs');
const notificationsRoutes = require('./routes/notifications');
const audit_eventsRoutes = require('./routes/audit_events');
const export_jobsRoutes = require('./routes/export_jobs');
const sessionsRoutes = require('./routes/sessions');
const getBaseUrl = (url) => {
if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url;
};
const options = {
definition: {
openapi: "3.0.0",
info: {
version: "1.0.0",
title: "WWF-DRC ProcureFlow v2",
description: "WWF-DRC ProcureFlow v2 Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
},
servers: [
{
url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
description: "Development server",
}
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
},
responses: {
UnauthorizedError: {
description: "Access token is missing or invalid"
}
}
},
security: [{
bearerAuth: []
}]
},
apis: ["./src/routes/*.js"],
};
const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
next()
}, swaggerUI.serve, swaggerUI.setup(specs))
app.use(cors({origin: true}));
require('./auth/auth');
app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');
app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);
app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);
app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);
app.use('/api/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);
app.use('/api/tenants', passport.authenticate('jwt', {session: false}), tenantsRoutes);
app.use('/api/departments', passport.authenticate('jwt', {session: false}), departmentsRoutes);
app.use('/api/projects', passport.authenticate('jwt', {session: false}), projectsRoutes);
app.use('/api/budget_lines', passport.authenticate('jwt', {session: false}), budget_linesRoutes);
app.use('/api/workflow_rules', passport.authenticate('jwt', {session: false}), workflow_rulesRoutes);
app.use('/api/currency_rates', passport.authenticate('jwt', {session: false}), currency_ratesRoutes);
app.use('/api/requisitions', passport.authenticate('jwt', {session: false}), requisitionsRoutes);
app.use('/api/approval_steps', passport.authenticate('jwt', {session: false}), approval_stepsRoutes);
app.use('/api/procurement_cases', passport.authenticate('jwt', {session: false}), procurement_casesRoutes);
app.use('/api/suppliers', passport.authenticate('jwt', {session: false}), suppliersRoutes);
app.use('/api/supplier_categories', passport.authenticate('jwt', {session: false}), supplier_categoriesRoutes);
app.use('/api/supplier_diligence_checks', passport.authenticate('jwt', {session: false}), supplier_diligence_checksRoutes);
app.use('/api/tender_events', passport.authenticate('jwt', {session: false}), tender_eventsRoutes);
app.use('/api/supplier_offers', passport.authenticate('jwt', {session: false}), supplier_offersRoutes);
app.use('/api/bid_criteria', passport.authenticate('jwt', {session: false}), bid_criteriaRoutes);
app.use('/api/offer_scores', passport.authenticate('jwt', {session: false}), offer_scoresRoutes);
app.use('/api/awards', passport.authenticate('jwt', {session: false}), awardsRoutes);
app.use('/api/purchase_orders', passport.authenticate('jwt', {session: false}), purchase_ordersRoutes);
app.use('/api/po_lines', passport.authenticate('jwt', {session: false}), po_linesRoutes);
app.use('/api/goods_receipt_notes', passport.authenticate('jwt', {session: false}), goods_receipt_notesRoutes);
app.use('/api/grn_lines', passport.authenticate('jwt', {session: false}), grn_linesRoutes);
app.use('/api/service_acceptance_notes', passport.authenticate('jwt', {session: false}), service_acceptance_notesRoutes);
app.use('/api/discrepancy_cases', passport.authenticate('jwt', {session: false}), discrepancy_casesRoutes);
app.use('/api/archive_items', passport.authenticate('jwt', {session: false}), archive_itemsRoutes);
app.use('/api/access_logs', passport.authenticate('jwt', {session: false}), access_logsRoutes);
app.use('/api/notifications', passport.authenticate('jwt', {session: false}), notificationsRoutes);
app.use('/api/audit_events', passport.authenticate('jwt', {session: false}), audit_eventsRoutes);
app.use('/api/export_jobs', passport.authenticate('jwt', {session: false}), export_jobsRoutes);
app.use('/api/sessions', passport.authenticate('jwt', {session: false}), sessionsRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
app.use(
'/api/org-for-auth',
organizationForAuthRoutes,
);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
module.exports = app;

View File

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

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