Initial version

This commit is contained in:
Flatlogic Bot 2026-06-21 21:31:49 +00:00
commit 864cabd38c
601 changed files with 223483 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>VORTA ResellerOS</h2>
<p>AI-powered SaaS to manage reseller networks, stock, orders, commissions, referrals, and analytics in one dashboard.</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 @@
# VORTA ResellerOS
## 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 @@
#VORTA ResellerOS - 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_vorta_reselleros;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_vorta_reselleros 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": "vortareselleros",
"description": "VORTA ResellerOS - 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: "2b2d02aa",
user_pass: "ba2c29cb57eb",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '2b2d02aa-6e8d-4f83-9c35-ba2c29cb57eb',
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: 'VORTA ResellerOS <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: 'Reseller Leader',
},
project_uuid: '2b2d02aa-6e8d-4f83-9c35-ba2c29cb57eb',
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 = 'Growing tree with branching roots';
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,737 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Ai_insightsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_insights = await db.ai_insights.create(
{
id: data.id || undefined,
insight_type: data.insight_type
||
null
,
severity: data.severity
||
null
,
insight_title: data.insight_title
||
null
,
insight_summary: data.insight_summary
||
null
,
recommendation: data.recommendation
||
null
,
generated_at: data.generated_at
||
null
,
valid_until: data.valid_until
||
null
,
is_acknowledged: data.is_acknowledged
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_insights.setTenant( data.tenant || null, {
transaction,
});
await ai_insights.setRelated_user( data.related_user || null, {
transaction,
});
await ai_insights.setRelated_product( data.related_product || null, {
transaction,
});
await ai_insights.setRelated_warehouse( data.related_warehouse || null, {
transaction,
});
await ai_insights.setOrganizations( data.organizations || null, {
transaction,
});
return ai_insights;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const ai_insightsData = data.map((item, index) => ({
id: item.id || undefined,
insight_type: item.insight_type
||
null
,
severity: item.severity
||
null
,
insight_title: item.insight_title
||
null
,
insight_summary: item.insight_summary
||
null
,
recommendation: item.recommendation
||
null
,
generated_at: item.generated_at
||
null
,
valid_until: item.valid_until
||
null
,
is_acknowledged: item.is_acknowledged
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ai_insights = await db.ai_insights.bulkCreate(ai_insightsData, { transaction });
// For each item created, replace relation files
return ai_insights;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const ai_insights = await db.ai_insights.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.insight_type !== undefined) updatePayload.insight_type = data.insight_type;
if (data.severity !== undefined) updatePayload.severity = data.severity;
if (data.insight_title !== undefined) updatePayload.insight_title = data.insight_title;
if (data.insight_summary !== undefined) updatePayload.insight_summary = data.insight_summary;
if (data.recommendation !== undefined) updatePayload.recommendation = data.recommendation;
if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
if (data.valid_until !== undefined) updatePayload.valid_until = data.valid_until;
if (data.is_acknowledged !== undefined) updatePayload.is_acknowledged = data.is_acknowledged;
updatePayload.updatedById = currentUser.id;
await ai_insights.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await ai_insights.setTenant(
data.tenant,
{ transaction }
);
}
if (data.related_user !== undefined) {
await ai_insights.setRelated_user(
data.related_user,
{ transaction }
);
}
if (data.related_product !== undefined) {
await ai_insights.setRelated_product(
data.related_product,
{ transaction }
);
}
if (data.related_warehouse !== undefined) {
await ai_insights.setRelated_warehouse(
data.related_warehouse,
{ transaction }
);
}
if (data.organizations !== undefined) {
await ai_insights.setOrganizations(
data.organizations,
{ transaction }
);
}
return ai_insights;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_insights = await db.ai_insights.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ai_insights) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ai_insights) {
await record.destroy({transaction});
}
});
return ai_insights;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_insights = await db.ai_insights.findByPk(id, options);
await ai_insights.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ai_insights.destroy({
transaction
});
return ai_insights;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ai_insights = await db.ai_insights.findOne(
{ where },
{ transaction },
);
if (!ai_insights) {
return ai_insights;
}
const output = ai_insights.get({plain: true});
output.tenant = await ai_insights.getTenant({
transaction
});
output.related_user = await ai_insights.getRelated_user({
transaction
});
output.related_product = await ai_insights.getRelated_product({
transaction
});
output.related_warehouse = await ai_insights.getRelated_warehouse({
transaction
});
output.organizations = await ai_insights.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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'related_user',
where: filter.related_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.related_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.related_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.products,
as: 'related_product',
where: filter.related_product ? {
[Op.or]: [
{ id: { [Op.in]: filter.related_product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.related_product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.warehouses,
as: 'related_warehouse',
where: filter.related_warehouse ? {
[Op.or]: [
{ id: { [Op.in]: filter.related_warehouse.split('|').map(term => Utils.uuid(term)) } },
{
warehouse_name: {
[Op.or]: filter.related_warehouse.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.insight_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_insights',
'insight_title',
filter.insight_title,
),
};
}
if (filter.insight_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_insights',
'insight_summary',
filter.insight_summary,
),
};
}
if (filter.recommendation) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_insights',
'recommendation',
filter.recommendation,
),
};
}
if (filter.generated_atRange) {
const [start, end] = filter.generated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
generated_at: {
...where.generated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
generated_at: {
...where.generated_at,
[Op.lte]: end,
},
};
}
}
if (filter.valid_untilRange) {
const [start, end] = filter.valid_untilRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
valid_until: {
...where.valid_until,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
valid_until: {
...where.valid_until,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.insight_type) {
where = {
...where,
insight_type: filter.insight_type,
};
}
if (filter.severity) {
where = {
...where,
severity: filter.severity,
};
}
if (filter.is_acknowledged) {
where = {
...where,
is_acknowledged: filter.is_acknowledged,
};
}
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.ai_insights.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'ai_insights',
'insight_title',
query,
),
],
};
}
const records = await db.ai_insights.findAll({
attributes: [ 'id', 'insight_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['insight_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.insight_title,
}));
}
};

View File

@ -0,0 +1,753 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Bonus_programsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bonus_programs = await db.bonus_programs.create(
{
id: data.id || undefined,
program_name: data.program_name
||
null
,
program_status: data.program_status
||
null
,
target_metric: data.target_metric
||
null
,
target_value: data.target_value
||
null
,
reward_type: data.reward_type
||
null
,
reward_rate: data.reward_rate
||
null
,
reward_amount: data.reward_amount
||
null
,
gift_description: data.gift_description
||
null
,
starts_at: data.starts_at
||
null
,
ends_at: data.ends_at
||
null
,
terms: data.terms
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await bonus_programs.setTenant( data.tenant || null, {
transaction,
});
await bonus_programs.setOrganizations( data.organizations || null, {
transaction,
});
return bonus_programs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const bonus_programsData = data.map((item, index) => ({
id: item.id || undefined,
program_name: item.program_name
||
null
,
program_status: item.program_status
||
null
,
target_metric: item.target_metric
||
null
,
target_value: item.target_value
||
null
,
reward_type: item.reward_type
||
null
,
reward_rate: item.reward_rate
||
null
,
reward_amount: item.reward_amount
||
null
,
gift_description: item.gift_description
||
null
,
starts_at: item.starts_at
||
null
,
ends_at: item.ends_at
||
null
,
terms: item.terms
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const bonus_programs = await db.bonus_programs.bulkCreate(bonus_programsData, { transaction });
// For each item created, replace relation files
return bonus_programs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const bonus_programs = await db.bonus_programs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.program_name !== undefined) updatePayload.program_name = data.program_name;
if (data.program_status !== undefined) updatePayload.program_status = data.program_status;
if (data.target_metric !== undefined) updatePayload.target_metric = data.target_metric;
if (data.target_value !== undefined) updatePayload.target_value = data.target_value;
if (data.reward_type !== undefined) updatePayload.reward_type = data.reward_type;
if (data.reward_rate !== undefined) updatePayload.reward_rate = data.reward_rate;
if (data.reward_amount !== undefined) updatePayload.reward_amount = data.reward_amount;
if (data.gift_description !== undefined) updatePayload.gift_description = data.gift_description;
if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
if (data.terms !== undefined) updatePayload.terms = data.terms;
updatePayload.updatedById = currentUser.id;
await bonus_programs.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await bonus_programs.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await bonus_programs.setOrganizations(
data.organizations,
{ transaction }
);
}
return bonus_programs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const bonus_programs = await db.bonus_programs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of bonus_programs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of bonus_programs) {
await record.destroy({transaction});
}
});
return bonus_programs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const bonus_programs = await db.bonus_programs.findByPk(id, options);
await bonus_programs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await bonus_programs.destroy({
transaction
});
return bonus_programs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const bonus_programs = await db.bonus_programs.findOne(
{ where },
{ transaction },
);
if (!bonus_programs) {
return bonus_programs;
}
const output = bonus_programs.get({plain: true});
output.tenant = await bonus_programs.getTenant({
transaction
});
output.organizations = await bonus_programs.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)) } },
{
tenant_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.program_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'bonus_programs',
'program_name',
filter.program_name,
),
};
}
if (filter.gift_description) {
where = {
...where,
[Op.and]: Utils.ilike(
'bonus_programs',
'gift_description',
filter.gift_description,
),
};
}
if (filter.terms) {
where = {
...where,
[Op.and]: Utils.ilike(
'bonus_programs',
'terms',
filter.terms,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
starts_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ends_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.target_valueRange) {
const [start, end] = filter.target_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.lte]: end,
},
};
}
}
if (filter.reward_rateRange) {
const [start, end] = filter.reward_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reward_rate: {
...where.reward_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reward_rate: {
...where.reward_rate,
[Op.lte]: end,
},
};
}
}
if (filter.reward_amountRange) {
const [start, end] = filter.reward_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reward_amount: {
...where.reward_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reward_amount: {
...where.reward_amount,
[Op.lte]: end,
},
};
}
}
if (filter.starts_atRange) {
const [start, end] = filter.starts_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.lte]: end,
},
};
}
}
if (filter.ends_atRange) {
const [start, end] = filter.ends_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.program_status) {
where = {
...where,
program_status: filter.program_status,
};
}
if (filter.target_metric) {
where = {
...where,
target_metric: filter.target_metric,
};
}
if (filter.reward_type) {
where = {
...where,
reward_type: filter.reward_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.bonus_programs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'bonus_programs',
'program_name',
query,
),
],
};
}
const records = await db.bonus_programs.findAll({
attributes: [ 'id', 'program_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['program_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.program_name,
}));
}
};

View File

@ -0,0 +1,726 @@
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 Commission_plansDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const commission_plans = await db.commission_plans.create(
{
id: data.id || undefined,
plan_name: data.plan_name
||
null
,
plan_status: data.plan_status
||
null
,
calculation_base: data.calculation_base
||
null
,
commission_type: data.commission_type
||
null
,
default_rate: data.default_rate
||
null
,
default_amount: data.default_amount
||
null
,
include_shipping: data.include_shipping
||
false
,
include_tax: data.include_tax
||
false
,
effective_from: data.effective_from
||
null
,
effective_to: data.effective_to
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await commission_plans.setTenant( data.tenant || null, {
transaction,
});
await commission_plans.setOrganizations( data.organizations || null, {
transaction,
});
return commission_plans;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const commission_plansData = data.map((item, index) => ({
id: item.id || undefined,
plan_name: item.plan_name
||
null
,
plan_status: item.plan_status
||
null
,
calculation_base: item.calculation_base
||
null
,
commission_type: item.commission_type
||
null
,
default_rate: item.default_rate
||
null
,
default_amount: item.default_amount
||
null
,
include_shipping: item.include_shipping
||
false
,
include_tax: item.include_tax
||
false
,
effective_from: item.effective_from
||
null
,
effective_to: item.effective_to
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const commission_plans = await db.commission_plans.bulkCreate(commission_plansData, { transaction });
// For each item created, replace relation files
return commission_plans;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const commission_plans = await db.commission_plans.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.plan_name !== undefined) updatePayload.plan_name = data.plan_name;
if (data.plan_status !== undefined) updatePayload.plan_status = data.plan_status;
if (data.calculation_base !== undefined) updatePayload.calculation_base = data.calculation_base;
if (data.commission_type !== undefined) updatePayload.commission_type = data.commission_type;
if (data.default_rate !== undefined) updatePayload.default_rate = data.default_rate;
if (data.default_amount !== undefined) updatePayload.default_amount = data.default_amount;
if (data.include_shipping !== undefined) updatePayload.include_shipping = data.include_shipping;
if (data.include_tax !== undefined) updatePayload.include_tax = data.include_tax;
if (data.effective_from !== undefined) updatePayload.effective_from = data.effective_from;
if (data.effective_to !== undefined) updatePayload.effective_to = data.effective_to;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await commission_plans.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await commission_plans.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await commission_plans.setOrganizations(
data.organizations,
{ transaction }
);
}
return commission_plans;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const commission_plans = await db.commission_plans.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of commission_plans) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of commission_plans) {
await record.destroy({transaction});
}
});
return commission_plans;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const commission_plans = await db.commission_plans.findByPk(id, options);
await commission_plans.update({
deletedBy: currentUser.id
}, {
transaction,
});
await commission_plans.destroy({
transaction
});
return commission_plans;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const commission_plans = await db.commission_plans.findOne(
{ where },
{ transaction },
);
if (!commission_plans) {
return commission_plans;
}
const output = commission_plans.get({plain: true});
output.commission_rules_commission_plan = await commission_plans.getCommission_rules_commission_plan({
transaction
});
output.commissions_commission_plan = await commission_plans.getCommissions_commission_plan({
transaction
});
output.tenant = await commission_plans.getTenant({
transaction
});
output.organizations = await commission_plans.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
tenant_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.plan_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'commission_plans',
'plan_name',
filter.plan_name,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'commission_plans',
'notes',
filter.notes,
),
};
}
if (filter.default_rateRange) {
const [start, end] = filter.default_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
default_rate: {
...where.default_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
default_rate: {
...where.default_rate,
[Op.lte]: end,
},
};
}
}
if (filter.default_amountRange) {
const [start, end] = filter.default_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
default_amount: {
...where.default_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
default_amount: {
...where.default_amount,
[Op.lte]: end,
},
};
}
}
if (filter.effective_fromRange) {
const [start, end] = filter.effective_fromRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_from: {
...where.effective_from,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_from: {
...where.effective_from,
[Op.lte]: end,
},
};
}
}
if (filter.effective_toRange) {
const [start, end] = filter.effective_toRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_to: {
...where.effective_to,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_to: {
...where.effective_to,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.plan_status) {
where = {
...where,
plan_status: filter.plan_status,
};
}
if (filter.calculation_base) {
where = {
...where,
calculation_base: filter.calculation_base,
};
}
if (filter.commission_type) {
where = {
...where,
commission_type: filter.commission_type,
};
}
if (filter.include_shipping) {
where = {
...where,
include_shipping: filter.include_shipping,
};
}
if (filter.include_tax) {
where = {
...where,
include_tax: filter.include_tax,
};
}
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.commission_plans.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'commission_plans',
'plan_name',
query,
),
],
};
}
const records = await db.commission_plans.findAll({
attributes: [ 'id', 'plan_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['plan_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.plan_name,
}));
}
};

View File

@ -0,0 +1,652 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Commission_rulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const commission_rules = await db.commission_rules.create(
{
id: data.id || undefined,
applies_to_role: data.applies_to_role
||
null
,
commission_type: data.commission_type
||
null
,
rate: data.rate
||
null
,
amount: data.amount
||
null
,
min_order_amount: data.min_order_amount
||
null
,
is_active: data.is_active
||
false
,
rule_name: data.rule_name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await commission_rules.setCommission_plan( data.commission_plan || null, {
transaction,
});
await commission_rules.setProduct( data.product || null, {
transaction,
});
await commission_rules.setOrganizations( data.organizations || null, {
transaction,
});
return commission_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 commission_rulesData = data.map((item, index) => ({
id: item.id || undefined,
applies_to_role: item.applies_to_role
||
null
,
commission_type: item.commission_type
||
null
,
rate: item.rate
||
null
,
amount: item.amount
||
null
,
min_order_amount: item.min_order_amount
||
null
,
is_active: item.is_active
||
false
,
rule_name: item.rule_name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const commission_rules = await db.commission_rules.bulkCreate(commission_rulesData, { transaction });
// For each item created, replace relation files
return commission_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 commission_rules = await db.commission_rules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.applies_to_role !== undefined) updatePayload.applies_to_role = data.applies_to_role;
if (data.commission_type !== undefined) updatePayload.commission_type = data.commission_type;
if (data.rate !== undefined) updatePayload.rate = data.rate;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.min_order_amount !== undefined) updatePayload.min_order_amount = data.min_order_amount;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.rule_name !== undefined) updatePayload.rule_name = data.rule_name;
updatePayload.updatedById = currentUser.id;
await commission_rules.update(updatePayload, {transaction});
if (data.commission_plan !== undefined) {
await commission_rules.setCommission_plan(
data.commission_plan,
{ transaction }
);
}
if (data.product !== undefined) {
await commission_rules.setProduct(
data.product,
{ transaction }
);
}
if (data.organizations !== undefined) {
await commission_rules.setOrganizations(
data.organizations,
{ transaction }
);
}
return commission_rules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const commission_rules = await db.commission_rules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of commission_rules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of commission_rules) {
await record.destroy({transaction});
}
});
return commission_rules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const commission_rules = await db.commission_rules.findByPk(id, options);
await commission_rules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await commission_rules.destroy({
transaction
});
return commission_rules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const commission_rules = await db.commission_rules.findOne(
{ where },
{ transaction },
);
if (!commission_rules) {
return commission_rules;
}
const output = commission_rules.get({plain: true});
output.commission_plan = await commission_rules.getCommission_plan({
transaction
});
output.product = await commission_rules.getProduct({
transaction
});
output.organizations = await commission_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.commission_plans,
as: 'commission_plan',
where: filter.commission_plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.commission_plan.split('|').map(term => Utils.uuid(term)) } },
{
plan_name: {
[Op.or]: filter.commission_plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.rule_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'commission_rules',
'rule_name',
filter.rule_name,
),
};
}
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.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.min_order_amountRange) {
const [start, end] = filter.min_order_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_order_amount: {
...where.min_order_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_order_amount: {
...where.min_order_amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.applies_to_role) {
where = {
...where,
applies_to_role: filter.applies_to_role,
};
}
if (filter.commission_type) {
where = {
...where,
commission_type: filter.commission_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.commission_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(
'commission_rules',
'rule_name',
query,
),
],
};
}
const records = await db.commission_rules.findAll({
attributes: [ 'id', 'rule_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['rule_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.rule_name,
}));
}
};

View File

@ -0,0 +1,839 @@
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 CommissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const commissions = await db.commissions.create(
{
id: data.id || undefined,
commission_code: data.commission_code
||
null
,
commission_status: data.commission_status
||
null
,
commission_type: data.commission_type
||
null
,
base_amount: data.base_amount
||
null
,
commission_amount: data.commission_amount
||
null
,
earned_at: data.earned_at
||
null
,
approved_at: data.approved_at
||
null
,
paid_at: data.paid_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await commissions.setTenant( data.tenant || null, {
transaction,
});
await commissions.setOrder( data.order || null, {
transaction,
});
await commissions.setOrder_item( data.order_item || null, {
transaction,
});
await commissions.setBeneficiary_user( data.beneficiary_user || null, {
transaction,
});
await commissions.setCommission_plan( data.commission_plan || null, {
transaction,
});
await commissions.setOrganizations( data.organizations || null, {
transaction,
});
return commissions;
}
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 commissionsData = data.map((item, index) => ({
id: item.id || undefined,
commission_code: item.commission_code
||
null
,
commission_status: item.commission_status
||
null
,
commission_type: item.commission_type
||
null
,
base_amount: item.base_amount
||
null
,
commission_amount: item.commission_amount
||
null
,
earned_at: item.earned_at
||
null
,
approved_at: item.approved_at
||
null
,
paid_at: item.paid_at
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const commissions = await db.commissions.bulkCreate(commissionsData, { transaction });
// For each item created, replace relation files
return commissions;
}
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 commissions = await db.commissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.commission_code !== undefined) updatePayload.commission_code = data.commission_code;
if (data.commission_status !== undefined) updatePayload.commission_status = data.commission_status;
if (data.commission_type !== undefined) updatePayload.commission_type = data.commission_type;
if (data.base_amount !== undefined) updatePayload.base_amount = data.base_amount;
if (data.commission_amount !== undefined) updatePayload.commission_amount = data.commission_amount;
if (data.earned_at !== undefined) updatePayload.earned_at = data.earned_at;
if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await commissions.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await commissions.setTenant(
data.tenant,
{ transaction }
);
}
if (data.order !== undefined) {
await commissions.setOrder(
data.order,
{ transaction }
);
}
if (data.order_item !== undefined) {
await commissions.setOrder_item(
data.order_item,
{ transaction }
);
}
if (data.beneficiary_user !== undefined) {
await commissions.setBeneficiary_user(
data.beneficiary_user,
{ transaction }
);
}
if (data.commission_plan !== undefined) {
await commissions.setCommission_plan(
data.commission_plan,
{ transaction }
);
}
if (data.organizations !== undefined) {
await commissions.setOrganizations(
data.organizations,
{ transaction }
);
}
return commissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const commissions = await db.commissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of commissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of commissions) {
await record.destroy({transaction});
}
});
return commissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const commissions = await db.commissions.findByPk(id, options);
await commissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await commissions.destroy({
transaction
});
return commissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const commissions = await db.commissions.findOne(
{ where },
{ transaction },
);
if (!commissions) {
return commissions;
}
const output = commissions.get({plain: true});
output.tenant = await commissions.getTenant({
transaction
});
output.order = await commissions.getOrder({
transaction
});
output.order_item = await commissions.getOrder_item({
transaction
});
output.beneficiary_user = await commissions.getBeneficiary_user({
transaction
});
output.commission_plan = await commissions.getCommission_plan({
transaction
});
output.organizations = await commissions.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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.orders,
as: 'order',
where: filter.order ? {
[Op.or]: [
{ id: { [Op.in]: filter.order.split('|').map(term => Utils.uuid(term)) } },
{
order_number: {
[Op.or]: filter.order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.order_items,
as: 'order_item',
where: filter.order_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.order_item.split('|').map(term => Utils.uuid(term)) } },
{
item_name: {
[Op.or]: filter.order_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'beneficiary_user',
where: filter.beneficiary_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.beneficiary_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.beneficiary_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.commission_plans,
as: 'commission_plan',
where: filter.commission_plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.commission_plan.split('|').map(term => Utils.uuid(term)) } },
{
plan_name: {
[Op.or]: filter.commission_plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.commission_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'commissions',
'commission_code',
filter.commission_code,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'commissions',
'notes',
filter.notes,
),
};
}
if (filter.base_amountRange) {
const [start, end] = filter.base_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
base_amount: {
...where.base_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
base_amount: {
...where.base_amount,
[Op.lte]: end,
},
};
}
}
if (filter.commission_amountRange) {
const [start, end] = filter.commission_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commission_amount: {
...where.commission_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commission_amount: {
...where.commission_amount,
[Op.lte]: end,
},
};
}
}
if (filter.earned_atRange) {
const [start, end] = filter.earned_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
earned_at: {
...where.earned_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
earned_at: {
...where.earned_at,
[Op.lte]: end,
},
};
}
}
if (filter.approved_atRange) {
const [start, end] = filter.approved_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
approved_at: {
...where.approved_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
approved_at: {
...where.approved_at,
[Op.lte]: end,
},
};
}
}
if (filter.paid_atRange) {
const [start, end] = filter.paid_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.commission_status) {
where = {
...where,
commission_status: filter.commission_status,
};
}
if (filter.commission_type) {
where = {
...where,
commission_type: filter.commission_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.commissions.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(
'commissions',
'commission_code',
query,
),
],
};
}
const records = await db.commissions.findAll({
attributes: [ 'id', 'commission_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['commission_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.commission_code,
}));
}
};

View File

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

View File

@ -0,0 +1,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,664 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Inventory_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory_items = await db.inventory_items.create(
{
id: data.id || undefined,
on_hand_qty: data.on_hand_qty
||
null
,
reserved_qty: data.reserved_qty
||
null
,
available_qty: data.available_qty
||
null
,
last_counted_at: data.last_counted_at
||
null
,
note: data.note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inventory_items.setTenant( data.tenant || null, {
transaction,
});
await inventory_items.setProduct( data.product || null, {
transaction,
});
await inventory_items.setWarehouse( data.warehouse || null, {
transaction,
});
await inventory_items.setOrganizations( data.organizations || null, {
transaction,
});
return inventory_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 inventory_itemsData = data.map((item, index) => ({
id: item.id || undefined,
on_hand_qty: item.on_hand_qty
||
null
,
reserved_qty: item.reserved_qty
||
null
,
available_qty: item.available_qty
||
null
,
last_counted_at: item.last_counted_at
||
null
,
note: item.note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const inventory_items = await db.inventory_items.bulkCreate(inventory_itemsData, { transaction });
// For each item created, replace relation files
return inventory_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 inventory_items = await db.inventory_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.on_hand_qty !== undefined) updatePayload.on_hand_qty = data.on_hand_qty;
if (data.reserved_qty !== undefined) updatePayload.reserved_qty = data.reserved_qty;
if (data.available_qty !== undefined) updatePayload.available_qty = data.available_qty;
if (data.last_counted_at !== undefined) updatePayload.last_counted_at = data.last_counted_at;
if (data.note !== undefined) updatePayload.note = data.note;
updatePayload.updatedById = currentUser.id;
await inventory_items.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await inventory_items.setTenant(
data.tenant,
{ transaction }
);
}
if (data.product !== undefined) {
await inventory_items.setProduct(
data.product,
{ transaction }
);
}
if (data.warehouse !== undefined) {
await inventory_items.setWarehouse(
data.warehouse,
{ transaction }
);
}
if (data.organizations !== undefined) {
await inventory_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return inventory_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory_items = await db.inventory_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inventory_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inventory_items) {
await record.destroy({transaction});
}
});
return inventory_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inventory_items = await db.inventory_items.findByPk(id, options);
await inventory_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inventory_items.destroy({
transaction
});
return inventory_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inventory_items = await db.inventory_items.findOne(
{ where },
{ transaction },
);
if (!inventory_items) {
return inventory_items;
}
const output = inventory_items.get({plain: true});
output.tenant = await inventory_items.getTenant({
transaction
});
output.product = await inventory_items.getProduct({
transaction
});
output.warehouse = await inventory_items.getWarehouse({
transaction
});
output.organizations = await inventory_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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.warehouses,
as: 'warehouse',
where: filter.warehouse ? {
[Op.or]: [
{ id: { [Op.in]: filter.warehouse.split('|').map(term => Utils.uuid(term)) } },
{
warehouse_name: {
[Op.or]: filter.warehouse.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_items',
'note',
filter.note,
),
};
}
if (filter.on_hand_qtyRange) {
const [start, end] = filter.on_hand_qtyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
on_hand_qty: {
...where.on_hand_qty,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
on_hand_qty: {
...where.on_hand_qty,
[Op.lte]: end,
},
};
}
}
if (filter.reserved_qtyRange) {
const [start, end] = filter.reserved_qtyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reserved_qty: {
...where.reserved_qty,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reserved_qty: {
...where.reserved_qty,
[Op.lte]: end,
},
};
}
}
if (filter.available_qtyRange) {
const [start, end] = filter.available_qtyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
available_qty: {
...where.available_qty,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
available_qty: {
...where.available_qty,
[Op.lte]: end,
},
};
}
}
if (filter.last_counted_atRange) {
const [start, end] = filter.last_counted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_counted_at: {
...where.last_counted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_counted_at: {
...where.last_counted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.inventory_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(
'inventory_items',
'note',
query,
),
],
};
}
const records = await db.inventory_items.findAll({
attributes: [ 'id', 'note' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['note', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.note,
}));
}
};

View File

@ -0,0 +1,732 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Inventory_movementsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory_movements = await db.inventory_movements.create(
{
id: data.id || undefined,
movement_type: data.movement_type
||
null
,
quantity: data.quantity
||
null
,
unit_cost: data.unit_cost
||
null
,
reference_type: data.reference_type
||
null
,
reference_number: data.reference_number
||
null
,
moved_at: data.moved_at
||
null
,
note: data.note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inventory_movements.setTenant( data.tenant || null, {
transaction,
});
await inventory_movements.setWarehouse( data.warehouse || null, {
transaction,
});
await inventory_movements.setProduct( data.product || null, {
transaction,
});
await inventory_movements.setPerformed_by( data.performed_by || null, {
transaction,
});
await inventory_movements.setOrganizations( data.organizations || null, {
transaction,
});
return inventory_movements;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const inventory_movementsData = data.map((item, index) => ({
id: item.id || undefined,
movement_type: item.movement_type
||
null
,
quantity: item.quantity
||
null
,
unit_cost: item.unit_cost
||
null
,
reference_type: item.reference_type
||
null
,
reference_number: item.reference_number
||
null
,
moved_at: item.moved_at
||
null
,
note: item.note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const inventory_movements = await db.inventory_movements.bulkCreate(inventory_movementsData, { transaction });
// For each item created, replace relation files
return inventory_movements;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const inventory_movements = await db.inventory_movements.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.movement_type !== undefined) updatePayload.movement_type = data.movement_type;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.unit_cost !== undefined) updatePayload.unit_cost = data.unit_cost;
if (data.reference_type !== undefined) updatePayload.reference_type = data.reference_type;
if (data.reference_number !== undefined) updatePayload.reference_number = data.reference_number;
if (data.moved_at !== undefined) updatePayload.moved_at = data.moved_at;
if (data.note !== undefined) updatePayload.note = data.note;
updatePayload.updatedById = currentUser.id;
await inventory_movements.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await inventory_movements.setTenant(
data.tenant,
{ transaction }
);
}
if (data.warehouse !== undefined) {
await inventory_movements.setWarehouse(
data.warehouse,
{ transaction }
);
}
if (data.product !== undefined) {
await inventory_movements.setProduct(
data.product,
{ transaction }
);
}
if (data.performed_by !== undefined) {
await inventory_movements.setPerformed_by(
data.performed_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await inventory_movements.setOrganizations(
data.organizations,
{ transaction }
);
}
return inventory_movements;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory_movements = await db.inventory_movements.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inventory_movements) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inventory_movements) {
await record.destroy({transaction});
}
});
return inventory_movements;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inventory_movements = await db.inventory_movements.findByPk(id, options);
await inventory_movements.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inventory_movements.destroy({
transaction
});
return inventory_movements;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inventory_movements = await db.inventory_movements.findOne(
{ where },
{ transaction },
);
if (!inventory_movements) {
return inventory_movements;
}
const output = inventory_movements.get({plain: true});
output.tenant = await inventory_movements.getTenant({
transaction
});
output.warehouse = await inventory_movements.getWarehouse({
transaction
});
output.product = await inventory_movements.getProduct({
transaction
});
output.performed_by = await inventory_movements.getPerformed_by({
transaction
});
output.organizations = await inventory_movements.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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.warehouses,
as: 'warehouse',
where: filter.warehouse ? {
[Op.or]: [
{ id: { [Op.in]: filter.warehouse.split('|').map(term => Utils.uuid(term)) } },
{
warehouse_name: {
[Op.or]: filter.warehouse.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'performed_by',
where: filter.performed_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.performed_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.performed_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reference_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_movements',
'reference_type',
filter.reference_type,
),
};
}
if (filter.reference_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_movements',
'reference_number',
filter.reference_number,
),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory_movements',
'note',
filter.note,
),
};
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.unit_costRange) {
const [start, end] = filter.unit_costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unit_cost: {
...where.unit_cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unit_cost: {
...where.unit_cost,
[Op.lte]: end,
},
};
}
}
if (filter.moved_atRange) {
const [start, end] = filter.moved_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
moved_at: {
...where.moved_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
moved_at: {
...where.moved_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.movement_type) {
where = {
...where,
movement_type: filter.movement_type,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.inventory_movements.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'inventory_movements',
'reference_number',
query,
),
],
};
}
const records = await db.inventory_movements.findAll({
attributes: [ 'id', 'reference_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reference_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reference_number,
}));
}
};

View File

@ -0,0 +1,759 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class InvoicesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.create(
{
id: data.id || undefined,
invoice_number: data.invoice_number
||
null
,
invoice_status: data.invoice_status
||
null
,
issued_at: data.issued_at
||
null
,
due_at: data.due_at
||
null
,
amount_due: data.amount_due
||
null
,
amount_paid: data.amount_paid
||
null
,
billing_name: data.billing_name
||
null
,
billing_address: data.billing_address
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await invoices.setTenant( data.tenant || null, {
transaction,
});
await invoices.setOrder( data.order || null, {
transaction,
});
await invoices.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.invoices.getTableName(),
belongsToColumn: 'invoice_files',
belongsToId: invoices.id,
},
data.invoice_files,
options,
);
return invoices;
}
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 invoicesData = data.map((item, index) => ({
id: item.id || undefined,
invoice_number: item.invoice_number
||
null
,
invoice_status: item.invoice_status
||
null
,
issued_at: item.issued_at
||
null
,
due_at: item.due_at
||
null
,
amount_due: item.amount_due
||
null
,
amount_paid: item.amount_paid
||
null
,
billing_name: item.billing_name
||
null
,
billing_address: item.billing_address
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const invoices = await db.invoices.bulkCreate(invoicesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < invoices.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.invoices.getTableName(),
belongsToColumn: 'invoice_files',
belongsToId: invoices[i].id,
},
data[i].invoice_files,
options,
);
}
return invoices;
}
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 invoices = await db.invoices.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.invoice_number !== undefined) updatePayload.invoice_number = data.invoice_number;
if (data.invoice_status !== undefined) updatePayload.invoice_status = data.invoice_status;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.amount_due !== undefined) updatePayload.amount_due = data.amount_due;
if (data.amount_paid !== undefined) updatePayload.amount_paid = data.amount_paid;
if (data.billing_name !== undefined) updatePayload.billing_name = data.billing_name;
if (data.billing_address !== undefined) updatePayload.billing_address = data.billing_address;
updatePayload.updatedById = currentUser.id;
await invoices.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await invoices.setTenant(
data.tenant,
{ transaction }
);
}
if (data.order !== undefined) {
await invoices.setOrder(
data.order,
{ transaction }
);
}
if (data.organizations !== undefined) {
await invoices.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.invoices.getTableName(),
belongsToColumn: 'invoice_files',
belongsToId: invoices.id,
},
data.invoice_files,
options,
);
return invoices;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of invoices) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of invoices) {
await record.destroy({transaction});
}
});
return invoices;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.findByPk(id, options);
await invoices.update({
deletedBy: currentUser.id
}, {
transaction,
});
await invoices.destroy({
transaction
});
return invoices;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.findOne(
{ where },
{ transaction },
);
if (!invoices) {
return invoices;
}
const output = invoices.get({plain: true});
output.payments_invoice = await invoices.getPayments_invoice({
transaction
});
output.tenant = await invoices.getTenant({
transaction
});
output.order = await invoices.getOrder({
transaction
});
output.invoice_files = await invoices.getInvoice_files({
transaction
});
output.organizations = await invoices.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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.orders,
as: 'order',
where: filter.order ? {
[Op.or]: [
{ id: { [Op.in]: filter.order.split('|').map(term => Utils.uuid(term)) } },
{
order_number: {
[Op.or]: filter.order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'invoice_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.invoice_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoices',
'invoice_number',
filter.invoice_number,
),
};
}
if (filter.billing_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoices',
'billing_name',
filter.billing_name,
),
};
}
if (filter.billing_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoices',
'billing_address',
filter.billing_address,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
issued_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
due_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.lte]: end,
},
};
}
}
if (filter.due_atRange) {
const [start, end] = filter.due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.lte]: end,
},
};
}
}
if (filter.amount_dueRange) {
const [start, end] = filter.amount_dueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount_due: {
...where.amount_due,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount_due: {
...where.amount_due,
[Op.lte]: end,
},
};
}
}
if (filter.amount_paidRange) {
const [start, end] = filter.amount_paidRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount_paid: {
...where.amount_paid,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount_paid: {
...where.amount_paid,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.invoice_status) {
where = {
...where,
invoice_status: filter.invoice_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.invoices.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(
'invoices',
'invoice_number',
query,
),
],
};
}
const records = await db.invoices.findAll({
attributes: [ 'id', 'invoice_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['invoice_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.invoice_number,
}));
}
};

View File

@ -0,0 +1,663 @@
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,
notification_type: data.notification_type
||
null
,
channel: data.channel
||
null
,
title_text: data.title_text
||
null
,
message_text: data.message_text
||
null
,
action_url: data.action_url
||
null
,
is_read: data.is_read
||
false
,
sent_at: data.sent_at
||
null
,
read_at: data.read_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notifications.setTenant( data.tenant || null, {
transaction,
});
await notifications.setRecipient_user( data.recipient_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,
notification_type: item.notification_type
||
null
,
channel: item.channel
||
null
,
title_text: item.title_text
||
null
,
message_text: item.message_text
||
null
,
action_url: item.action_url
||
null
,
is_read: item.is_read
||
false
,
sent_at: item.sent_at
||
null
,
read_at: item.read_at
||
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.notification_type !== undefined) updatePayload.notification_type = data.notification_type;
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
if (data.message_text !== undefined) updatePayload.message_text = data.message_text;
if (data.action_url !== undefined) updatePayload.action_url = data.action_url;
if (data.is_read !== undefined) updatePayload.is_read = data.is_read;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.read_at !== undefined) updatePayload.read_at = data.read_at;
updatePayload.updatedById = currentUser.id;
await notifications.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await notifications.setTenant(
data.tenant,
{ transaction }
);
}
if (data.recipient_user !== undefined) {
await notifications.setRecipient_user(
data.recipient_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.recipient_user = await notifications.getRecipient_user({
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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'recipient_user',
where: filter.recipient_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.recipient_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recipient_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.title_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'title_text',
filter.title_text,
),
};
}
if (filter.message_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'message_text',
filter.message_text,
),
};
}
if (filter.action_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'action_url',
filter.action_url,
),
};
}
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.notification_type) {
where = {
...where,
notification_type: filter.notification_type,
};
}
if (filter.channel) {
where = {
...where,
channel: filter.channel,
};
}
if (filter.is_read) {
where = {
...where,
is_read: filter.is_read,
};
}
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',
'title_text',
query,
),
],
};
}
const records = await db.notifications.findAll({
attributes: [ 'id', 'title_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title_text,
}));
}
};

View File

@ -0,0 +1,655 @@
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 Order_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const order_items = await db.order_items.create(
{
id: data.id || undefined,
item_name: data.item_name
||
null
,
sku: data.sku
||
null
,
unit_price: data.unit_price
||
null
,
quantity: data.quantity
||
null
,
discount_amount: data.discount_amount
||
null
,
line_total_amount: data.line_total_amount
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await order_items.setOrder( data.order || null, {
transaction,
});
await order_items.setProduct( data.product || null, {
transaction,
});
await order_items.setOrganizations( data.organizations || null, {
transaction,
});
return order_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 order_itemsData = data.map((item, index) => ({
id: item.id || undefined,
item_name: item.item_name
||
null
,
sku: item.sku
||
null
,
unit_price: item.unit_price
||
null
,
quantity: item.quantity
||
null
,
discount_amount: item.discount_amount
||
null
,
line_total_amount: item.line_total_amount
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const order_items = await db.order_items.bulkCreate(order_itemsData, { transaction });
// For each item created, replace relation files
return order_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 order_items = await db.order_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.item_name !== undefined) updatePayload.item_name = data.item_name;
if (data.sku !== undefined) updatePayload.sku = data.sku;
if (data.unit_price !== undefined) updatePayload.unit_price = data.unit_price;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.discount_amount !== undefined) updatePayload.discount_amount = data.discount_amount;
if (data.line_total_amount !== undefined) updatePayload.line_total_amount = data.line_total_amount;
updatePayload.updatedById = currentUser.id;
await order_items.update(updatePayload, {transaction});
if (data.order !== undefined) {
await order_items.setOrder(
data.order,
{ transaction }
);
}
if (data.product !== undefined) {
await order_items.setProduct(
data.product,
{ transaction }
);
}
if (data.organizations !== undefined) {
await order_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return order_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const order_items = await db.order_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of order_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of order_items) {
await record.destroy({transaction});
}
});
return order_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const order_items = await db.order_items.findByPk(id, options);
await order_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await order_items.destroy({
transaction
});
return order_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const order_items = await db.order_items.findOne(
{ where },
{ transaction },
);
if (!order_items) {
return order_items;
}
const output = order_items.get({plain: true});
output.commissions_order_item = await order_items.getCommissions_order_item({
transaction
});
output.order = await order_items.getOrder({
transaction
});
output.product = await order_items.getProduct({
transaction
});
output.organizations = await order_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.orders,
as: 'order',
where: filter.order ? {
[Op.or]: [
{ id: { [Op.in]: filter.order.split('|').map(term => Utils.uuid(term)) } },
{
order_number: {
[Op.or]: filter.order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.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(
'order_items',
'item_name',
filter.item_name,
),
};
}
if (filter.sku) {
where = {
...where,
[Op.and]: Utils.ilike(
'order_items',
'sku',
filter.sku,
),
};
}
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.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.discount_amountRange) {
const [start, end] = filter.discount_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
discount_amount: {
...where.discount_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
discount_amount: {
...where.discount_amount,
[Op.lte]: end,
},
};
}
}
if (filter.line_total_amountRange) {
const [start, end] = filter.line_total_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
line_total_amount: {
...where.line_total_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
line_total_amount: {
...where.line_total_amount,
[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.order_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(
'order_items',
'item_name',
query,
),
],
};
}
const records = await db.order_items.findAll({
attributes: [ 'id', 'item_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['item_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.item_name,
}));
}
};

1126
backend/src/db/api/orders.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,456 @@
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.products_organizations = await organizations.getProducts_organizations({
transaction
});
output.warehouses_organizations = await organizations.getWarehouses_organizations({
transaction
});
output.inventory_items_organizations = await organizations.getInventory_items_organizations({
transaction
});
output.inventory_movements_organizations = await organizations.getInventory_movements_organizations({
transaction
});
output.customers_organizations = await organizations.getCustomers_organizations({
transaction
});
output.orders_organizations = await organizations.getOrders_organizations({
transaction
});
output.order_items_organizations = await organizations.getOrder_items_organizations({
transaction
});
output.invoices_organizations = await organizations.getInvoices_organizations({
transaction
});
output.payments_organizations = await organizations.getPayments_organizations({
transaction
});
output.commission_plans_organizations = await organizations.getCommission_plans_organizations({
transaction
});
output.commission_rules_organizations = await organizations.getCommission_rules_organizations({
transaction
});
output.commissions_organizations = await organizations.getCommissions_organizations({
transaction
});
output.payouts_organizations = await organizations.getPayouts_organizations({
transaction
});
output.bonus_programs_organizations = await organizations.getBonus_programs_organizations({
transaction
});
output.referral_links_organizations = await organizations.getReferral_links_organizations({
transaction
});
output.reseller_stores_organizations = await organizations.getReseller_stores_organizations({
transaction
});
output.store_pages_organizations = await organizations.getStore_pages_organizations({
transaction
});
output.notifications_organizations = await organizations.getNotifications_organizations({
transaction
});
output.ai_insights_organizations = await organizations.getAi_insights_organizations({
transaction
});
output.sales_targets_organizations = await organizations.getSales_targets_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,720 @@
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 PaymentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.create(
{
id: data.id || undefined,
payment_reference: data.payment_reference
||
null
,
payment_method: data.payment_method
||
null
,
payment_status: data.payment_status
||
null
,
amount: data.amount
||
null
,
paid_at: data.paid_at
||
null
,
payer_name: data.payer_name
||
null
,
note: data.note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payments.setTenant( data.tenant || null, {
transaction,
});
await payments.setOrder( data.order || null, {
transaction,
});
await payments.setInvoice( data.invoice || null, {
transaction,
});
await payments.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'proof_files',
belongsToId: payments.id,
},
data.proof_files,
options,
);
return payments;
}
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 paymentsData = data.map((item, index) => ({
id: item.id || undefined,
payment_reference: item.payment_reference
||
null
,
payment_method: item.payment_method
||
null
,
payment_status: item.payment_status
||
null
,
amount: item.amount
||
null
,
paid_at: item.paid_at
||
null
,
payer_name: item.payer_name
||
null
,
note: item.note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payments = await db.payments.bulkCreate(paymentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < payments.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'proof_files',
belongsToId: payments[i].id,
},
data[i].proof_files,
options,
);
}
return payments;
}
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 payments = await db.payments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.payment_reference !== undefined) updatePayload.payment_reference = data.payment_reference;
if (data.payment_method !== undefined) updatePayload.payment_method = data.payment_method;
if (data.payment_status !== undefined) updatePayload.payment_status = data.payment_status;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.payer_name !== undefined) updatePayload.payer_name = data.payer_name;
if (data.note !== undefined) updatePayload.note = data.note;
updatePayload.updatedById = currentUser.id;
await payments.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await payments.setTenant(
data.tenant,
{ transaction }
);
}
if (data.order !== undefined) {
await payments.setOrder(
data.order,
{ transaction }
);
}
if (data.invoice !== undefined) {
await payments.setInvoice(
data.invoice,
{ transaction }
);
}
if (data.organizations !== undefined) {
await payments.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'proof_files',
belongsToId: payments.id,
},
data.proof_files,
options,
);
return payments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payments) {
await record.destroy({transaction});
}
});
return payments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findByPk(id, options);
await payments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payments.destroy({
transaction
});
return payments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findOne(
{ where },
{ transaction },
);
if (!payments) {
return payments;
}
const output = payments.get({plain: true});
output.tenant = await payments.getTenant({
transaction
});
output.order = await payments.getOrder({
transaction
});
output.invoice = await payments.getInvoice({
transaction
});
output.proof_files = await payments.getProof_files({
transaction
});
output.organizations = await payments.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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.orders,
as: 'order',
where: filter.order ? {
[Op.or]: [
{ id: { [Op.in]: filter.order.split('|').map(term => Utils.uuid(term)) } },
{
order_number: {
[Op.or]: filter.order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.invoices,
as: 'invoice',
where: filter.invoice ? {
[Op.or]: [
{ id: { [Op.in]: filter.invoice.split('|').map(term => Utils.uuid(term)) } },
{
invoice_number: {
[Op.or]: filter.invoice.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'proof_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.payment_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'payment_reference',
filter.payment_reference,
),
};
}
if (filter.payer_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'payer_name',
filter.payer_name,
),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'note',
filter.note,
),
};
}
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.paid_atRange) {
const [start, end] = filter.paid_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.payment_method) {
where = {
...where,
payment_method: filter.payment_method,
};
}
if (filter.payment_status) {
where = {
...where,
payment_status: filter.payment_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.payments.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(
'payments',
'payment_reference',
query,
),
],
};
}
const records = await db.payments.findAll({
attributes: [ 'id', 'payment_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['payment_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.payment_reference,
}));
}
};

View File

@ -0,0 +1,807 @@
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 PayoutsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payouts = await db.payouts.create(
{
id: data.id || undefined,
payout_reference: data.payout_reference
||
null
,
payout_method: data.payout_method
||
null
,
payout_status: data.payout_status
||
null
,
gross_amount: data.gross_amount
||
null
,
fee_amount: data.fee_amount
||
null
,
net_amount: data.net_amount
||
null
,
scheduled_at: data.scheduled_at
||
null
,
processed_at: data.processed_at
||
null
,
paid_at: data.paid_at
||
null
,
note: data.note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payouts.setTenant( data.tenant || null, {
transaction,
});
await payouts.setRecipient_user( data.recipient_user || null, {
transaction,
});
await payouts.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payouts.getTableName(),
belongsToColumn: 'payout_proof_files',
belongsToId: payouts.id,
},
data.payout_proof_files,
options,
);
return payouts;
}
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 payoutsData = data.map((item, index) => ({
id: item.id || undefined,
payout_reference: item.payout_reference
||
null
,
payout_method: item.payout_method
||
null
,
payout_status: item.payout_status
||
null
,
gross_amount: item.gross_amount
||
null
,
fee_amount: item.fee_amount
||
null
,
net_amount: item.net_amount
||
null
,
scheduled_at: item.scheduled_at
||
null
,
processed_at: item.processed_at
||
null
,
paid_at: item.paid_at
||
null
,
note: item.note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payouts = await db.payouts.bulkCreate(payoutsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < payouts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payouts.getTableName(),
belongsToColumn: 'payout_proof_files',
belongsToId: payouts[i].id,
},
data[i].payout_proof_files,
options,
);
}
return payouts;
}
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 payouts = await db.payouts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.payout_reference !== undefined) updatePayload.payout_reference = data.payout_reference;
if (data.payout_method !== undefined) updatePayload.payout_method = data.payout_method;
if (data.payout_status !== undefined) updatePayload.payout_status = data.payout_status;
if (data.gross_amount !== undefined) updatePayload.gross_amount = data.gross_amount;
if (data.fee_amount !== undefined) updatePayload.fee_amount = data.fee_amount;
if (data.net_amount !== undefined) updatePayload.net_amount = data.net_amount;
if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
if (data.processed_at !== undefined) updatePayload.processed_at = data.processed_at;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.note !== undefined) updatePayload.note = data.note;
updatePayload.updatedById = currentUser.id;
await payouts.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await payouts.setTenant(
data.tenant,
{ transaction }
);
}
if (data.recipient_user !== undefined) {
await payouts.setRecipient_user(
data.recipient_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await payouts.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payouts.getTableName(),
belongsToColumn: 'payout_proof_files',
belongsToId: payouts.id,
},
data.payout_proof_files,
options,
);
return payouts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payouts = await db.payouts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payouts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payouts) {
await record.destroy({transaction});
}
});
return payouts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payouts = await db.payouts.findByPk(id, options);
await payouts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payouts.destroy({
transaction
});
return payouts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payouts = await db.payouts.findOne(
{ where },
{ transaction },
);
if (!payouts) {
return payouts;
}
const output = payouts.get({plain: true});
output.tenant = await payouts.getTenant({
transaction
});
output.recipient_user = await payouts.getRecipient_user({
transaction
});
output.payout_proof_files = await payouts.getPayout_proof_files({
transaction
});
output.organizations = await payouts.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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'recipient_user',
where: filter.recipient_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.recipient_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recipient_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'payout_proof_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.payout_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'payouts',
'payout_reference',
filter.payout_reference,
),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'payouts',
'note',
filter.note,
),
};
}
if (filter.gross_amountRange) {
const [start, end] = filter.gross_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
gross_amount: {
...where.gross_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
gross_amount: {
...where.gross_amount,
[Op.lte]: end,
},
};
}
}
if (filter.fee_amountRange) {
const [start, end] = filter.fee_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
fee_amount: {
...where.fee_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
fee_amount: {
...where.fee_amount,
[Op.lte]: end,
},
};
}
}
if (filter.net_amountRange) {
const [start, end] = filter.net_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
net_amount: {
...where.net_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
net_amount: {
...where.net_amount,
[Op.lte]: end,
},
};
}
}
if (filter.scheduled_atRange) {
const [start, end] = filter.scheduled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.lte]: end,
},
};
}
}
if (filter.processed_atRange) {
const [start, end] = filter.processed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
processed_at: {
...where.processed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
processed_at: {
...where.processed_at,
[Op.lte]: end,
},
};
}
}
if (filter.paid_atRange) {
const [start, end] = filter.paid_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.payout_method) {
where = {
...where,
payout_method: filter.payout_method,
};
}
if (filter.payout_status) {
where = {
...where,
payout_status: filter.payout_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.payouts.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(
'payouts',
'payout_reference',
query,
),
],
};
}
const records = await db.payouts.findAll({
attributes: [ 'id', 'payout_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['payout_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.payout_reference,
}));
}
};

View File

@ -0,0 +1,354 @@
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,
}));
}
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,754 @@
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 Referral_linksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral_links = await db.referral_links.create(
{
id: data.id || undefined,
link_name: data.link_name
||
null
,
code: data.code
||
null
,
destination_url: data.destination_url
||
null
,
link_type: data.link_type
||
null
,
is_active: data.is_active
||
false
,
starts_at: data.starts_at
||
null
,
ends_at: data.ends_at
||
null
,
click_count: data.click_count
||
null
,
conversion_count: data.conversion_count
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await referral_links.setTenant( data.tenant || null, {
transaction,
});
await referral_links.setOwner_user( data.owner_user || null, {
transaction,
});
await referral_links.setProduct( data.product || null, {
transaction,
});
await referral_links.setOrganizations( data.organizations || null, {
transaction,
});
return referral_links;
}
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 referral_linksData = data.map((item, index) => ({
id: item.id || undefined,
link_name: item.link_name
||
null
,
code: item.code
||
null
,
destination_url: item.destination_url
||
null
,
link_type: item.link_type
||
null
,
is_active: item.is_active
||
false
,
starts_at: item.starts_at
||
null
,
ends_at: item.ends_at
||
null
,
click_count: item.click_count
||
null
,
conversion_count: item.conversion_count
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const referral_links = await db.referral_links.bulkCreate(referral_linksData, { transaction });
// For each item created, replace relation files
return referral_links;
}
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 referral_links = await db.referral_links.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.link_name !== undefined) updatePayload.link_name = data.link_name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.destination_url !== undefined) updatePayload.destination_url = data.destination_url;
if (data.link_type !== undefined) updatePayload.link_type = data.link_type;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
if (data.click_count !== undefined) updatePayload.click_count = data.click_count;
if (data.conversion_count !== undefined) updatePayload.conversion_count = data.conversion_count;
updatePayload.updatedById = currentUser.id;
await referral_links.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await referral_links.setTenant(
data.tenant,
{ transaction }
);
}
if (data.owner_user !== undefined) {
await referral_links.setOwner_user(
data.owner_user,
{ transaction }
);
}
if (data.product !== undefined) {
await referral_links.setProduct(
data.product,
{ transaction }
);
}
if (data.organizations !== undefined) {
await referral_links.setOrganizations(
data.organizations,
{ transaction }
);
}
return referral_links;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral_links = await db.referral_links.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of referral_links) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of referral_links) {
await record.destroy({transaction});
}
});
return referral_links;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const referral_links = await db.referral_links.findByPk(id, options);
await referral_links.update({
deletedBy: currentUser.id
}, {
transaction,
});
await referral_links.destroy({
transaction
});
return referral_links;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const referral_links = await db.referral_links.findOne(
{ where },
{ transaction },
);
if (!referral_links) {
return referral_links;
}
const output = referral_links.get({plain: true});
output.tenant = await referral_links.getTenant({
transaction
});
output.owner_user = await referral_links.getOwner_user({
transaction
});
output.product = await referral_links.getProduct({
transaction
});
output.organizations = await referral_links.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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner_user',
where: filter.owner_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
product_name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.link_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'referral_links',
'link_name',
filter.link_name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'referral_links',
'code',
filter.code,
),
};
}
if (filter.destination_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'referral_links',
'destination_url',
filter.destination_url,
),
};
}
if (filter.starts_atRange) {
const [start, end] = filter.starts_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.lte]: end,
},
};
}
}
if (filter.ends_atRange) {
const [start, end] = filter.ends_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.lte]: end,
},
};
}
}
if (filter.click_countRange) {
const [start, end] = filter.click_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
click_count: {
...where.click_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
click_count: {
...where.click_count,
[Op.lte]: end,
},
};
}
}
if (filter.conversion_countRange) {
const [start, end] = filter.conversion_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
conversion_count: {
...where.conversion_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
conversion_count: {
...where.conversion_count,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.link_type) {
where = {
...where,
link_type: filter.link_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.referral_links.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(
'referral_links',
'link_name',
query,
),
],
};
}
const records = await db.referral_links.findAll({
attributes: [ 'id', 'link_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['link_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.link_name,
}));
}
};

View File

@ -0,0 +1,713 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Reseller_storesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reseller_stores = await db.reseller_stores.create(
{
id: data.id || undefined,
store_name: data.store_name
||
null
,
slug: data.slug
||
null
,
store_status: data.store_status
||
null
,
tagline: data.tagline
||
null
,
about: data.about
||
null
,
whatsapp_number: data.whatsapp_number
||
null
,
instagram_handle: data.instagram_handle
||
null
,
tiktok_handle: data.tiktok_handle
||
null
,
custom_domain: data.custom_domain
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await reseller_stores.setTenant( data.tenant || null, {
transaction,
});
await reseller_stores.setOwner_user( data.owner_user || null, {
transaction,
});
await reseller_stores.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.reseller_stores.getTableName(),
belongsToColumn: 'banner_images',
belongsToId: reseller_stores.id,
},
data.banner_images,
options,
);
return reseller_stores;
}
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 reseller_storesData = data.map((item, index) => ({
id: item.id || undefined,
store_name: item.store_name
||
null
,
slug: item.slug
||
null
,
store_status: item.store_status
||
null
,
tagline: item.tagline
||
null
,
about: item.about
||
null
,
whatsapp_number: item.whatsapp_number
||
null
,
instagram_handle: item.instagram_handle
||
null
,
tiktok_handle: item.tiktok_handle
||
null
,
custom_domain: item.custom_domain
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const reseller_stores = await db.reseller_stores.bulkCreate(reseller_storesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < reseller_stores.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.reseller_stores.getTableName(),
belongsToColumn: 'banner_images',
belongsToId: reseller_stores[i].id,
},
data[i].banner_images,
options,
);
}
return reseller_stores;
}
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 reseller_stores = await db.reseller_stores.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.store_name !== undefined) updatePayload.store_name = data.store_name;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.store_status !== undefined) updatePayload.store_status = data.store_status;
if (data.tagline !== undefined) updatePayload.tagline = data.tagline;
if (data.about !== undefined) updatePayload.about = data.about;
if (data.whatsapp_number !== undefined) updatePayload.whatsapp_number = data.whatsapp_number;
if (data.instagram_handle !== undefined) updatePayload.instagram_handle = data.instagram_handle;
if (data.tiktok_handle !== undefined) updatePayload.tiktok_handle = data.tiktok_handle;
if (data.custom_domain !== undefined) updatePayload.custom_domain = data.custom_domain;
updatePayload.updatedById = currentUser.id;
await reseller_stores.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await reseller_stores.setTenant(
data.tenant,
{ transaction }
);
}
if (data.owner_user !== undefined) {
await reseller_stores.setOwner_user(
data.owner_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await reseller_stores.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.reseller_stores.getTableName(),
belongsToColumn: 'banner_images',
belongsToId: reseller_stores.id,
},
data.banner_images,
options,
);
return reseller_stores;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reseller_stores = await db.reseller_stores.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of reseller_stores) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of reseller_stores) {
await record.destroy({transaction});
}
});
return reseller_stores;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reseller_stores = await db.reseller_stores.findByPk(id, options);
await reseller_stores.update({
deletedBy: currentUser.id
}, {
transaction,
});
await reseller_stores.destroy({
transaction
});
return reseller_stores;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const reseller_stores = await db.reseller_stores.findOne(
{ where },
{ transaction },
);
if (!reseller_stores) {
return reseller_stores;
}
const output = reseller_stores.get({plain: true});
output.store_pages_reseller_store = await reseller_stores.getStore_pages_reseller_store({
transaction
});
output.tenant = await reseller_stores.getTenant({
transaction
});
output.owner_user = await reseller_stores.getOwner_user({
transaction
});
output.banner_images = await reseller_stores.getBanner_images({
transaction
});
output.organizations = await reseller_stores.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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner_user',
where: filter.owner_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'banner_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.store_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'reseller_stores',
'store_name',
filter.store_name,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'reseller_stores',
'slug',
filter.slug,
),
};
}
if (filter.tagline) {
where = {
...where,
[Op.and]: Utils.ilike(
'reseller_stores',
'tagline',
filter.tagline,
),
};
}
if (filter.about) {
where = {
...where,
[Op.and]: Utils.ilike(
'reseller_stores',
'about',
filter.about,
),
};
}
if (filter.whatsapp_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'reseller_stores',
'whatsapp_number',
filter.whatsapp_number,
),
};
}
if (filter.instagram_handle) {
where = {
...where,
[Op.and]: Utils.ilike(
'reseller_stores',
'instagram_handle',
filter.instagram_handle,
),
};
}
if (filter.tiktok_handle) {
where = {
...where,
[Op.and]: Utils.ilike(
'reseller_stores',
'tiktok_handle',
filter.tiktok_handle,
),
};
}
if (filter.custom_domain) {
where = {
...where,
[Op.and]: Utils.ilike(
'reseller_stores',
'custom_domain',
filter.custom_domain,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.store_status) {
where = {
...where,
store_status: filter.store_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.reseller_stores.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(
'reseller_stores',
'store_name',
query,
),
],
};
}
const records = await db.reseller_stores.findAll({
attributes: [ 'id', 'store_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['store_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.store_name,
}));
}
};

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

@ -0,0 +1,456 @@
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,729 @@
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 Sales_targetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sales_targets = await db.sales_targets.create(
{
id: data.id || undefined,
target_name: data.target_name
||
null
,
target_scope: data.target_scope
||
null
,
metric: data.metric
||
null
,
target_value: data.target_value
||
null
,
achieved_value: data.achieved_value
||
null
,
period_start: data.period_start
||
null
,
period_end: data.period_end
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await sales_targets.setTenant( data.tenant || null, {
transaction,
});
await sales_targets.setTarget_user( data.target_user || null, {
transaction,
});
await sales_targets.setOrganizations( data.organizations || null, {
transaction,
});
return sales_targets;
}
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 sales_targetsData = data.map((item, index) => ({
id: item.id || undefined,
target_name: item.target_name
||
null
,
target_scope: item.target_scope
||
null
,
metric: item.metric
||
null
,
target_value: item.target_value
||
null
,
achieved_value: item.achieved_value
||
null
,
period_start: item.period_start
||
null
,
period_end: item.period_end
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const sales_targets = await db.sales_targets.bulkCreate(sales_targetsData, { transaction });
// For each item created, replace relation files
return sales_targets;
}
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 sales_targets = await db.sales_targets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.target_name !== undefined) updatePayload.target_name = data.target_name;
if (data.target_scope !== undefined) updatePayload.target_scope = data.target_scope;
if (data.metric !== undefined) updatePayload.metric = data.metric;
if (data.target_value !== undefined) updatePayload.target_value = data.target_value;
if (data.achieved_value !== undefined) updatePayload.achieved_value = data.achieved_value;
if (data.period_start !== undefined) updatePayload.period_start = data.period_start;
if (data.period_end !== undefined) updatePayload.period_end = data.period_end;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await sales_targets.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await sales_targets.setTenant(
data.tenant,
{ transaction }
);
}
if (data.target_user !== undefined) {
await sales_targets.setTarget_user(
data.target_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await sales_targets.setOrganizations(
data.organizations,
{ transaction }
);
}
return sales_targets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sales_targets = await db.sales_targets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of sales_targets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of sales_targets) {
await record.destroy({transaction});
}
});
return sales_targets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const sales_targets = await db.sales_targets.findByPk(id, options);
await sales_targets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await sales_targets.destroy({
transaction
});
return sales_targets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const sales_targets = await db.sales_targets.findOne(
{ where },
{ transaction },
);
if (!sales_targets) {
return sales_targets;
}
const output = sales_targets.get({plain: true});
output.tenant = await sales_targets.getTenant({
transaction
});
output.target_user = await sales_targets.getTarget_user({
transaction
});
output.organizations = await sales_targets.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)) } },
{
tenant_name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'target_user',
where: filter.target_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.target_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.target_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.target_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'sales_targets',
'target_name',
filter.target_name,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'sales_targets',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
period_start: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
period_end: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.target_valueRange) {
const [start, end] = filter.target_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.lte]: end,
},
};
}
}
if (filter.achieved_valueRange) {
const [start, end] = filter.achieved_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
achieved_value: {
...where.achieved_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
achieved_value: {
...where.achieved_value,
[Op.lte]: end,
},
};
}
}
if (filter.period_startRange) {
const [start, end] = filter.period_startRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_start: {
...where.period_start,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_start: {
...where.period_start,
[Op.lte]: end,
},
};
}
}
if (filter.period_endRange) {
const [start, end] = filter.period_endRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_end: {
...where.period_end,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_end: {
...where.period_end,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.target_scope) {
where = {
...where,
target_scope: filter.target_scope,
};
}
if (filter.metric) {
where = {
...where,
metric: filter.metric,
};
}
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.sales_targets.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(
'sales_targets',
'target_name',
query,
),
],
};
}
const records = await db.sales_targets.findAll({
attributes: [ 'id', 'target_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['target_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.target_name,
}));
}
};

View File

@ -0,0 +1,572 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Store_pagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const store_pages = await db.store_pages.create(
{
id: data.id || undefined,
page_title: data.page_title
||
null
,
slug: data.slug
||
null
,
page_type: data.page_type
||
null
,
page_status: data.page_status
||
null
,
content: data.content
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await store_pages.setReseller_store( data.reseller_store || null, {
transaction,
});
await store_pages.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.store_pages.getTableName(),
belongsToColumn: 'page_images',
belongsToId: store_pages.id,
},
data.page_images,
options,
);
return store_pages;
}
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 store_pagesData = data.map((item, index) => ({
id: item.id || undefined,
page_title: item.page_title
||
null
,
slug: item.slug
||
null
,
page_type: item.page_type
||
null
,
page_status: item.page_status
||
null
,
content: item.content
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const store_pages = await db.store_pages.bulkCreate(store_pagesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < store_pages.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.store_pages.getTableName(),
belongsToColumn: 'page_images',
belongsToId: store_pages[i].id,
},
data[i].page_images,
options,
);
}
return store_pages;
}
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 store_pages = await db.store_pages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.page_title !== undefined) updatePayload.page_title = data.page_title;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.page_type !== undefined) updatePayload.page_type = data.page_type;
if (data.page_status !== undefined) updatePayload.page_status = data.page_status;
if (data.content !== undefined) updatePayload.content = data.content;
updatePayload.updatedById = currentUser.id;
await store_pages.update(updatePayload, {transaction});
if (data.reseller_store !== undefined) {
await store_pages.setReseller_store(
data.reseller_store,
{ transaction }
);
}
if (data.organizations !== undefined) {
await store_pages.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.store_pages.getTableName(),
belongsToColumn: 'page_images',
belongsToId: store_pages.id,
},
data.page_images,
options,
);
return store_pages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const store_pages = await db.store_pages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of store_pages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of store_pages) {
await record.destroy({transaction});
}
});
return store_pages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const store_pages = await db.store_pages.findByPk(id, options);
await store_pages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await store_pages.destroy({
transaction
});
return store_pages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const store_pages = await db.store_pages.findOne(
{ where },
{ transaction },
);
if (!store_pages) {
return store_pages;
}
const output = store_pages.get({plain: true});
output.reseller_store = await store_pages.getReseller_store({
transaction
});
output.page_images = await store_pages.getPage_images({
transaction
});
output.organizations = await store_pages.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.reseller_stores,
as: 'reseller_store',
where: filter.reseller_store ? {
[Op.or]: [
{ id: { [Op.in]: filter.reseller_store.split('|').map(term => Utils.uuid(term)) } },
{
store_name: {
[Op.or]: filter.reseller_store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'page_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.page_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'store_pages',
'page_title',
filter.page_title,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'store_pages',
'slug',
filter.slug,
),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'store_pages',
'content',
filter.content,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.page_type) {
where = {
...where,
page_type: filter.page_type,
};
}
if (filter.page_status) {
where = {
...where,
page_status: filter.page_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.store_pages.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(
'store_pages',
'page_title',
query,
),
],
};
}
const records = await db.store_pages.findAll({
attributes: [ 'id', 'page_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['page_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.page_title,
}));
}
};

View File

@ -0,0 +1,729 @@
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,
tenant_name: data.tenant_name
||
null
,
legal_name: data.legal_name
||
null
,
domain: data.domain
||
null
,
industry: data.industry
||
null
,
default_currency: data.default_currency
||
null
,
timezone: data.timezone
||
null
,
is_active: data.is_active
||
false
,
support_email: data.support_email
||
null
,
support_phone: data.support_phone
||
null
,
address: data.address
||
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_images',
belongsToId: tenants.id,
},
data.logo_images,
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,
tenant_name: item.tenant_name
||
null
,
legal_name: item.legal_name
||
null
,
domain: item.domain
||
null
,
industry: item.industry
||
null
,
default_currency: item.default_currency
||
null
,
timezone: item.timezone
||
null
,
is_active: item.is_active
||
false
,
support_email: item.support_email
||
null
,
support_phone: item.support_phone
||
null
,
address: item.address
||
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_images',
belongsToId: tenants[i].id,
},
data[i].logo_images,
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.tenant_name !== undefined) updatePayload.tenant_name = data.tenant_name;
if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
if (data.domain !== undefined) updatePayload.domain = data.domain;
if (data.industry !== undefined) updatePayload.industry = data.industry;
if (data.default_currency !== undefined) updatePayload.default_currency = data.default_currency;
if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
if (data.support_phone !== undefined) updatePayload.support_phone = data.support_phone;
if (data.address !== undefined) updatePayload.address = data.address;
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_images',
belongsToId: tenants.id,
},
data.logo_images,
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.products_tenant = await tenants.getProducts_tenant({
transaction
});
output.warehouses_tenant = await tenants.getWarehouses_tenant({
transaction
});
output.inventory_items_tenant = await tenants.getInventory_items_tenant({
transaction
});
output.inventory_movements_tenant = await tenants.getInventory_movements_tenant({
transaction
});
output.customers_tenant = await tenants.getCustomers_tenant({
transaction
});
output.orders_tenant = await tenants.getOrders_tenant({
transaction
});
output.invoices_tenant = await tenants.getInvoices_tenant({
transaction
});
output.payments_tenant = await tenants.getPayments_tenant({
transaction
});
output.commission_plans_tenant = await tenants.getCommission_plans_tenant({
transaction
});
output.commissions_tenant = await tenants.getCommissions_tenant({
transaction
});
output.payouts_tenant = await tenants.getPayouts_tenant({
transaction
});
output.bonus_programs_tenant = await tenants.getBonus_programs_tenant({
transaction
});
output.referral_links_tenant = await tenants.getReferral_links_tenant({
transaction
});
output.reseller_stores_tenant = await tenants.getReseller_stores_tenant({
transaction
});
output.notifications_tenant = await tenants.getNotifications_tenant({
transaction
});
output.ai_insights_tenant = await tenants.getAi_insights_tenant({
transaction
});
output.sales_targets_tenant = await tenants.getSales_targets_tenant({
transaction
});
output.logo_images = await tenants.getLogo_images({
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_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.tenant_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'tenant_name',
filter.tenant_name,
),
};
}
if (filter.legal_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'legal_name',
filter.legal_name,
),
};
}
if (filter.domain) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'domain',
filter.domain,
),
};
}
if (filter.industry) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'industry',
filter.industry,
),
};
}
if (filter.default_currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'default_currency',
filter.default_currency,
),
};
}
if (filter.timezone) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'timezone',
filter.timezone,
),
};
}
if (filter.support_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'support_email',
filter.support_email,
),
};
}
if (filter.support_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'support_phone',
filter.support_phone,
),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'address',
filter.address,
),
};
}
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.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',
'tenant_name',
query,
),
],
};
}
const records = await db.tenants.findAll({
attributes: [ 'id', 'tenant_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['tenant_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.tenant_name,
}));
}
};

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

File diff suppressed because it is too large Load Diff

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 WarehousesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const warehouses = await db.warehouses.create(
{
id: data.id || undefined,
warehouse_name: data.warehouse_name
||
null
,
code: data.code
||
null
,
contact_name: data.contact_name
||
null
,
contact_phone: data.contact_phone
||
null
,
address: data.address
||
null
,
is_default: data.is_default
||
false
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await warehouses.setTenant( data.tenant || null, {
transaction,
});
await warehouses.setOrganizations( data.organizations || null, {
transaction,
});
return warehouses;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const warehousesData = data.map((item, index) => ({
id: item.id || undefined,
warehouse_name: item.warehouse_name
||
null
,
code: item.code
||
null
,
contact_name: item.contact_name
||
null
,
contact_phone: item.contact_phone
||
null
,
address: item.address
||
null
,
is_default: item.is_default
||
false
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const warehouses = await db.warehouses.bulkCreate(warehousesData, { transaction });
// For each item created, replace relation files
return warehouses;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const warehouses = await db.warehouses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.warehouse_name !== undefined) updatePayload.warehouse_name = data.warehouse_name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await warehouses.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await warehouses.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await warehouses.setOrganizations(
data.organizations,
{ transaction }
);
}
return warehouses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const warehouses = await db.warehouses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of warehouses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of warehouses) {
await record.destroy({transaction});
}
});
return warehouses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const warehouses = await db.warehouses.findByPk(id, options);
await warehouses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await warehouses.destroy({
transaction
});
return warehouses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const warehouses = await db.warehouses.findOne(
{ where },
{ transaction },
);
if (!warehouses) {
return warehouses;
}
const output = warehouses.get({plain: true});
output.inventory_items_warehouse = await warehouses.getInventory_items_warehouse({
transaction
});
output.inventory_movements_warehouse = await warehouses.getInventory_movements_warehouse({
transaction
});
output.orders_warehouse = await warehouses.getOrders_warehouse({
transaction
});
output.ai_insights_related_warehouse = await warehouses.getAi_insights_related_warehouse({
transaction
});
output.tenant = await warehouses.getTenant({
transaction
});
output.organizations = await warehouses.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
tenant_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.warehouse_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'warehouses',
'warehouse_name',
filter.warehouse_name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'warehouses',
'code',
filter.code,
),
};
}
if (filter.contact_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'warehouses',
'contact_name',
filter.contact_name,
),
};
}
if (filter.contact_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'warehouses',
'contact_phone',
filter.contact_phone,
),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'warehouses',
'address',
filter.address,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_default) {
where = {
...where,
is_default: filter.is_default,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.warehouses.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'warehouses',
'warehouse_name',
query,
),
],
};
}
const records = await db.warehouses.findAll({
attributes: [ 'id', 'warehouse_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['warehouse_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.warehouse_name,
}));
}
};

View File

@ -0,0 +1,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_vorta_reselleros',
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,215 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ai_insights = sequelize.define(
'ai_insights',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
insight_type: {
type: DataTypes.ENUM,
values: [
"sales_forecast",
"stock_forecast",
"performance_drop",
"top_reseller",
"strategy_recommendation",
"market_opportunity"
],
},
severity: {
type: DataTypes.ENUM,
values: [
"info",
"warning",
"critical"
],
},
insight_title: {
type: DataTypes.TEXT,
},
insight_summary: {
type: DataTypes.TEXT,
},
recommendation: {
type: DataTypes.TEXT,
},
generated_at: {
type: DataTypes.DATE,
},
valid_until: {
type: DataTypes.DATE,
},
is_acknowledged: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ai_insights.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.ai_insights.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.ai_insights.belongsTo(db.users, {
as: 'related_user',
foreignKey: {
name: 'related_userId',
},
constraints: false,
});
db.ai_insights.belongsTo(db.products, {
as: 'related_product',
foreignKey: {
name: 'related_productId',
},
constraints: false,
});
db.ai_insights.belongsTo(db.warehouses, {
as: 'related_warehouse',
foreignKey: {
name: 'related_warehouseId',
},
constraints: false,
});
db.ai_insights.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.ai_insights.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_insights.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_insights;
};

View File

@ -0,0 +1,218 @@
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 bonus_programs = sequelize.define(
'bonus_programs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
program_name: {
type: DataTypes.TEXT,
},
program_status: {
type: DataTypes.ENUM,
values: [
"draft",
"active",
"inactive",
"ended"
],
},
target_metric: {
type: DataTypes.ENUM,
values: [
"revenue",
"profit_estimate",
"orders_count",
"units_sold"
],
},
target_value: {
type: DataTypes.DECIMAL,
},
reward_type: {
type: DataTypes.ENUM,
values: [
"percentage",
"fixed_amount",
"gift"
],
},
reward_rate: {
type: DataTypes.DECIMAL,
},
reward_amount: {
type: DataTypes.DECIMAL,
},
gift_description: {
type: DataTypes.TEXT,
},
starts_at: {
type: DataTypes.DATE,
},
ends_at: {
type: DataTypes.DATE,
},
terms: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
bonus_programs.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.bonus_programs.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.bonus_programs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.bonus_programs.belongsTo(db.users, {
as: 'createdBy',
});
db.bonus_programs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return bonus_programs;
};

View File

@ -0,0 +1,234 @@
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 commission_plans = sequelize.define(
'commission_plans',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
plan_name: {
type: DataTypes.TEXT,
},
plan_status: {
type: DataTypes.ENUM,
values: [
"draft",
"active",
"inactive"
],
},
calculation_base: {
type: DataTypes.ENUM,
values: [
"order_subtotal",
"order_total",
"profit_estimate",
"line_item_total"
],
},
commission_type: {
type: DataTypes.ENUM,
values: [
"percentage",
"fixed_amount"
],
},
default_rate: {
type: DataTypes.DECIMAL,
},
default_amount: {
type: DataTypes.DECIMAL,
},
include_shipping: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
include_tax: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
effective_from: {
type: DataTypes.DATE,
},
effective_to: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
commission_plans.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.commission_plans.hasMany(db.commission_rules, {
as: 'commission_rules_commission_plan',
foreignKey: {
name: 'commission_planId',
},
constraints: false,
});
db.commission_plans.hasMany(db.commissions, {
as: 'commissions_commission_plan',
foreignKey: {
name: 'commission_planId',
},
constraints: false,
});
//end loop
db.commission_plans.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.commission_plans.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.commission_plans.belongsTo(db.users, {
as: 'createdBy',
});
db.commission_plans.belongsTo(db.users, {
as: 'updatedBy',
});
};
return commission_plans;
};

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 commission_rules = sequelize.define(
'commission_rules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
applies_to_role: {
type: DataTypes.ENUM,
values: [
"reseller",
"agent",
"distributor",
"master_distributor"
],
},
commission_type: {
type: DataTypes.ENUM,
values: [
"percentage",
"fixed_amount"
],
},
rate: {
type: DataTypes.DECIMAL,
},
amount: {
type: DataTypes.DECIMAL,
},
min_order_amount: {
type: DataTypes.DECIMAL,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
rule_name: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
commission_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.commission_rules.belongsTo(db.commission_plans, {
as: 'commission_plan',
foreignKey: {
name: 'commission_planId',
},
constraints: false,
});
db.commission_rules.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.commission_rules.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.commission_rules.belongsTo(db.users, {
as: 'createdBy',
});
db.commission_rules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return commission_rules;
};

View File

@ -0,0 +1,230 @@
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 commissions = sequelize.define(
'commissions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
commission_code: {
type: DataTypes.TEXT,
},
commission_status: {
type: DataTypes.ENUM,
values: [
"pending",
"approved",
"payable",
"paid",
"reversed",
"cancelled"
],
},
commission_type: {
type: DataTypes.ENUM,
values: [
"sale",
"referral",
"bonus",
"adjustment"
],
},
base_amount: {
type: DataTypes.DECIMAL,
},
commission_amount: {
type: DataTypes.DECIMAL,
},
earned_at: {
type: DataTypes.DATE,
},
approved_at: {
type: DataTypes.DATE,
},
paid_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
commissions.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.commissions.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.commissions.belongsTo(db.orders, {
as: 'order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.commissions.belongsTo(db.order_items, {
as: 'order_item',
foreignKey: {
name: 'order_itemId',
},
constraints: false,
});
db.commissions.belongsTo(db.users, {
as: 'beneficiary_user',
foreignKey: {
name: 'beneficiary_userId',
},
constraints: false,
});
db.commissions.belongsTo(db.commission_plans, {
as: 'commission_plan',
foreignKey: {
name: 'commission_planId',
},
constraints: false,
});
db.commissions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.commissions.belongsTo(db.users, {
as: 'createdBy',
});
db.commissions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return commissions;
};

View File

@ -0,0 +1,163 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const customers = sequelize.define(
'customers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
customer_name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone_number: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
province: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
customers.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.customers.hasMany(db.orders, {
as: 'orders_customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
//end loop
db.customers.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.customers.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.customers.belongsTo(db.users, {
as: 'createdBy',
});
db.customers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return customers;
};

View File

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

View File

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

View File

@ -0,0 +1,150 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const inventory_items = sequelize.define(
'inventory_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
on_hand_qty: {
type: DataTypes.INTEGER,
},
reserved_qty: {
type: DataTypes.INTEGER,
},
available_qty: {
type: DataTypes.INTEGER,
},
last_counted_at: {
type: DataTypes.DATE,
},
note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
inventory_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.inventory_items.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.inventory_items.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.inventory_items.belongsTo(db.warehouses, {
as: 'warehouse',
foreignKey: {
name: 'warehouseId',
},
constraints: false,
});
db.inventory_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.inventory_items.belongsTo(db.users, {
as: 'createdBy',
});
db.inventory_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inventory_items;
};

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 inventory_movements = sequelize.define(
'inventory_movements',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
movement_type: {
type: DataTypes.ENUM,
values: [
"in",
"out",
"adjustment",
"transfer_out",
"transfer_in"
],
},
quantity: {
type: DataTypes.INTEGER,
},
unit_cost: {
type: DataTypes.DECIMAL,
},
reference_type: {
type: DataTypes.TEXT,
},
reference_number: {
type: DataTypes.TEXT,
},
moved_at: {
type: DataTypes.DATE,
},
note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
inventory_movements.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.inventory_movements.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.warehouses, {
as: 'warehouse',
foreignKey: {
name: 'warehouseId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.users, {
as: 'performed_by',
foreignKey: {
name: 'performed_byId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.inventory_movements.belongsTo(db.users, {
as: 'createdBy',
});
db.inventory_movements.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inventory_movements;
};

View File

@ -0,0 +1,199 @@
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 invoices = sequelize.define(
'invoices',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
invoice_number: {
type: DataTypes.TEXT,
},
invoice_status: {
type: DataTypes.ENUM,
values: [
"draft",
"issued",
"paid",
"void",
"refunded"
],
},
issued_at: {
type: DataTypes.DATE,
},
due_at: {
type: DataTypes.DATE,
},
amount_due: {
type: DataTypes.DECIMAL,
},
amount_paid: {
type: DataTypes.DECIMAL,
},
billing_name: {
type: DataTypes.TEXT,
},
billing_address: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
invoices.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.invoices.hasMany(db.payments, {
as: 'payments_invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
//end loop
db.invoices.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.invoices.belongsTo(db.orders, {
as: 'order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.invoices.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.invoices.hasMany(db.file, {
as: 'invoice_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.invoices.getTableName(),
belongsToColumn: 'invoice_files',
},
});
db.invoices.belongsTo(db.users, {
as: 'createdBy',
});
db.invoices.belongsTo(db.users, {
as: 'updatedBy',
});
};
return invoices;
};

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 notifications = sequelize.define(
'notifications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
notification_type: {
type: DataTypes.ENUM,
values: [
"low_stock",
"order_update",
"commission_update",
"payout_update",
"system",
"ai_insight"
],
},
channel: {
type: DataTypes.ENUM,
values: [
"in_app",
"email",
"whatsapp",
"sms",
"push"
],
},
title_text: {
type: DataTypes.TEXT,
},
message_text: {
type: DataTypes.TEXT,
},
action_url: {
type: DataTypes.TEXT,
},
is_read: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
sent_at: {
type: DataTypes.DATE,
},
read_at: {
type: DataTypes.DATE,
},
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: 'recipient_user',
foreignKey: {
name: 'recipient_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,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 order_items = sequelize.define(
'order_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
item_name: {
type: DataTypes.TEXT,
},
sku: {
type: DataTypes.TEXT,
},
unit_price: {
type: DataTypes.DECIMAL,
},
quantity: {
type: DataTypes.INTEGER,
},
discount_amount: {
type: DataTypes.DECIMAL,
},
line_total_amount: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
order_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.order_items.hasMany(db.commissions, {
as: 'commissions_order_item',
foreignKey: {
name: 'order_itemId',
},
constraints: false,
});
//end loop
db.order_items.belongsTo(db.orders, {
as: 'order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.order_items.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.order_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.order_items.belongsTo(db.users, {
as: 'createdBy',
});
db.order_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return order_items;
};

View File

@ -0,0 +1,373 @@
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 orders = sequelize.define(
'orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
order_number: {
type: DataTypes.TEXT,
},
order_channel: {
type: DataTypes.ENUM,
values: [
"admin",
"reseller_storefront",
"affiliate_link",
"manual_import",
"api"
],
},
order_status: {
type: DataTypes.ENUM,
values: [
"draft",
"pending_payment",
"paid",
"processing",
"packed",
"shipped",
"delivered",
"cancelled",
"refunded"
],
},
subtotal_amount: {
type: DataTypes.DECIMAL,
},
discount_amount: {
type: DataTypes.DECIMAL,
},
shipping_amount: {
type: DataTypes.DECIMAL,
},
tax_amount: {
type: DataTypes.DECIMAL,
},
total_amount: {
type: DataTypes.DECIMAL,
},
payment_status: {
type: DataTypes.ENUM,
values: [
"unpaid",
"paid",
"partial",
"refunded"
],
},
fulfillment_status: {
type: DataTypes.ENUM,
values: [
"unfulfilled",
"partial",
"fulfilled",
"returned"
],
},
shipping_courier: {
type: DataTypes.TEXT,
},
shipping_service: {
type: DataTypes.TEXT,
},
tracking_number: {
type: DataTypes.TEXT,
},
ordered_at: {
type: DataTypes.DATE,
},
paid_at: {
type: DataTypes.DATE,
},
shipped_at: {
type: DataTypes.DATE,
},
delivered_at: {
type: DataTypes.DATE,
},
shipping_address: {
type: DataTypes.TEXT,
},
customer_note: {
type: DataTypes.TEXT,
},
internal_note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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.orders.hasMany(db.order_items, {
as: 'order_items_order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.orders.hasMany(db.invoices, {
as: 'invoices_order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.orders.hasMany(db.payments, {
as: 'payments_order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.orders.hasMany(db.commissions, {
as: 'commissions_order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
//end loop
db.orders.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.orders.belongsTo(db.customers, {
as: 'customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.orders.belongsTo(db.users, {
as: 'seller_user',
foreignKey: {
name: 'seller_userId',
},
constraints: false,
});
db.orders.belongsTo(db.warehouses, {
as: 'warehouse',
foreignKey: {
name: 'warehouseId',
},
constraints: false,
});
db.orders.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.orders.belongsTo(db.users, {
as: 'createdBy',
});
db.orders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return orders;
};

View File

@ -0,0 +1,266 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const 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.products, {
as: 'products_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.warehouses, {
as: 'warehouses_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.inventory_items, {
as: 'inventory_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.inventory_movements, {
as: 'inventory_movements_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.customers, {
as: 'customers_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.orders, {
as: 'orders_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.order_items, {
as: 'order_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.invoices, {
as: 'invoices_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.payments, {
as: 'payments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.commission_plans, {
as: 'commission_plans_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.commission_rules, {
as: 'commission_rules_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.commissions, {
as: 'commissions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.payouts, {
as: 'payouts_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.bonus_programs, {
as: 'bonus_programs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.referral_links, {
as: 'referral_links_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.reseller_stores, {
as: 'reseller_stores_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.store_pages, {
as: 'store_pages_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.notifications, {
as: 'notifications_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.ai_insights, {
as: 'ai_insights_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.sales_targets, {
as: 'sales_targets_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,210 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const payments = sequelize.define(
'payments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
payment_reference: {
type: DataTypes.TEXT,
},
payment_method: {
type: DataTypes.ENUM,
values: [
"bank_transfer",
"cash",
"cod",
"ewallet",
"virtual_account",
"payment_gateway"
],
},
payment_status: {
type: DataTypes.ENUM,
values: [
"pending",
"succeeded",
"failed",
"refunded"
],
},
amount: {
type: DataTypes.DECIMAL,
},
paid_at: {
type: DataTypes.DATE,
},
payer_name: {
type: DataTypes.TEXT,
},
note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payments.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.payments.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.payments.belongsTo(db.orders, {
as: 'order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.payments.belongsTo(db.invoices, {
as: 'invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.payments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.payments.hasMany(db.file, {
as: 'proof_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.payments.getTableName(),
belongsToColumn: 'proof_files',
},
});
db.payments.belongsTo(db.users, {
as: 'createdBy',
});
db.payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payments;
};

View File

@ -0,0 +1,220 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const payouts = sequelize.define(
'payouts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
payout_reference: {
type: DataTypes.TEXT,
},
payout_method: {
type: DataTypes.ENUM,
values: [
"bank_transfer",
"ewallet",
"cash"
],
},
payout_status: {
type: DataTypes.ENUM,
values: [
"draft",
"scheduled",
"processing",
"paid",
"failed",
"cancelled"
],
},
gross_amount: {
type: DataTypes.DECIMAL,
},
fee_amount: {
type: DataTypes.DECIMAL,
},
net_amount: {
type: DataTypes.DECIMAL,
},
scheduled_at: {
type: DataTypes.DATE,
},
processed_at: {
type: DataTypes.DATE,
},
paid_at: {
type: DataTypes.DATE,
},
note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payouts.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.payouts.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.payouts.belongsTo(db.users, {
as: 'recipient_user',
foreignKey: {
name: 'recipient_userId',
},
constraints: false,
});
db.payouts.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.payouts.hasMany(db.file, {
as: 'payout_proof_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.payouts.getTableName(),
belongsToColumn: 'payout_proof_files',
},
});
db.payouts.belongsTo(db.users, {
as: 'createdBy',
});
db.payouts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payouts;
};

View File

@ -0,0 +1,90 @@
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,302 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const products = sequelize.define(
'products',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
product_name: {
type: DataTypes.TEXT,
},
sku: {
type: DataTypes.TEXT,
},
barcode: {
type: DataTypes.TEXT,
},
product_status: {
type: DataTypes.ENUM,
values: [
"draft",
"active",
"archived"
],
},
brand: {
type: DataTypes.TEXT,
},
category: {
type: DataTypes.TEXT,
},
unit: {
type: DataTypes.TEXT,
},
weight_grams: {
type: DataTypes.DECIMAL,
},
length_cm: {
type: DataTypes.DECIMAL,
},
width_cm: {
type: DataTypes.DECIMAL,
},
height_cm: {
type: DataTypes.DECIMAL,
},
cost_price: {
type: DataTypes.DECIMAL,
},
retail_price: {
type: DataTypes.DECIMAL,
},
reseller_price: {
type: DataTypes.DECIMAL,
},
agent_price: {
type: DataTypes.DECIMAL,
},
distributor_price: {
type: DataTypes.DECIMAL,
},
low_stock_threshold: {
type: DataTypes.INTEGER,
},
short_description: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
products.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.products.hasMany(db.inventory_items, {
as: 'inventory_items_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.inventory_movements, {
as: 'inventory_movements_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.order_items, {
as: 'order_items_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.commission_rules, {
as: 'commission_rules_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.referral_links, {
as: 'referral_links_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.ai_insights, {
as: 'ai_insights_related_product',
foreignKey: {
name: 'related_productId',
},
constraints: false,
});
//end loop
db.products.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.products.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.products.hasMany(db.file, {
as: 'product_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.products.getTableName(),
belongsToColumn: 'product_images',
},
});
db.products.belongsTo(db.users, {
as: 'createdBy',
});
db.products.belongsTo(db.users, {
as: 'updatedBy',
});
};
return products;
};

View File

@ -0,0 +1,196 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const referral_links = sequelize.define(
'referral_links',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
link_name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
destination_url: {
type: DataTypes.TEXT,
},
link_type: {
type: DataTypes.ENUM,
values: [
"storefront",
"product",
"landing_page",
"campaign"
],
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
starts_at: {
type: DataTypes.DATE,
},
ends_at: {
type: DataTypes.DATE,
},
click_count: {
type: DataTypes.INTEGER,
},
conversion_count: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
referral_links.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.referral_links.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.referral_links.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.referral_links.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.referral_links.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.referral_links.belongsTo(db.users, {
as: 'createdBy',
});
db.referral_links.belongsTo(db.users, {
as: 'updatedBy',
});
};
return referral_links;
};

View File

@ -0,0 +1,200 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const reseller_stores = sequelize.define(
'reseller_stores',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
store_name: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
store_status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"suspended"
],
},
tagline: {
type: DataTypes.TEXT,
},
about: {
type: DataTypes.TEXT,
},
whatsapp_number: {
type: DataTypes.TEXT,
},
instagram_handle: {
type: DataTypes.TEXT,
},
tiktok_handle: {
type: DataTypes.TEXT,
},
custom_domain: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
reseller_stores.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.reseller_stores.hasMany(db.store_pages, {
as: 'store_pages_reseller_store',
foreignKey: {
name: 'reseller_storeId',
},
constraints: false,
});
//end loop
db.reseller_stores.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.reseller_stores.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.reseller_stores.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.reseller_stores.hasMany(db.file, {
as: 'banner_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.reseller_stores.getTableName(),
belongsToColumn: 'banner_images',
},
});
db.reseller_stores.belongsTo(db.users, {
as: 'createdBy',
});
db.reseller_stores.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reseller_stores;
};

View File

@ -0,0 +1,133 @@
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,215 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const sales_targets = sequelize.define(
'sales_targets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
target_name: {
type: DataTypes.TEXT,
},
target_scope: {
type: DataTypes.ENUM,
values: [
"company",
"user",
"team"
],
},
metric: {
type: DataTypes.ENUM,
values: [
"revenue",
"orders_count",
"units_sold",
"new_resellers"
],
},
target_value: {
type: DataTypes.DECIMAL,
},
achieved_value: {
type: DataTypes.DECIMAL,
},
period_start: {
type: DataTypes.DATE,
},
period_end: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"planned",
"active",
"achieved",
"missed",
"cancelled"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
sales_targets.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.sales_targets.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.sales_targets.belongsTo(db.users, {
as: 'target_user',
foreignKey: {
name: 'target_userId',
},
constraints: false,
});
db.sales_targets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.sales_targets.belongsTo(db.users, {
as: 'createdBy',
});
db.sales_targets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return sales_targets;
};

View File

@ -0,0 +1,174 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const store_pages = sequelize.define(
'store_pages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
page_title: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
page_type: {
type: DataTypes.ENUM,
values: [
"landing",
"product_list",
"faq",
"policy",
"custom"
],
},
page_status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"archived"
],
},
content: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
store_pages.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.store_pages.belongsTo(db.reseller_stores, {
as: 'reseller_store',
foreignKey: {
name: 'reseller_storeId',
},
constraints: false,
});
db.store_pages.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.store_pages.hasMany(db.file, {
as: 'page_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.store_pages.getTableName(),
belongsToColumn: 'page_images',
},
});
db.store_pages.belongsTo(db.users, {
as: 'createdBy',
});
db.store_pages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return store_pages;
};

View File

@ -0,0 +1,310 @@
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,
},
tenant_name: {
type: DataTypes.TEXT,
},
legal_name: {
type: DataTypes.TEXT,
},
domain: {
type: DataTypes.TEXT,
},
industry: {
type: DataTypes.TEXT,
},
default_currency: {
type: DataTypes.TEXT,
},
timezone: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
support_email: {
type: DataTypes.TEXT,
},
support_phone: {
type: DataTypes.TEXT,
},
address: {
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.products, {
as: 'products_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.warehouses, {
as: 'warehouses_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.inventory_items, {
as: 'inventory_items_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.inventory_movements, {
as: 'inventory_movements_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.customers, {
as: 'customers_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.orders, {
as: 'orders_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.invoices, {
as: 'invoices_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.payments, {
as: 'payments_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.commission_plans, {
as: 'commission_plans_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.commissions, {
as: 'commissions_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.payouts, {
as: 'payouts_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.bonus_programs, {
as: 'bonus_programs_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.referral_links, {
as: 'referral_links_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.reseller_stores, {
as: 'reseller_stores_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.notifications, {
as: 'notifications_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.ai_insights, {
as: 'ai_insights_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.sales_targets, {
as: 'sales_targets_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_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.tenants.getTableName(),
belongsToColumn: 'logo_images',
},
});
db.tenants.belongsTo(db.users, {
as: 'createdBy',
});
db.tenants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tenants;
};

View File

@ -0,0 +1,328 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const users = sequelize.define(
'users',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
firstName: {
type: DataTypes.TEXT,
},
lastName: {
type: DataTypes.TEXT,
},
phoneNumber: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
disabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
password: {
type: DataTypes.TEXT,
},
emailVerified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
emailVerificationToken: {
type: DataTypes.TEXT,
},
emailVerificationTokenExpiresAt: {
type: DataTypes.DATE,
},
passwordResetToken: {
type: DataTypes.TEXT,
},
passwordResetTokenExpiresAt: {
type: DataTypes.DATE,
},
provider: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
users.associate = (db) => {
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions_filter',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.users.hasMany(db.inventory_movements, {
as: 'inventory_movements_performed_by',
foreignKey: {
name: 'performed_byId',
},
constraints: false,
});
db.users.hasMany(db.orders, {
as: 'orders_seller_user',
foreignKey: {
name: 'seller_userId',
},
constraints: false,
});
db.users.hasMany(db.commissions, {
as: 'commissions_beneficiary_user',
foreignKey: {
name: 'beneficiary_userId',
},
constraints: false,
});
db.users.hasMany(db.payouts, {
as: 'payouts_recipient_user',
foreignKey: {
name: 'recipient_userId',
},
constraints: false,
});
db.users.hasMany(db.referral_links, {
as: 'referral_links_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.users.hasMany(db.reseller_stores, {
as: 'reseller_stores_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.users.hasMany(db.notifications, {
as: 'notifications_recipient_user',
foreignKey: {
name: 'recipient_userId',
},
constraints: false,
});
db.users.hasMany(db.ai_insights, {
as: 'ai_insights_related_user',
foreignKey: {
name: 'related_userId',
},
constraints: false,
});
db.users.hasMany(db.sales_targets, {
as: 'sales_targets_target_user',
foreignKey: {
name: 'target_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,186 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const warehouses = sequelize.define(
'warehouses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
warehouse_name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
contact_name: {
type: DataTypes.TEXT,
},
contact_phone: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
is_default: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
warehouses.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.warehouses.hasMany(db.inventory_items, {
as: 'inventory_items_warehouse',
foreignKey: {
name: 'warehouseId',
},
constraints: false,
});
db.warehouses.hasMany(db.inventory_movements, {
as: 'inventory_movements_warehouse',
foreignKey: {
name: 'warehouseId',
},
constraints: false,
});
db.warehouses.hasMany(db.orders, {
as: 'orders_warehouse',
foreignKey: {
name: 'warehouseId',
},
constraints: false,
});
db.warehouses.hasMany(db.ai_insights, {
as: 'ai_insights_related_warehouse',
foreignKey: {
name: 'related_warehouseId',
},
constraints: false,
});
//end loop
db.warehouses.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.warehouses.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.warehouses.belongsTo(db.users, {
as: 'createdBy',
});
db.warehouses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return warehouses;
};

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

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

@ -0,0 +1,231 @@
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 productsRoutes = require('./routes/products');
const warehousesRoutes = require('./routes/warehouses');
const inventory_itemsRoutes = require('./routes/inventory_items');
const inventory_movementsRoutes = require('./routes/inventory_movements');
const customersRoutes = require('./routes/customers');
const ordersRoutes = require('./routes/orders');
const order_itemsRoutes = require('./routes/order_items');
const invoicesRoutes = require('./routes/invoices');
const paymentsRoutes = require('./routes/payments');
const commission_plansRoutes = require('./routes/commission_plans');
const commission_rulesRoutes = require('./routes/commission_rules');
const commissionsRoutes = require('./routes/commissions');
const payoutsRoutes = require('./routes/payouts');
const bonus_programsRoutes = require('./routes/bonus_programs');
const referral_linksRoutes = require('./routes/referral_links');
const reseller_storesRoutes = require('./routes/reseller_stores');
const store_pagesRoutes = require('./routes/store_pages');
const notificationsRoutes = require('./routes/notifications');
const ai_insightsRoutes = require('./routes/ai_insights');
const sales_targetsRoutes = require('./routes/sales_targets');
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: "VORTA ResellerOS",
description: "VORTA ResellerOS 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/products', passport.authenticate('jwt', {session: false}), productsRoutes);
app.use('/api/warehouses', passport.authenticate('jwt', {session: false}), warehousesRoutes);
app.use('/api/inventory_items', passport.authenticate('jwt', {session: false}), inventory_itemsRoutes);
app.use('/api/inventory_movements', passport.authenticate('jwt', {session: false}), inventory_movementsRoutes);
app.use('/api/customers', passport.authenticate('jwt', {session: false}), customersRoutes);
app.use('/api/orders', passport.authenticate('jwt', {session: false}), ordersRoutes);
app.use('/api/order_items', passport.authenticate('jwt', {session: false}), order_itemsRoutes);
app.use('/api/invoices', passport.authenticate('jwt', {session: false}), invoicesRoutes);
app.use('/api/payments', passport.authenticate('jwt', {session: false}), paymentsRoutes);
app.use('/api/commission_plans', passport.authenticate('jwt', {session: false}), commission_plansRoutes);
app.use('/api/commission_rules', passport.authenticate('jwt', {session: false}), commission_rulesRoutes);
app.use('/api/commissions', passport.authenticate('jwt', {session: false}), commissionsRoutes);
app.use('/api/payouts', passport.authenticate('jwt', {session: false}), payoutsRoutes);
app.use('/api/bonus_programs', passport.authenticate('jwt', {session: false}), bonus_programsRoutes);
app.use('/api/referral_links', passport.authenticate('jwt', {session: false}), referral_linksRoutes);
app.use('/api/reseller_stores', passport.authenticate('jwt', {session: false}), reseller_storesRoutes);
app.use('/api/store_pages', passport.authenticate('jwt', {session: false}), store_pagesRoutes);
app.use('/api/notifications', passport.authenticate('jwt', {session: false}), notificationsRoutes);
app.use('/api/ai_insights', passport.authenticate('jwt', {session: false}), ai_insightsRoutes);
app.use('/api/sales_targets', passport.authenticate('jwt', {session: false}), sales_targetsRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
app.use(
'/api/org-for-auth',
organizationForAuthRoutes,
);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
module.exports = app;

View File

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

View File

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

View File

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

View File

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

View File

@ -0,0 +1,32 @@
const express = require('express');
const config = require('../config');
const path = require('path');
const passport = require('passport');
const services = require('../services/file');
const router = express.Router();
router.get('/download', (req, res) => {
if (process.env.NODE_ENV == "production" || process.env.NEXT_PUBLIC_BACK_API) {
services.downloadGCloud(req, res);
}
else {
services.downloadLocal(req, res);
}
});
router.post('/upload/:table/:field', passport.authenticate('jwt', {session: false}), (req, res) => {
const fileName = `${req.params.table}/${req.params.field}`;
if (process.env.NODE_ENV == "production" || process.env.NEXT_PUBLIC_BACK_API) {
services.uploadGCloud(fileName, req, res);
}
else {
services.uploadLocal(fileName, {
entity: null,
maxFileSize: 10 * 1024 * 1024,
folderIncludesAuthenticationUid: false,
})(req, res);
}
});
module.exports = router;

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,328 @@
const express = require('express');
const db = require('../db/models');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const sjs = require('sequelize-json-schema');
const { getWidget, askGpt } = require('../services/openai');
const { LocalAIApi } = require('../ai/LocalAIApi');
const loadRolesModules = () => {
try {
return {
RolesService: require('../services/roles'),
RolesDBApi: require('../db/api/roles'),
};
} catch (error) {
console.error('Roles modules are missing. Advanced roles are required for this endpoint.', error);
const err = new Error('Roles modules are missing. Advanced roles are required for this endpoint.');
err.originalError = error;
throw err;
}
};
/**
* @swagger
* /api/roles/roles-info/{infoId}:
* delete:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Remove role information by ID
* description: Remove specific role information by ID
* parameters:
* - in: path
* name: infoId
* description: ID of role information to remove
* required: true
* schema:
* type: string
* - in: query
* name: userId
* description: ID of the user
* required: true
* schema:
* type: string
* - in: query
* name: key
* description: Key of the role information to remove
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Role information successfully removed
* content:
* application/json:
* schema:
* type: object
* properties:
* user:
* type: string
* description: The user information
* 400:
* description: Invalid ID or key supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Role not found
* 500:
* description: Some server error
*/
router.delete(
'/roles-info/:infoId',
wrapAsync(async (req, res) => {
const { RolesService } = loadRolesModules();
const role = await RolesService.removeRoleInfoById(
req.query.infoId,
req.query.roleId,
req.query.key,
req.currentUser,
);
res.status(200).send(role);
}),
);
/**
* @swagger
* /api/roles/role-info/{roleId}:
* get:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Get role information by key
* description: Get specific role information by key
* parameters:
* - in: path
* name: roleId
* description: ID of role to get information for
* required: true
* schema:
* type: string
* - in: query
* name: key
* description: Key of the role information to retrieve
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Role information successfully received
* content:
* application/json:
* schema:
* type: object
* properties:
* info:
* type: string
* description: The role information
* 400:
* description: Invalid ID or key supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Role not found
* 500:
* description: Some server error
*/
router.get(
'/info-by-key',
wrapAsync(async (req, res) => {
const { RolesService, RolesDBApi } = loadRolesModules();
const roleId = req.query.roleId;
const key = req.query.key;
const currentUser = req.currentUser;
let info = await RolesService.getRoleInfoByKey(
key,
roleId,
currentUser,
);
const role = await RolesDBApi.findBy({ id: roleId });
if (!role?.role_customization) {
await Promise.all(["pie", "bar"].map(async (e) => {
const schema = await sjs.getSequelizeSchema(db.sequelize, {});
const payload = {
description: `Create some cool ${e} chart`,
modelDefinition: schema.definitions,
};
const widgetId = await getWidget(payload, currentUser?.id, roleId);
if (widgetId) {
await RolesService.addRoleInfo(
roleId,
currentUser?.id,
'widgets',
widgetId,
req.currentUser,
);
}
}))
info = await RolesService.getRoleInfoByKey(
key,
roleId,
currentUser,
);
}
res.status(200).send(info);
}),
);
router.post(
'/create_widget',
wrapAsync(async (req, res) => {
const { RolesService } = loadRolesModules();
const { description, userId, roleId } = req.body;
const currentUser = req.currentUser;
const schema = await sjs.getSequelizeSchema(db.sequelize, {});
const payload = {
description,
modelDefinition: schema.definitions,
};
const widgetId = await getWidget(payload, userId, roleId);
if (widgetId) {
await RolesService.addRoleInfo(
roleId,
userId,
'widgets',
widgetId,
currentUser,
);
return res.status(200).send(widgetId);
} else {
return res.status(400).send(widgetId);
}
}),
);
/**
* @swagger
* /api/openai/response:
* post:
* security:
* - bearerAuth: []
* tags: [OpenAI]
* summary: Proxy a Responses API request
* description: Sends the payload to the Flatlogic AI proxy and returns the response.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* input:
* type: array
* description: List of messages with roles and content.
* items:
* type: object
* properties:
* role:
* type: string
* content:
* type: string
* options:
* type: object
* description: Optional polling controls.
* properties:
* poll_interval:
* type: number
* poll_timeout:
* type: number
* responses:
* 200:
* description: AI response received
* 400:
* description: Invalid request
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 502:
* description: Proxy error
*/
router.post(
'/response',
wrapAsync(async (req, res) => {
const body = req.body || {};
const options = body.options || {};
const payload = { ...body };
delete payload.options;
const response = await LocalAIApi.createResponse(payload, options);
if (response.success) {
return res.status(200).send(response);
}
console.error('AI proxy error:', response);
const status = response.error === 'input_missing' ? 400 : 502;
return res.status(status).send(response);
}),
);
/**
* @swagger
* /api/openai/ask:
* post:
* security:
* - bearerAuth: []
* tags: [OpenAI]
* summary: Ask a question to ChatGPT
* description: Send a question through the Flatlogic AI proxy and get a response
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* prompt:
* type: string
* description: The question to ask ChatGPT
* responses:
* 200:
* description: Question successfully answered
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* description: Whether the request was successful
* data:
* type: string
* description: The answer from ChatGPT
* 400:
* description: Invalid request
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 500:
* description: Some server error
*/
router.post(
'/ask-gpt',
wrapAsync(async (req, res) => {
const { prompt } = req.body;
if (!prompt) {
return res.status(400).send({
success: false,
error: 'Prompt is required',
});
}
const response = await askGpt(prompt);
if (response.success) {
return res.status(200).send(response);
} else {
return res.status(500).send(response);
}
}),
);
module.exports = router;

View File

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

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