Initial version

This commit is contained in:
Flatlogic Bot 2026-06-18 21:11:44 +00:00
commit a4ecdd89c9
841 changed files with 318591 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 Universe MVP</h2>
<p>Unified super-app for verified identity, chat-to-commerce, and citation-backed search with a single wallet.</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 Universe MVP
## 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 Universe MVP - 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_universe_mvp;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_vorta_universe_mvp 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": "vortauniversemvp",
"description": "Vorta Universe MVP - 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: "9654d2ec",
user_pass: "d1ee0bfa4a0f",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '9654d2ec-35eb-46fc-a269-d1ee0bfa4a0f',
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 Universe MVP <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: 'Verified Member',
},
project_uuid: '9654d2ec-35eb-46fc-a269-d1ee0bfa4a0f',
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 = 'Constellation over calm night';
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,758 @@
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 AddressesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const addresses = await db.addresses.create(
{
id: data.id || undefined,
label: data.label
||
null
,
recipient_name: data.recipient_name
||
null
,
phone_number: data.phone_number
||
null
,
country: data.country
||
null
,
province: data.province
||
null
,
city: data.city
||
null
,
district: data.district
||
null
,
postal_code: data.postal_code
||
null
,
street_address: data.street_address
||
null
,
latitude: data.latitude
||
null
,
longitude: data.longitude
||
null
,
is_default: data.is_default
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await addresses.setUser( data.user || null, {
transaction,
});
await addresses.setOrganizations( data.organizations || null, {
transaction,
});
return addresses;
}
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 addressesData = data.map((item, index) => ({
id: item.id || undefined,
label: item.label
||
null
,
recipient_name: item.recipient_name
||
null
,
phone_number: item.phone_number
||
null
,
country: item.country
||
null
,
province: item.province
||
null
,
city: item.city
||
null
,
district: item.district
||
null
,
postal_code: item.postal_code
||
null
,
street_address: item.street_address
||
null
,
latitude: item.latitude
||
null
,
longitude: item.longitude
||
null
,
is_default: item.is_default
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const addresses = await db.addresses.bulkCreate(addressesData, { transaction });
// For each item created, replace relation files
return addresses;
}
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 addresses = await db.addresses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.label !== undefined) updatePayload.label = data.label;
if (data.recipient_name !== undefined) updatePayload.recipient_name = data.recipient_name;
if (data.phone_number !== undefined) updatePayload.phone_number = data.phone_number;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.province !== undefined) updatePayload.province = data.province;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.district !== undefined) updatePayload.district = data.district;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
if (data.street_address !== undefined) updatePayload.street_address = data.street_address;
if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
updatePayload.updatedById = currentUser.id;
await addresses.update(updatePayload, {transaction});
if (data.user !== undefined) {
await addresses.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await addresses.setOrganizations(
data.organizations,
{ transaction }
);
}
return addresses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const addresses = await db.addresses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of addresses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of addresses) {
await record.destroy({transaction});
}
});
return addresses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const addresses = await db.addresses.findByPk(id, options);
await addresses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await addresses.destroy({
transaction
});
return addresses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const addresses = await db.addresses.findOne(
{ where },
{ transaction },
);
if (!addresses) {
return addresses;
}
const output = addresses.get({plain: true});
output.stores_primary_address = await addresses.getStores_primary_address({
transaction
});
output.orders_shipping_address = await addresses.getOrders_shipping_address({
transaction
});
output.job_companies_hq_address = await addresses.getJob_companies_hq_address({
transaction
});
output.user = await addresses.getUser({
transaction
});
output.organizations = await addresses.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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.label) {
where = {
...where,
[Op.and]: Utils.ilike(
'addresses',
'label',
filter.label,
),
};
}
if (filter.recipient_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'addresses',
'recipient_name',
filter.recipient_name,
),
};
}
if (filter.phone_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'addresses',
'phone_number',
filter.phone_number,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'addresses',
'country',
filter.country,
),
};
}
if (filter.province) {
where = {
...where,
[Op.and]: Utils.ilike(
'addresses',
'province',
filter.province,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'addresses',
'city',
filter.city,
),
};
}
if (filter.district) {
where = {
...where,
[Op.and]: Utils.ilike(
'addresses',
'district',
filter.district,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'addresses',
'postal_code',
filter.postal_code,
),
};
}
if (filter.street_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'addresses',
'street_address',
filter.street_address,
),
};
}
if (filter.latitudeRange) {
const [start, end] = filter.latitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
latitude: {
...where.latitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
latitude: {
...where.latitude,
[Op.lte]: end,
},
};
}
}
if (filter.longitudeRange) {
const [start, end] = filter.longitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
longitude: {
...where.longitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
longitude: {
...where.longitude,
[Op.lte]: end,
},
};
}
}
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.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.addresses.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(
'addresses',
'label',
query,
),
],
};
}
const records = await db.addresses.findAll({
attributes: [ 'id', 'label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.label,
}));
}
};

View File

@ -0,0 +1,617 @@
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 Affiliate_membershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const affiliate_memberships = await db.affiliate_memberships.create(
{
id: data.id || undefined,
status: data.status
||
null
,
applied_at: data.applied_at
||
null
,
approved_at: data.approved_at
||
null
,
referral_code: data.referral_code
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await affiliate_memberships.setProgram( data.program || null, {
transaction,
});
await affiliate_memberships.setMember( data.member || null, {
transaction,
});
await affiliate_memberships.setOrganizations( data.organizations || null, {
transaction,
});
return affiliate_memberships;
}
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 affiliate_membershipsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
applied_at: item.applied_at
||
null
,
approved_at: item.approved_at
||
null
,
referral_code: item.referral_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 affiliate_memberships = await db.affiliate_memberships.bulkCreate(affiliate_membershipsData, { transaction });
// For each item created, replace relation files
return affiliate_memberships;
}
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 affiliate_memberships = await db.affiliate_memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.applied_at !== undefined) updatePayload.applied_at = data.applied_at;
if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
if (data.referral_code !== undefined) updatePayload.referral_code = data.referral_code;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await affiliate_memberships.update(updatePayload, {transaction});
if (data.program !== undefined) {
await affiliate_memberships.setProgram(
data.program,
{ transaction }
);
}
if (data.member !== undefined) {
await affiliate_memberships.setMember(
data.member,
{ transaction }
);
}
if (data.organizations !== undefined) {
await affiliate_memberships.setOrganizations(
data.organizations,
{ transaction }
);
}
return affiliate_memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const affiliate_memberships = await db.affiliate_memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of affiliate_memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of affiliate_memberships) {
await record.destroy({transaction});
}
});
return affiliate_memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const affiliate_memberships = await db.affiliate_memberships.findByPk(id, options);
await affiliate_memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await affiliate_memberships.destroy({
transaction
});
return affiliate_memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const affiliate_memberships = await db.affiliate_memberships.findOne(
{ where },
{ transaction },
);
if (!affiliate_memberships) {
return affiliate_memberships;
}
const output = affiliate_memberships.get({plain: true});
output.commissions_membership = await affiliate_memberships.getCommissions_membership({
transaction
});
output.program = await affiliate_memberships.getProgram({
transaction
});
output.member = await affiliate_memberships.getMember({
transaction
});
output.organizations = await affiliate_memberships.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.affiliate_programs,
as: 'program',
where: filter.program ? {
[Op.or]: [
{ id: { [Op.in]: filter.program.split('|').map(term => Utils.uuid(term)) } },
{
program_name: {
[Op.or]: filter.program.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'member',
where: filter.member ? {
[Op.or]: [
{ id: { [Op.in]: filter.member.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.member.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.referral_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'affiliate_memberships',
'referral_code',
filter.referral_code,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'affiliate_memberships',
'notes',
filter.notes,
),
};
}
if (filter.applied_atRange) {
const [start, end] = filter.applied_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
applied_at: {
...where.applied_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
applied_at: {
...where.applied_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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.affiliate_memberships.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(
'affiliate_memberships',
'referral_code',
query,
),
],
};
}
const records = await db.affiliate_memberships.findAll({
attributes: [ 'id', 'referral_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['referral_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.referral_code,
}));
}
};

View File

@ -0,0 +1,654 @@
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 Affiliate_programsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const affiliate_programs = await db.affiliate_programs.create(
{
id: data.id || undefined,
program_name: data.program_name
||
null
,
status: data.status
||
null
,
commission_rate_percent: data.commission_rate_percent
||
null
,
terms_text: data.terms_text
||
null
,
min_trust_score_to_join: data.min_trust_score_to_join
||
null
,
starts_at: data.starts_at
||
null
,
ends_at: data.ends_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await affiliate_programs.setProducer_store( data.producer_store || null, {
transaction,
});
await affiliate_programs.setOrganizations( data.organizations || null, {
transaction,
});
return affiliate_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 affiliate_programsData = data.map((item, index) => ({
id: item.id || undefined,
program_name: item.program_name
||
null
,
status: item.status
||
null
,
commission_rate_percent: item.commission_rate_percent
||
null
,
terms_text: item.terms_text
||
null
,
min_trust_score_to_join: item.min_trust_score_to_join
||
null
,
starts_at: item.starts_at
||
null
,
ends_at: item.ends_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const affiliate_programs = await db.affiliate_programs.bulkCreate(affiliate_programsData, { transaction });
// For each item created, replace relation files
return affiliate_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 affiliate_programs = await db.affiliate_programs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.program_name !== undefined) updatePayload.program_name = data.program_name;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.commission_rate_percent !== undefined) updatePayload.commission_rate_percent = data.commission_rate_percent;
if (data.terms_text !== undefined) updatePayload.terms_text = data.terms_text;
if (data.min_trust_score_to_join !== undefined) updatePayload.min_trust_score_to_join = data.min_trust_score_to_join;
if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
updatePayload.updatedById = currentUser.id;
await affiliate_programs.update(updatePayload, {transaction});
if (data.producer_store !== undefined) {
await affiliate_programs.setProducer_store(
data.producer_store,
{ transaction }
);
}
if (data.organizations !== undefined) {
await affiliate_programs.setOrganizations(
data.organizations,
{ transaction }
);
}
return affiliate_programs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const affiliate_programs = await db.affiliate_programs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of affiliate_programs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of affiliate_programs) {
await record.destroy({transaction});
}
});
return affiliate_programs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const affiliate_programs = await db.affiliate_programs.findByPk(id, options);
await affiliate_programs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await affiliate_programs.destroy({
transaction
});
return affiliate_programs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const affiliate_programs = await db.affiliate_programs.findOne(
{ where },
{ transaction },
);
if (!affiliate_programs) {
return affiliate_programs;
}
const output = affiliate_programs.get({plain: true});
output.affiliate_memberships_program = await affiliate_programs.getAffiliate_memberships_program({
transaction
});
output.producer_store = await affiliate_programs.getProducer_store({
transaction
});
output.organizations = await affiliate_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.stores,
as: 'producer_store',
where: filter.producer_store ? {
[Op.or]: [
{ id: { [Op.in]: filter.producer_store.split('|').map(term => Utils.uuid(term)) } },
{
store_name: {
[Op.or]: filter.producer_store.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(
'affiliate_programs',
'program_name',
filter.program_name,
),
};
}
if (filter.terms_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'affiliate_programs',
'terms_text',
filter.terms_text,
),
};
}
if (filter.commission_rate_percentRange) {
const [start, end] = filter.commission_rate_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commission_rate_percent: {
...where.commission_rate_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commission_rate_percent: {
...where.commission_rate_percent,
[Op.lte]: end,
},
};
}
}
if (filter.min_trust_score_to_joinRange) {
const [start, end] = filter.min_trust_score_to_joinRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_trust_score_to_join: {
...where.min_trust_score_to_join,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_trust_score_to_join: {
...where.min_trust_score_to_join,
[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.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.affiliate_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(
'affiliate_programs',
'program_name',
query,
),
],
};
}
const records = await db.affiliate_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,631 @@
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 Api_clientsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const api_clients = await db.api_clients.create(
{
id: data.id || undefined,
client_name: data.client_name
||
null
,
client_type: data.client_type
||
null
,
status: data.status
||
null
,
contact_email: data.contact_email
||
null
,
contact_phone: data.contact_phone
||
null
,
api_key_label: data.api_key_label
||
null
,
issued_at: data.issued_at
||
null
,
last_used_at: data.last_used_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await api_clients.setOrganizations( data.organizations || null, {
transaction,
});
return api_clients;
}
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 api_clientsData = data.map((item, index) => ({
id: item.id || undefined,
client_name: item.client_name
||
null
,
client_type: item.client_type
||
null
,
status: item.status
||
null
,
contact_email: item.contact_email
||
null
,
contact_phone: item.contact_phone
||
null
,
api_key_label: item.api_key_label
||
null
,
issued_at: item.issued_at
||
null
,
last_used_at: item.last_used_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 api_clients = await db.api_clients.bulkCreate(api_clientsData, { transaction });
// For each item created, replace relation files
return api_clients;
}
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 api_clients = await db.api_clients.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.client_name !== undefined) updatePayload.client_name = data.client_name;
if (data.client_type !== undefined) updatePayload.client_type = data.client_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
if (data.api_key_label !== undefined) updatePayload.api_key_label = data.api_key_label;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.last_used_at !== undefined) updatePayload.last_used_at = data.last_used_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await api_clients.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await api_clients.setOrganizations(
data.organizations,
{ transaction }
);
}
return api_clients;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const api_clients = await db.api_clients.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of api_clients) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of api_clients) {
await record.destroy({transaction});
}
});
return api_clients;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const api_clients = await db.api_clients.findByPk(id, options);
await api_clients.update({
deletedBy: currentUser.id
}, {
transaction,
});
await api_clients.destroy({
transaction
});
return api_clients;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const api_clients = await db.api_clients.findOne(
{ where },
{ transaction },
);
if (!api_clients) {
return api_clients;
}
const output = api_clients.get({plain: true});
output.organizations = await api_clients.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.client_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_clients',
'client_name',
filter.client_name,
),
};
}
if (filter.contact_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_clients',
'contact_email',
filter.contact_email,
),
};
}
if (filter.contact_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_clients',
'contact_phone',
filter.contact_phone,
),
};
}
if (filter.api_key_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_clients',
'api_key_label',
filter.api_key_label,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_clients',
'notes',
filter.notes,
),
};
}
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.last_used_atRange) {
const [start, end] = filter.last_used_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_used_at: {
...where.last_used_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_used_at: {
...where.last_used_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.client_type) {
where = {
...where,
client_type: filter.client_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.api_clients.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(
'api_clients',
'client_name',
query,
),
],
};
}
const records = await db.api_clients.findAll({
attributes: [ 'id', 'client_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['client_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.client_name,
}));
}
};

View File

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

View File

@ -0,0 +1,550 @@
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 Chat_participantsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const chat_participants = await db.chat_participants.create(
{
id: data.id || undefined,
role: data.role
||
null
,
joined_at: data.joined_at
||
null
,
is_muted: data.is_muted
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await chat_participants.setChat( data.chat || null, {
transaction,
});
await chat_participants.setUser( data.user || null, {
transaction,
});
await chat_participants.setOrganizations( data.organizations || null, {
transaction,
});
return chat_participants;
}
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 chat_participantsData = data.map((item, index) => ({
id: item.id || undefined,
role: item.role
||
null
,
joined_at: item.joined_at
||
null
,
is_muted: item.is_muted
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const chat_participants = await db.chat_participants.bulkCreate(chat_participantsData, { transaction });
// For each item created, replace relation files
return chat_participants;
}
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 chat_participants = await db.chat_participants.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.role !== undefined) updatePayload.role = data.role;
if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
if (data.is_muted !== undefined) updatePayload.is_muted = data.is_muted;
updatePayload.updatedById = currentUser.id;
await chat_participants.update(updatePayload, {transaction});
if (data.chat !== undefined) {
await chat_participants.setChat(
data.chat,
{ transaction }
);
}
if (data.user !== undefined) {
await chat_participants.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await chat_participants.setOrganizations(
data.organizations,
{ transaction }
);
}
return chat_participants;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const chat_participants = await db.chat_participants.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of chat_participants) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of chat_participants) {
await record.destroy({transaction});
}
});
return chat_participants;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const chat_participants = await db.chat_participants.findByPk(id, options);
await chat_participants.update({
deletedBy: currentUser.id
}, {
transaction,
});
await chat_participants.destroy({
transaction
});
return chat_participants;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const chat_participants = await db.chat_participants.findOne(
{ where },
{ transaction },
);
if (!chat_participants) {
return chat_participants;
}
const output = chat_participants.get({plain: true});
output.chat = await chat_participants.getChat({
transaction
});
output.user = await chat_participants.getUser({
transaction
});
output.organizations = await chat_participants.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.chats,
as: 'chat',
where: filter.chat ? {
[Op.or]: [
{ id: { [Op.in]: filter.chat.split('|').map(term => Utils.uuid(term)) } },
{
chat_title: {
[Op.or]: filter.chat.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.joined_atRange) {
const [start, end] = filter.joined_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.role) {
where = {
...where,
role: filter.role,
};
}
if (filter.is_muted) {
where = {
...where,
is_muted: filter.is_muted,
};
}
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.chat_participants.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(
'chat_participants',
'role',
query,
),
],
};
}
const records = await db.chat_participants.findAll({
attributes: [ 'id', 'role' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['role', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.role,
}));
}
};

550
backend/src/db/api/chats.js Normal file
View File

@ -0,0 +1,550 @@
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 ChatsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const chats = await db.chats.create(
{
id: data.id || undefined,
chat_type: data.chat_type
||
null
,
chat_title: data.chat_title
||
null
,
last_message_at: data.last_message_at
||
null
,
is_encrypted: data.is_encrypted
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await chats.setOrganizations( data.organizations || null, {
transaction,
});
await chats.setParticipants(data.participants || [], {
transaction,
});
return chats;
}
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 chatsData = data.map((item, index) => ({
id: item.id || undefined,
chat_type: item.chat_type
||
null
,
chat_title: item.chat_title
||
null
,
last_message_at: item.last_message_at
||
null
,
is_encrypted: item.is_encrypted
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const chats = await db.chats.bulkCreate(chatsData, { transaction });
// For each item created, replace relation files
return chats;
}
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 chats = await db.chats.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.chat_type !== undefined) updatePayload.chat_type = data.chat_type;
if (data.chat_title !== undefined) updatePayload.chat_title = data.chat_title;
if (data.last_message_at !== undefined) updatePayload.last_message_at = data.last_message_at;
if (data.is_encrypted !== undefined) updatePayload.is_encrypted = data.is_encrypted;
updatePayload.updatedById = currentUser.id;
await chats.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await chats.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.participants !== undefined) {
await chats.setParticipants(data.participants, { transaction });
}
return chats;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const chats = await db.chats.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of chats) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of chats) {
await record.destroy({transaction});
}
});
return chats;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const chats = await db.chats.findByPk(id, options);
await chats.update({
deletedBy: currentUser.id
}, {
transaction,
});
await chats.destroy({
transaction
});
return chats;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const chats = await db.chats.findOne(
{ where },
{ transaction },
);
if (!chats) {
return chats;
}
const output = chats.get({plain: true});
output.chat_participants_chat = await chats.getChat_participants_chat({
transaction
});
output.messages_chat = await chats.getMessages_chat({
transaction
});
output.participants = await chats.getParticipants({
transaction
});
output.organizations = await chats.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.chat_participants,
as: 'participants',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.chat_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'chats',
'chat_title',
filter.chat_title,
),
};
}
if (filter.last_message_atRange) {
const [start, end] = filter.last_message_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_message_at: {
...where.last_message_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_message_at: {
...where.last_message_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.chat_type) {
where = {
...where,
chat_type: filter.chat_type,
};
}
if (filter.is_encrypted) {
where = {
...where,
is_encrypted: filter.is_encrypted,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.participants) {
const searchTerms = filter.participants.split('|');
include = [
{
model: db.chat_participants,
as: 'participants_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
role: {
[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) {
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.chats.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(
'chats',
'chat_title',
query,
),
],
};
}
const records = await db.chats.findAll({
attributes: [ 'id', 'chat_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['chat_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.chat_title,
}));
}
};

View File

@ -0,0 +1,594 @@
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 CitationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const citations = await db.citations.create(
{
id: data.id || undefined,
source_type: data.source_type
||
null
,
source_title: data.source_title
||
null
,
source_url: data.source_url
||
null
,
publisher: data.publisher
||
null
,
published_at: data.published_at
||
null
,
quote_excerpt: data.quote_excerpt
||
null
,
doi_or_identifier: data.doi_or_identifier
||
null
,
credibility_grade: data.credibility_grade
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await citations.setOrganizations( data.organizations || null, {
transaction,
});
return citations;
}
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 citationsData = data.map((item, index) => ({
id: item.id || undefined,
source_type: item.source_type
||
null
,
source_title: item.source_title
||
null
,
source_url: item.source_url
||
null
,
publisher: item.publisher
||
null
,
published_at: item.published_at
||
null
,
quote_excerpt: item.quote_excerpt
||
null
,
doi_or_identifier: item.doi_or_identifier
||
null
,
credibility_grade: item.credibility_grade
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const citations = await db.citations.bulkCreate(citationsData, { transaction });
// For each item created, replace relation files
return citations;
}
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 citations = await db.citations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.source_type !== undefined) updatePayload.source_type = data.source_type;
if (data.source_title !== undefined) updatePayload.source_title = data.source_title;
if (data.source_url !== undefined) updatePayload.source_url = data.source_url;
if (data.publisher !== undefined) updatePayload.publisher = data.publisher;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
if (data.quote_excerpt !== undefined) updatePayload.quote_excerpt = data.quote_excerpt;
if (data.doi_or_identifier !== undefined) updatePayload.doi_or_identifier = data.doi_or_identifier;
if (data.credibility_grade !== undefined) updatePayload.credibility_grade = data.credibility_grade;
updatePayload.updatedById = currentUser.id;
await citations.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await citations.setOrganizations(
data.organizations,
{ transaction }
);
}
return citations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const citations = await db.citations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of citations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of citations) {
await record.destroy({transaction});
}
});
return citations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const citations = await db.citations.findByPk(id, options);
await citations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await citations.destroy({
transaction
});
return citations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const citations = await db.citations.findOne(
{ where },
{ transaction },
);
if (!citations) {
return citations;
}
const output = citations.get({plain: true});
output.organizations = await citations.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.source_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'citations',
'source_title',
filter.source_title,
),
};
}
if (filter.source_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'citations',
'source_url',
filter.source_url,
),
};
}
if (filter.publisher) {
where = {
...where,
[Op.and]: Utils.ilike(
'citations',
'publisher',
filter.publisher,
),
};
}
if (filter.quote_excerpt) {
where = {
...where,
[Op.and]: Utils.ilike(
'citations',
'quote_excerpt',
filter.quote_excerpt,
),
};
}
if (filter.doi_or_identifier) {
where = {
...where,
[Op.and]: Utils.ilike(
'citations',
'doi_or_identifier',
filter.doi_or_identifier,
),
};
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.source_type) {
where = {
...where,
source_type: filter.source_type,
};
}
if (filter.credibility_grade) {
where = {
...where,
credibility_grade: filter.credibility_grade,
};
}
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.citations.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(
'citations',
'source_title',
query,
),
],
};
}
const records = await db.citations.findAll({
attributes: [ 'id', 'source_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['source_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.source_title,
}));
}
};

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 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,
status: data.status
||
null
,
gross_profit_amount: data.gross_profit_amount
||
null
,
commission_amount: data.commission_amount
||
null
,
commission_rate_percent: data.commission_rate_percent
||
null
,
earned_at: data.earned_at
||
null
,
paid_at: data.paid_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await commissions.setMembership( data.membership || null, {
transaction,
});
await commissions.setOrder( data.order || null, {
transaction,
});
await commissions.setWallet_transaction( data.wallet_transaction || 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,
status: item.status
||
null
,
gross_profit_amount: item.gross_profit_amount
||
null
,
commission_amount: item.commission_amount
||
null
,
commission_rate_percent: item.commission_rate_percent
||
null
,
earned_at: item.earned_at
||
null
,
paid_at: item.paid_at
||
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.status !== undefined) updatePayload.status = data.status;
if (data.gross_profit_amount !== undefined) updatePayload.gross_profit_amount = data.gross_profit_amount;
if (data.commission_amount !== undefined) updatePayload.commission_amount = data.commission_amount;
if (data.commission_rate_percent !== undefined) updatePayload.commission_rate_percent = data.commission_rate_percent;
if (data.earned_at !== undefined) updatePayload.earned_at = data.earned_at;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
updatePayload.updatedById = currentUser.id;
await commissions.update(updatePayload, {transaction});
if (data.membership !== undefined) {
await commissions.setMembership(
data.membership,
{ transaction }
);
}
if (data.order !== undefined) {
await commissions.setOrder(
data.order,
{ transaction }
);
}
if (data.wallet_transaction !== undefined) {
await commissions.setWallet_transaction(
data.wallet_transaction,
{ 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.membership = await commissions.getMembership({
transaction
});
output.order = await commissions.getOrder({
transaction
});
output.wallet_transaction = await commissions.getWallet_transaction({
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.affiliate_memberships,
as: 'membership',
where: filter.membership ? {
[Op.or]: [
{ id: { [Op.in]: filter.membership.split('|').map(term => Utils.uuid(term)) } },
{
referral_code: {
[Op.or]: filter.membership.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.wallet_transactions,
as: 'wallet_transaction',
where: filter.wallet_transaction ? {
[Op.or]: [
{ id: { [Op.in]: filter.wallet_transaction.split('|').map(term => Utils.uuid(term)) } },
{
reference_code: {
[Op.or]: filter.wallet_transaction.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.gross_profit_amountRange) {
const [start, end] = filter.gross_profit_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
gross_profit_amount: {
...where.gross_profit_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
gross_profit_amount: {
...where.gross_profit_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.commission_rate_percentRange) {
const [start, end] = filter.commission_rate_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commission_rate_percent: {
...where.commission_rate_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commission_rate_percent: {
...where.commission_rate_percent,
[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.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.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.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',
'status',
query,
),
],
};
}
const records = await db.commissions.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,627 @@
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 Deep_dive_linksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const deep_dive_links = await db.deep_dive_links.create(
{
id: data.id || undefined,
title_text: data.title_text
||
null
,
summary: data.summary
||
null
,
validation_status: data.validation_status
||
null
,
ai_confidence: data.ai_confidence
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await deep_dive_links.setCreator( data.creator || null, {
transaction,
});
await deep_dive_links.setOrganizations( data.organizations || null, {
transaction,
});
await deep_dive_links.setCitations(data.citations || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.deep_dive_links.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: deep_dive_links.id,
},
data.evidence_files,
options,
);
return deep_dive_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 deep_dive_linksData = data.map((item, index) => ({
id: item.id || undefined,
title_text: item.title_text
||
null
,
summary: item.summary
||
null
,
validation_status: item.validation_status
||
null
,
ai_confidence: item.ai_confidence
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const deep_dive_links = await db.deep_dive_links.bulkCreate(deep_dive_linksData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < deep_dive_links.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.deep_dive_links.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: deep_dive_links[i].id,
},
data[i].evidence_files,
options,
);
}
return deep_dive_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 deep_dive_links = await db.deep_dive_links.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
if (data.summary !== undefined) updatePayload.summary = data.summary;
if (data.validation_status !== undefined) updatePayload.validation_status = data.validation_status;
if (data.ai_confidence !== undefined) updatePayload.ai_confidence = data.ai_confidence;
updatePayload.updatedById = currentUser.id;
await deep_dive_links.update(updatePayload, {transaction});
if (data.creator !== undefined) {
await deep_dive_links.setCreator(
data.creator,
{ transaction }
);
}
if (data.organizations !== undefined) {
await deep_dive_links.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.citations !== undefined) {
await deep_dive_links.setCitations(data.citations, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.deep_dive_links.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: deep_dive_links.id,
},
data.evidence_files,
options,
);
return deep_dive_links;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const deep_dive_links = await db.deep_dive_links.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of deep_dive_links) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of deep_dive_links) {
await record.destroy({transaction});
}
});
return deep_dive_links;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const deep_dive_links = await db.deep_dive_links.findByPk(id, options);
await deep_dive_links.update({
deletedBy: currentUser.id
}, {
transaction,
});
await deep_dive_links.destroy({
transaction
});
return deep_dive_links;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const deep_dive_links = await db.deep_dive_links.findOne(
{ where },
{ transaction },
);
if (!deep_dive_links) {
return deep_dive_links;
}
const output = deep_dive_links.get({plain: true});
output.posts_deep_dive_link = await deep_dive_links.getPosts_deep_dive_link({
transaction
});
output.creator = await deep_dive_links.getCreator({
transaction
});
output.evidence_files = await deep_dive_links.getEvidence_files({
transaction
});
output.citations = await deep_dive_links.getCitations({
transaction
});
output.organizations = await deep_dive_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.users,
as: 'creator',
where: filter.creator ? {
[Op.or]: [
{ id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.creator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.citations,
as: 'citations',
required: false,
},
{
model: db.file,
as: 'evidence_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'deep_dive_links',
'title_text',
filter.title_text,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'deep_dive_links',
'summary',
filter.summary,
),
};
}
if (filter.ai_confidenceRange) {
const [start, end] = filter.ai_confidenceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ai_confidence: {
...where.ai_confidence,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ai_confidence: {
...where.ai_confidence,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.validation_status) {
where = {
...where,
validation_status: filter.validation_status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.citations) {
const searchTerms = filter.citations.split('|');
include = [
{
model: db.citations,
as: 'citations_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
source_title: {
[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) {
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.deep_dive_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(
'deep_dive_links',
'title_text',
query,
),
],
};
}
const records = await db.deep_dive_links.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,690 @@
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 Facta_answersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const facta_answers = await db.facta_answers.create(
{
id: data.id || undefined,
executive_summary: data.executive_summary
||
null
,
truth_score_percent: data.truth_score_percent
||
null
,
verification_status: data.verification_status
||
null
,
ready_to_cite_text: data.ready_to_cite_text
||
null
,
neutral_perspective: data.neutral_perspective
||
null
,
pro_perspective: data.pro_perspective
||
null
,
contra_perspective: data.contra_perspective
||
null
,
generated_at: data.generated_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await facta_answers.setFacta_query( data.facta_query || null, {
transaction,
});
await facta_answers.setOrganizations( data.organizations || null, {
transaction,
});
await facta_answers.setCitations(data.citations || [], {
transaction,
});
return facta_answers;
}
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 facta_answersData = data.map((item, index) => ({
id: item.id || undefined,
executive_summary: item.executive_summary
||
null
,
truth_score_percent: item.truth_score_percent
||
null
,
verification_status: item.verification_status
||
null
,
ready_to_cite_text: item.ready_to_cite_text
||
null
,
neutral_perspective: item.neutral_perspective
||
null
,
pro_perspective: item.pro_perspective
||
null
,
contra_perspective: item.contra_perspective
||
null
,
generated_at: item.generated_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const facta_answers = await db.facta_answers.bulkCreate(facta_answersData, { transaction });
// For each item created, replace relation files
return facta_answers;
}
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 facta_answers = await db.facta_answers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.executive_summary !== undefined) updatePayload.executive_summary = data.executive_summary;
if (data.truth_score_percent !== undefined) updatePayload.truth_score_percent = data.truth_score_percent;
if (data.verification_status !== undefined) updatePayload.verification_status = data.verification_status;
if (data.ready_to_cite_text !== undefined) updatePayload.ready_to_cite_text = data.ready_to_cite_text;
if (data.neutral_perspective !== undefined) updatePayload.neutral_perspective = data.neutral_perspective;
if (data.pro_perspective !== undefined) updatePayload.pro_perspective = data.pro_perspective;
if (data.contra_perspective !== undefined) updatePayload.contra_perspective = data.contra_perspective;
if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
updatePayload.updatedById = currentUser.id;
await facta_answers.update(updatePayload, {transaction});
if (data.facta_query !== undefined) {
await facta_answers.setFacta_query(
data.facta_query,
{ transaction }
);
}
if (data.organizations !== undefined) {
await facta_answers.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.citations !== undefined) {
await facta_answers.setCitations(data.citations, { transaction });
}
return facta_answers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const facta_answers = await db.facta_answers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of facta_answers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of facta_answers) {
await record.destroy({transaction});
}
});
return facta_answers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const facta_answers = await db.facta_answers.findByPk(id, options);
await facta_answers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await facta_answers.destroy({
transaction
});
return facta_answers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const facta_answers = await db.facta_answers.findOne(
{ where },
{ transaction },
);
if (!facta_answers) {
return facta_answers;
}
const output = facta_answers.get({plain: true});
output.facta_query = await facta_answers.getFacta_query({
transaction
});
output.citations = await facta_answers.getCitations({
transaction
});
output.organizations = await facta_answers.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.facta_queries,
as: 'facta_query',
where: filter.facta_query ? {
[Op.or]: [
{ id: { [Op.in]: filter.facta_query.split('|').map(term => Utils.uuid(term)) } },
{
query_text: {
[Op.or]: filter.facta_query.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.citations,
as: 'citations',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.executive_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'facta_answers',
'executive_summary',
filter.executive_summary,
),
};
}
if (filter.ready_to_cite_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'facta_answers',
'ready_to_cite_text',
filter.ready_to_cite_text,
),
};
}
if (filter.neutral_perspective) {
where = {
...where,
[Op.and]: Utils.ilike(
'facta_answers',
'neutral_perspective',
filter.neutral_perspective,
),
};
}
if (filter.pro_perspective) {
where = {
...where,
[Op.and]: Utils.ilike(
'facta_answers',
'pro_perspective',
filter.pro_perspective,
),
};
}
if (filter.contra_perspective) {
where = {
...where,
[Op.and]: Utils.ilike(
'facta_answers',
'contra_perspective',
filter.contra_perspective,
),
};
}
if (filter.truth_score_percentRange) {
const [start, end] = filter.truth_score_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
truth_score_percent: {
...where.truth_score_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
truth_score_percent: {
...where.truth_score_percent,
[Op.lte]: end,
},
};
}
}
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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.verification_status) {
where = {
...where,
verification_status: filter.verification_status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.citations) {
const searchTerms = filter.citations.split('|');
include = [
{
model: db.citations,
as: 'citations_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
source_title: {
[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) {
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.facta_answers.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(
'facta_answers',
'executive_summary',
query,
),
],
};
}
const records = await db.facta_answers.findAll({
attributes: [ 'id', 'executive_summary' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['executive_summary', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.executive_summary,
}));
}
};

View File

@ -0,0 +1,561 @@
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 Facta_queriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const facta_queries = await db.facta_queries.create(
{
id: data.id || undefined,
query_text: data.query_text
||
null
,
mode: data.mode
||
null
,
sensitivity: data.sensitivity
||
null
,
queried_at: data.queried_at
||
null
,
is_history_saved: data.is_history_saved
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await facta_queries.setUser( data.user || null, {
transaction,
});
await facta_queries.setOrganizations( data.organizations || null, {
transaction,
});
return facta_queries;
}
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 facta_queriesData = data.map((item, index) => ({
id: item.id || undefined,
query_text: item.query_text
||
null
,
mode: item.mode
||
null
,
sensitivity: item.sensitivity
||
null
,
queried_at: item.queried_at
||
null
,
is_history_saved: item.is_history_saved
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const facta_queries = await db.facta_queries.bulkCreate(facta_queriesData, { transaction });
// For each item created, replace relation files
return facta_queries;
}
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 facta_queries = await db.facta_queries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.query_text !== undefined) updatePayload.query_text = data.query_text;
if (data.mode !== undefined) updatePayload.mode = data.mode;
if (data.sensitivity !== undefined) updatePayload.sensitivity = data.sensitivity;
if (data.queried_at !== undefined) updatePayload.queried_at = data.queried_at;
if (data.is_history_saved !== undefined) updatePayload.is_history_saved = data.is_history_saved;
updatePayload.updatedById = currentUser.id;
await facta_queries.update(updatePayload, {transaction});
if (data.user !== undefined) {
await facta_queries.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await facta_queries.setOrganizations(
data.organizations,
{ transaction }
);
}
return facta_queries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const facta_queries = await db.facta_queries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of facta_queries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of facta_queries) {
await record.destroy({transaction});
}
});
return facta_queries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const facta_queries = await db.facta_queries.findByPk(id, options);
await facta_queries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await facta_queries.destroy({
transaction
});
return facta_queries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const facta_queries = await db.facta_queries.findOne(
{ where },
{ transaction },
);
if (!facta_queries) {
return facta_queries;
}
const output = facta_queries.get({plain: true});
output.facta_answers_facta_query = await facta_queries.getFacta_answers_facta_query({
transaction
});
output.user = await facta_queries.getUser({
transaction
});
output.organizations = await facta_queries.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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.query_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'facta_queries',
'query_text',
filter.query_text,
),
};
}
if (filter.queried_atRange) {
const [start, end] = filter.queried_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
queried_at: {
...where.queried_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
queried_at: {
...where.queried_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.mode) {
where = {
...where,
mode: filter.mode,
};
}
if (filter.sensitivity) {
where = {
...where,
sensitivity: filter.sensitivity,
};
}
if (filter.is_history_saved) {
where = {
...where,
is_history_saved: filter.is_history_saved,
};
}
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.facta_queries.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(
'facta_queries',
'query_text',
query,
),
],
};
}
const records = await db.facta_queries.findAll({
attributes: [ 'id', 'query_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['query_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.query_text,
}));
}
};

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,589 @@
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 Forum_postsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const forum_posts = await db.forum_posts.create(
{
id: data.id || undefined,
body_text: data.body_text
||
null
,
status: data.status
||
null
,
posted_at: data.posted_at
||
null
,
upvotes_count: data.upvotes_count
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await forum_posts.setThread( data.thread || null, {
transaction,
});
await forum_posts.setAuthor( data.author || null, {
transaction,
});
await forum_posts.setOrganizations( data.organizations || null, {
transaction,
});
return forum_posts;
}
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 forum_postsData = data.map((item, index) => ({
id: item.id || undefined,
body_text: item.body_text
||
null
,
status: item.status
||
null
,
posted_at: item.posted_at
||
null
,
upvotes_count: item.upvotes_count
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const forum_posts = await db.forum_posts.bulkCreate(forum_postsData, { transaction });
// For each item created, replace relation files
return forum_posts;
}
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 forum_posts = await db.forum_posts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.body_text !== undefined) updatePayload.body_text = data.body_text;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
if (data.upvotes_count !== undefined) updatePayload.upvotes_count = data.upvotes_count;
updatePayload.updatedById = currentUser.id;
await forum_posts.update(updatePayload, {transaction});
if (data.thread !== undefined) {
await forum_posts.setThread(
data.thread,
{ transaction }
);
}
if (data.author !== undefined) {
await forum_posts.setAuthor(
data.author,
{ transaction }
);
}
if (data.organizations !== undefined) {
await forum_posts.setOrganizations(
data.organizations,
{ transaction }
);
}
return forum_posts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const forum_posts = await db.forum_posts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of forum_posts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of forum_posts) {
await record.destroy({transaction});
}
});
return forum_posts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const forum_posts = await db.forum_posts.findByPk(id, options);
await forum_posts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await forum_posts.destroy({
transaction
});
return forum_posts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const forum_posts = await db.forum_posts.findOne(
{ where },
{ transaction },
);
if (!forum_posts) {
return forum_posts;
}
const output = forum_posts.get({plain: true});
output.thread = await forum_posts.getThread({
transaction
});
output.author = await forum_posts.getAuthor({
transaction
});
output.organizations = await forum_posts.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.forum_threads,
as: 'thread',
where: filter.thread ? {
[Op.or]: [
{ id: { [Op.in]: filter.thread.split('|').map(term => Utils.uuid(term)) } },
{
thread_title: {
[Op.or]: filter.thread.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'author',
where: filter.author ? {
[Op.or]: [
{ id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.body_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'forum_posts',
'body_text',
filter.body_text,
),
};
}
if (filter.posted_atRange) {
const [start, end] = filter.posted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.lte]: end,
},
};
}
}
if (filter.upvotes_countRange) {
const [start, end] = filter.upvotes_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
upvotes_count: {
...where.upvotes_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
upvotes_count: {
...where.upvotes_count,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.forum_posts.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(
'forum_posts',
'body_text',
query,
),
],
};
}
const records = await db.forum_posts.findAll({
attributes: [ 'id', 'body_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['body_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.body_text,
}));
}
};

View File

@ -0,0 +1,654 @@
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 Forum_spacesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const forum_spaces = await db.forum_spaces.create(
{
id: data.id || undefined,
space_name: data.space_name
||
null
,
description: data.description
||
null
,
center_latitude: data.center_latitude
||
null
,
center_longitude: data.center_longitude
||
null
,
radius_meters: data.radius_meters
||
null
,
min_trust_score_to_post: data.min_trust_score_to_post
||
null
,
visibility: data.visibility
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await forum_spaces.setOwner( data.owner || null, {
transaction,
});
await forum_spaces.setOrganizations( data.organizations || null, {
transaction,
});
return forum_spaces;
}
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 forum_spacesData = data.map((item, index) => ({
id: item.id || undefined,
space_name: item.space_name
||
null
,
description: item.description
||
null
,
center_latitude: item.center_latitude
||
null
,
center_longitude: item.center_longitude
||
null
,
radius_meters: item.radius_meters
||
null
,
min_trust_score_to_post: item.min_trust_score_to_post
||
null
,
visibility: item.visibility
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const forum_spaces = await db.forum_spaces.bulkCreate(forum_spacesData, { transaction });
// For each item created, replace relation files
return forum_spaces;
}
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 forum_spaces = await db.forum_spaces.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.space_name !== undefined) updatePayload.space_name = data.space_name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.center_latitude !== undefined) updatePayload.center_latitude = data.center_latitude;
if (data.center_longitude !== undefined) updatePayload.center_longitude = data.center_longitude;
if (data.radius_meters !== undefined) updatePayload.radius_meters = data.radius_meters;
if (data.min_trust_score_to_post !== undefined) updatePayload.min_trust_score_to_post = data.min_trust_score_to_post;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
updatePayload.updatedById = currentUser.id;
await forum_spaces.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await forum_spaces.setOwner(
data.owner,
{ transaction }
);
}
if (data.organizations !== undefined) {
await forum_spaces.setOrganizations(
data.organizations,
{ transaction }
);
}
return forum_spaces;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const forum_spaces = await db.forum_spaces.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of forum_spaces) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of forum_spaces) {
await record.destroy({transaction});
}
});
return forum_spaces;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const forum_spaces = await db.forum_spaces.findByPk(id, options);
await forum_spaces.update({
deletedBy: currentUser.id
}, {
transaction,
});
await forum_spaces.destroy({
transaction
});
return forum_spaces;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const forum_spaces = await db.forum_spaces.findOne(
{ where },
{ transaction },
);
if (!forum_spaces) {
return forum_spaces;
}
const output = forum_spaces.get({plain: true});
output.forum_threads_space = await forum_spaces.getForum_threads_space({
transaction
});
output.owner = await forum_spaces.getOwner({
transaction
});
output.organizations = await forum_spaces.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.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.space_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'forum_spaces',
'space_name',
filter.space_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'forum_spaces',
'description',
filter.description,
),
};
}
if (filter.center_latitudeRange) {
const [start, end] = filter.center_latitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
center_latitude: {
...where.center_latitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
center_latitude: {
...where.center_latitude,
[Op.lte]: end,
},
};
}
}
if (filter.center_longitudeRange) {
const [start, end] = filter.center_longitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
center_longitude: {
...where.center_longitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
center_longitude: {
...where.center_longitude,
[Op.lte]: end,
},
};
}
}
if (filter.radius_metersRange) {
const [start, end] = filter.radius_metersRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
radius_meters: {
...where.radius_meters,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
radius_meters: {
...where.radius_meters,
[Op.lte]: end,
},
};
}
}
if (filter.min_trust_score_to_postRange) {
const [start, end] = filter.min_trust_score_to_postRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_trust_score_to_post: {
...where.min_trust_score_to_post,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_trust_score_to_post: {
...where.min_trust_score_to_post,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
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.forum_spaces.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(
'forum_spaces',
'space_name',
query,
),
],
};
}
const records = await db.forum_spaces.findAll({
attributes: [ 'id', 'space_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['space_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.space_name,
}));
}
};

View File

@ -0,0 +1,654 @@
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 Forum_threadsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const forum_threads = await db.forum_threads.create(
{
id: data.id || undefined,
thread_title: data.thread_title
||
null
,
thread_body: data.thread_body
||
null
,
status: data.status
||
null
,
created_on: data.created_on
||
null
,
last_activity_at: data.last_activity_at
||
null
,
upvotes_count: data.upvotes_count
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await forum_threads.setSpace( data.space || null, {
transaction,
});
await forum_threads.setAuthor( data.author || null, {
transaction,
});
await forum_threads.setOrganizations( data.organizations || null, {
transaction,
});
return forum_threads;
}
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 forum_threadsData = data.map((item, index) => ({
id: item.id || undefined,
thread_title: item.thread_title
||
null
,
thread_body: item.thread_body
||
null
,
status: item.status
||
null
,
created_on: item.created_on
||
null
,
last_activity_at: item.last_activity_at
||
null
,
upvotes_count: item.upvotes_count
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const forum_threads = await db.forum_threads.bulkCreate(forum_threadsData, { transaction });
// For each item created, replace relation files
return forum_threads;
}
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 forum_threads = await db.forum_threads.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.thread_title !== undefined) updatePayload.thread_title = data.thread_title;
if (data.thread_body !== undefined) updatePayload.thread_body = data.thread_body;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
if (data.last_activity_at !== undefined) updatePayload.last_activity_at = data.last_activity_at;
if (data.upvotes_count !== undefined) updatePayload.upvotes_count = data.upvotes_count;
updatePayload.updatedById = currentUser.id;
await forum_threads.update(updatePayload, {transaction});
if (data.space !== undefined) {
await forum_threads.setSpace(
data.space,
{ transaction }
);
}
if (data.author !== undefined) {
await forum_threads.setAuthor(
data.author,
{ transaction }
);
}
if (data.organizations !== undefined) {
await forum_threads.setOrganizations(
data.organizations,
{ transaction }
);
}
return forum_threads;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const forum_threads = await db.forum_threads.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of forum_threads) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of forum_threads) {
await record.destroy({transaction});
}
});
return forum_threads;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const forum_threads = await db.forum_threads.findByPk(id, options);
await forum_threads.update({
deletedBy: currentUser.id
}, {
transaction,
});
await forum_threads.destroy({
transaction
});
return forum_threads;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const forum_threads = await db.forum_threads.findOne(
{ where },
{ transaction },
);
if (!forum_threads) {
return forum_threads;
}
const output = forum_threads.get({plain: true});
output.forum_posts_thread = await forum_threads.getForum_posts_thread({
transaction
});
output.space = await forum_threads.getSpace({
transaction
});
output.author = await forum_threads.getAuthor({
transaction
});
output.organizations = await forum_threads.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.forum_spaces,
as: 'space',
where: filter.space ? {
[Op.or]: [
{ id: { [Op.in]: filter.space.split('|').map(term => Utils.uuid(term)) } },
{
space_name: {
[Op.or]: filter.space.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'author',
where: filter.author ? {
[Op.or]: [
{ id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.thread_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'forum_threads',
'thread_title',
filter.thread_title,
),
};
}
if (filter.thread_body) {
where = {
...where,
[Op.and]: Utils.ilike(
'forum_threads',
'thread_body',
filter.thread_body,
),
};
}
if (filter.created_onRange) {
const [start, end] = filter.created_onRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_on: {
...where.created_on,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_on: {
...where.created_on,
[Op.lte]: end,
},
};
}
}
if (filter.last_activity_atRange) {
const [start, end] = filter.last_activity_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_activity_at: {
...where.last_activity_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_activity_at: {
...where.last_activity_at,
[Op.lte]: end,
},
};
}
}
if (filter.upvotes_countRange) {
const [start, end] = filter.upvotes_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
upvotes_count: {
...where.upvotes_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
upvotes_count: {
...where.upvotes_count,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.forum_threads.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(
'forum_threads',
'thread_title',
query,
),
],
};
}
const records = await db.forum_threads.findAll({
attributes: [ 'id', 'thread_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['thread_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.thread_title,
}));
}
};

View File

@ -0,0 +1,596 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Geo_rulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const geo_rules = await db.geo_rules.create(
{
id: data.id || undefined,
rule_name: data.rule_name
||
null
,
rule_type: data.rule_type
||
null
,
center_latitude: data.center_latitude
||
null
,
center_longitude: data.center_longitude
||
null
,
radius_meters: data.radius_meters
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await geo_rules.setOrganizations( data.organizations || null, {
transaction,
});
return geo_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 geo_rulesData = data.map((item, index) => ({
id: item.id || undefined,
rule_name: item.rule_name
||
null
,
rule_type: item.rule_type
||
null
,
center_latitude: item.center_latitude
||
null
,
center_longitude: item.center_longitude
||
null
,
radius_meters: item.radius_meters
||
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 geo_rules = await db.geo_rules.bulkCreate(geo_rulesData, { transaction });
// For each item created, replace relation files
return geo_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 geo_rules = await db.geo_rules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.rule_name !== undefined) updatePayload.rule_name = data.rule_name;
if (data.rule_type !== undefined) updatePayload.rule_type = data.rule_type;
if (data.center_latitude !== undefined) updatePayload.center_latitude = data.center_latitude;
if (data.center_longitude !== undefined) updatePayload.center_longitude = data.center_longitude;
if (data.radius_meters !== undefined) updatePayload.radius_meters = data.radius_meters;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await geo_rules.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await geo_rules.setOrganizations(
data.organizations,
{ transaction }
);
}
return geo_rules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const geo_rules = await db.geo_rules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of geo_rules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of geo_rules) {
await record.destroy({transaction});
}
});
return geo_rules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const geo_rules = await db.geo_rules.findByPk(id, options);
await geo_rules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await geo_rules.destroy({
transaction
});
return geo_rules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const geo_rules = await db.geo_rules.findOne(
{ where },
{ transaction },
);
if (!geo_rules) {
return geo_rules;
}
const output = geo_rules.get({plain: true});
output.organizations = await geo_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.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(
'geo_rules',
'rule_name',
filter.rule_name,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'geo_rules',
'notes',
filter.notes,
),
};
}
if (filter.center_latitudeRange) {
const [start, end] = filter.center_latitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
center_latitude: {
...where.center_latitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
center_latitude: {
...where.center_latitude,
[Op.lte]: end,
},
};
}
}
if (filter.center_longitudeRange) {
const [start, end] = filter.center_longitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
center_longitude: {
...where.center_longitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
center_longitude: {
...where.center_longitude,
[Op.lte]: end,
},
};
}
}
if (filter.radius_metersRange) {
const [start, end] = filter.radius_metersRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
radius_meters: {
...where.radius_meters,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
radius_meters: {
...where.radius_meters,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.rule_type) {
where = {
...where,
rule_type: filter.rule_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.geo_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(
'geo_rules',
'rule_name',
query,
),
],
};
}
const records = await db.geo_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,772 @@
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 Identity_verificationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const identity_verifications = await db.identity_verifications.create(
{
id: data.id || undefined,
verification_type: data.verification_type
||
null
,
status: data.status
||
null
,
submitted_at: data.submitted_at
||
null
,
reviewed_at: data.reviewed_at
||
null
,
expires_at: data.expires_at
||
null
,
document_number: data.document_number
||
null
,
match_confidence: data.match_confidence
||
null
,
review_notes: data.review_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await identity_verifications.setUser( data.user || null, {
transaction,
});
await identity_verifications.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.identity_verifications.getTableName(),
belongsToColumn: 'document_files',
belongsToId: identity_verifications.id,
},
data.document_files,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.identity_verifications.getTableName(),
belongsToColumn: 'selfie_images',
belongsToId: identity_verifications.id,
},
data.selfie_images,
options,
);
return identity_verifications;
}
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 identity_verificationsData = data.map((item, index) => ({
id: item.id || undefined,
verification_type: item.verification_type
||
null
,
status: item.status
||
null
,
submitted_at: item.submitted_at
||
null
,
reviewed_at: item.reviewed_at
||
null
,
expires_at: item.expires_at
||
null
,
document_number: item.document_number
||
null
,
match_confidence: item.match_confidence
||
null
,
review_notes: item.review_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const identity_verifications = await db.identity_verifications.bulkCreate(identity_verificationsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < identity_verifications.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.identity_verifications.getTableName(),
belongsToColumn: 'document_files',
belongsToId: identity_verifications[i].id,
},
data[i].document_files,
options,
);
}
for (let i = 0; i < identity_verifications.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.identity_verifications.getTableName(),
belongsToColumn: 'selfie_images',
belongsToId: identity_verifications[i].id,
},
data[i].selfie_images,
options,
);
}
return identity_verifications;
}
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 identity_verifications = await db.identity_verifications.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.verification_type !== undefined) updatePayload.verification_type = data.verification_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
if (data.match_confidence !== undefined) updatePayload.match_confidence = data.match_confidence;
if (data.review_notes !== undefined) updatePayload.review_notes = data.review_notes;
updatePayload.updatedById = currentUser.id;
await identity_verifications.update(updatePayload, {transaction});
if (data.user !== undefined) {
await identity_verifications.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await identity_verifications.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.identity_verifications.getTableName(),
belongsToColumn: 'document_files',
belongsToId: identity_verifications.id,
},
data.document_files,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.identity_verifications.getTableName(),
belongsToColumn: 'selfie_images',
belongsToId: identity_verifications.id,
},
data.selfie_images,
options,
);
return identity_verifications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const identity_verifications = await db.identity_verifications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of identity_verifications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of identity_verifications) {
await record.destroy({transaction});
}
});
return identity_verifications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const identity_verifications = await db.identity_verifications.findByPk(id, options);
await identity_verifications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await identity_verifications.destroy({
transaction
});
return identity_verifications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const identity_verifications = await db.identity_verifications.findOne(
{ where },
{ transaction },
);
if (!identity_verifications) {
return identity_verifications;
}
const output = identity_verifications.get({plain: true});
output.user = await identity_verifications.getUser({
transaction
});
output.document_files = await identity_verifications.getDocument_files({
transaction
});
output.selfie_images = await identity_verifications.getSelfie_images({
transaction
});
output.organizations = await identity_verifications.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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'document_files',
},
{
model: db.file,
as: 'selfie_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.document_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'identity_verifications',
'document_number',
filter.document_number,
),
};
}
if (filter.review_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'identity_verifications',
'review_notes',
filter.review_notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
submitted_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
expires_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.submitted_atRange) {
const [start, end] = filter.submitted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.lte]: end,
},
};
}
}
if (filter.reviewed_atRange) {
const [start, end] = filter.reviewed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reviewed_at: {
...where.reviewed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reviewed_at: {
...where.reviewed_at,
[Op.lte]: end,
},
};
}
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.match_confidenceRange) {
const [start, end] = filter.match_confidenceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
match_confidence: {
...where.match_confidence,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
match_confidence: {
...where.match_confidence,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.verification_type) {
where = {
...where,
verification_type: filter.verification_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.identity_verifications.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(
'identity_verifications',
'document_number',
query,
),
],
};
}
const records = await db.identity_verifications.findAll({
attributes: [ 'id', 'document_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['document_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.document_number,
}));
}
};

View File

@ -0,0 +1,631 @@
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 Job_applicationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_applications = await db.job_applications.create(
{
id: data.id || undefined,
status: data.status
||
null
,
cover_letter: data.cover_letter
||
null
,
applied_at: data.applied_at
||
null
,
last_updated_at: data.last_updated_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await job_applications.setJob_listing( data.job_listing || null, {
transaction,
});
await job_applications.setApplicant( data.applicant || null, {
transaction,
});
await job_applications.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_applications.getTableName(),
belongsToColumn: 'resume_files',
belongsToId: job_applications.id,
},
data.resume_files,
options,
);
return job_applications;
}
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 job_applicationsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
cover_letter: item.cover_letter
||
null
,
applied_at: item.applied_at
||
null
,
last_updated_at: item.last_updated_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const job_applications = await db.job_applications.bulkCreate(job_applicationsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < job_applications.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_applications.getTableName(),
belongsToColumn: 'resume_files',
belongsToId: job_applications[i].id,
},
data[i].resume_files,
options,
);
}
return job_applications;
}
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 job_applications = await db.job_applications.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.cover_letter !== undefined) updatePayload.cover_letter = data.cover_letter;
if (data.applied_at !== undefined) updatePayload.applied_at = data.applied_at;
if (data.last_updated_at !== undefined) updatePayload.last_updated_at = data.last_updated_at;
updatePayload.updatedById = currentUser.id;
await job_applications.update(updatePayload, {transaction});
if (data.job_listing !== undefined) {
await job_applications.setJob_listing(
data.job_listing,
{ transaction }
);
}
if (data.applicant !== undefined) {
await job_applications.setApplicant(
data.applicant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await job_applications.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_applications.getTableName(),
belongsToColumn: 'resume_files',
belongsToId: job_applications.id,
},
data.resume_files,
options,
);
return job_applications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_applications = await db.job_applications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of job_applications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of job_applications) {
await record.destroy({transaction});
}
});
return job_applications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const job_applications = await db.job_applications.findByPk(id, options);
await job_applications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await job_applications.destroy({
transaction
});
return job_applications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const job_applications = await db.job_applications.findOne(
{ where },
{ transaction },
);
if (!job_applications) {
return job_applications;
}
const output = job_applications.get({plain: true});
output.job_listing = await job_applications.getJob_listing({
transaction
});
output.applicant = await job_applications.getApplicant({
transaction
});
output.resume_files = await job_applications.getResume_files({
transaction
});
output.organizations = await job_applications.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.job_listings,
as: 'job_listing',
where: filter.job_listing ? {
[Op.or]: [
{ id: { [Op.in]: filter.job_listing.split('|').map(term => Utils.uuid(term)) } },
{
job_title: {
[Op.or]: filter.job_listing.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'applicant',
where: filter.applicant ? {
[Op.or]: [
{ id: { [Op.in]: filter.applicant.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.applicant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'resume_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.cover_letter) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_applications',
'cover_letter',
filter.cover_letter,
),
};
}
if (filter.applied_atRange) {
const [start, end] = filter.applied_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
applied_at: {
...where.applied_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
applied_at: {
...where.applied_at,
[Op.lte]: end,
},
};
}
}
if (filter.last_updated_atRange) {
const [start, end] = filter.last_updated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_updated_at: {
...where.last_updated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_updated_at: {
...where.last_updated_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.job_applications.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(
'job_applications',
'cover_letter',
query,
),
],
};
}
const records = await db.job_applications.findAll({
attributes: [ 'id', 'cover_letter' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['cover_letter', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.cover_letter,
}));
}
};

View File

@ -0,0 +1,653 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Job_companiesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_companies = await db.job_companies.create(
{
id: data.id || undefined,
company_name: data.company_name
||
null
,
company_legal_name: data.company_legal_name
||
null
,
company_website: data.company_website
||
null
,
company_size: data.company_size
||
null
,
verification_status: data.verification_status
||
null
,
about: data.about
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await job_companies.setOwner( data.owner || null, {
transaction,
});
await job_companies.setHq_address( data.hq_address || null, {
transaction,
});
await job_companies.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_companies.getTableName(),
belongsToColumn: 'company_images',
belongsToId: job_companies.id,
},
data.company_images,
options,
);
return job_companies;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const job_companiesData = data.map((item, index) => ({
id: item.id || undefined,
company_name: item.company_name
||
null
,
company_legal_name: item.company_legal_name
||
null
,
company_website: item.company_website
||
null
,
company_size: item.company_size
||
null
,
verification_status: item.verification_status
||
null
,
about: item.about
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const job_companies = await db.job_companies.bulkCreate(job_companiesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < job_companies.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_companies.getTableName(),
belongsToColumn: 'company_images',
belongsToId: job_companies[i].id,
},
data[i].company_images,
options,
);
}
return job_companies;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const job_companies = await db.job_companies.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
if (data.company_legal_name !== undefined) updatePayload.company_legal_name = data.company_legal_name;
if (data.company_website !== undefined) updatePayload.company_website = data.company_website;
if (data.company_size !== undefined) updatePayload.company_size = data.company_size;
if (data.verification_status !== undefined) updatePayload.verification_status = data.verification_status;
if (data.about !== undefined) updatePayload.about = data.about;
updatePayload.updatedById = currentUser.id;
await job_companies.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await job_companies.setOwner(
data.owner,
{ transaction }
);
}
if (data.hq_address !== undefined) {
await job_companies.setHq_address(
data.hq_address,
{ transaction }
);
}
if (data.organizations !== undefined) {
await job_companies.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_companies.getTableName(),
belongsToColumn: 'company_images',
belongsToId: job_companies.id,
},
data.company_images,
options,
);
return job_companies;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_companies = await db.job_companies.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of job_companies) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of job_companies) {
await record.destroy({transaction});
}
});
return job_companies;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const job_companies = await db.job_companies.findByPk(id, options);
await job_companies.update({
deletedBy: currentUser.id
}, {
transaction,
});
await job_companies.destroy({
transaction
});
return job_companies;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const job_companies = await db.job_companies.findOne(
{ where },
{ transaction },
);
if (!job_companies) {
return job_companies;
}
const output = job_companies.get({plain: true});
output.job_listings_company = await job_companies.getJob_listings_company({
transaction
});
output.owner = await job_companies.getOwner({
transaction
});
output.company_images = await job_companies.getCompany_images({
transaction
});
output.hq_address = await job_companies.getHq_address({
transaction
});
output.organizations = await job_companies.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.addresses,
as: 'hq_address',
where: filter.hq_address ? {
[Op.or]: [
{ id: { [Op.in]: filter.hq_address.split('|').map(term => Utils.uuid(term)) } },
{
label: {
[Op.or]: filter.hq_address.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'company_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.company_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_companies',
'company_name',
filter.company_name,
),
};
}
if (filter.company_legal_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_companies',
'company_legal_name',
filter.company_legal_name,
),
};
}
if (filter.company_website) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_companies',
'company_website',
filter.company_website,
),
};
}
if (filter.about) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_companies',
'about',
filter.about,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.company_size) {
where = {
...where,
company_size: filter.company_size,
};
}
if (filter.verification_status) {
where = {
...where,
verification_status: filter.verification_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.job_companies.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'job_companies',
'company_name',
query,
),
],
};
}
const records = await db.job_companies.findAll({
attributes: [ 'id', 'company_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['company_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.company_name,
}));
}
};

View File

@ -0,0 +1,718 @@
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 Job_listingsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_listings = await db.job_listings.create(
{
id: data.id || undefined,
job_title: data.job_title
||
null
,
employment_type: data.employment_type
||
null
,
work_mode: data.work_mode
||
null
,
location_text: data.location_text
||
null
,
salary_min: data.salary_min
||
null
,
salary_max: data.salary_max
||
null
,
description: data.description
||
null
,
status: data.status
||
null
,
posted_at: data.posted_at
||
null
,
closes_at: data.closes_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await job_listings.setCompany( data.company || null, {
transaction,
});
await job_listings.setOrganizations( data.organizations || null, {
transaction,
});
return job_listings;
}
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 job_listingsData = data.map((item, index) => ({
id: item.id || undefined,
job_title: item.job_title
||
null
,
employment_type: item.employment_type
||
null
,
work_mode: item.work_mode
||
null
,
location_text: item.location_text
||
null
,
salary_min: item.salary_min
||
null
,
salary_max: item.salary_max
||
null
,
description: item.description
||
null
,
status: item.status
||
null
,
posted_at: item.posted_at
||
null
,
closes_at: item.closes_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const job_listings = await db.job_listings.bulkCreate(job_listingsData, { transaction });
// For each item created, replace relation files
return job_listings;
}
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 job_listings = await db.job_listings.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.job_title !== undefined) updatePayload.job_title = data.job_title;
if (data.employment_type !== undefined) updatePayload.employment_type = data.employment_type;
if (data.work_mode !== undefined) updatePayload.work_mode = data.work_mode;
if (data.location_text !== undefined) updatePayload.location_text = data.location_text;
if (data.salary_min !== undefined) updatePayload.salary_min = data.salary_min;
if (data.salary_max !== undefined) updatePayload.salary_max = data.salary_max;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
if (data.closes_at !== undefined) updatePayload.closes_at = data.closes_at;
updatePayload.updatedById = currentUser.id;
await job_listings.update(updatePayload, {transaction});
if (data.company !== undefined) {
await job_listings.setCompany(
data.company,
{ transaction }
);
}
if (data.organizations !== undefined) {
await job_listings.setOrganizations(
data.organizations,
{ transaction }
);
}
return job_listings;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_listings = await db.job_listings.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of job_listings) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of job_listings) {
await record.destroy({transaction});
}
});
return job_listings;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const job_listings = await db.job_listings.findByPk(id, options);
await job_listings.update({
deletedBy: currentUser.id
}, {
transaction,
});
await job_listings.destroy({
transaction
});
return job_listings;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const job_listings = await db.job_listings.findOne(
{ where },
{ transaction },
);
if (!job_listings) {
return job_listings;
}
const output = job_listings.get({plain: true});
output.job_applications_job_listing = await job_listings.getJob_applications_job_listing({
transaction
});
output.company = await job_listings.getCompany({
transaction
});
output.organizations = await job_listings.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.job_companies,
as: 'company',
where: filter.company ? {
[Op.or]: [
{ id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
{
company_name: {
[Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.job_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_listings',
'job_title',
filter.job_title,
),
};
}
if (filter.location_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_listings',
'location_text',
filter.location_text,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_listings',
'description',
filter.description,
),
};
}
if (filter.salary_minRange) {
const [start, end] = filter.salary_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
salary_min: {
...where.salary_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
salary_min: {
...where.salary_min,
[Op.lte]: end,
},
};
}
}
if (filter.salary_maxRange) {
const [start, end] = filter.salary_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
salary_max: {
...where.salary_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
salary_max: {
...where.salary_max,
[Op.lte]: end,
},
};
}
}
if (filter.posted_atRange) {
const [start, end] = filter.posted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.lte]: end,
},
};
}
}
if (filter.closes_atRange) {
const [start, end] = filter.closes_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
closes_at: {
...where.closes_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
closes_at: {
...where.closes_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.employment_type) {
where = {
...where,
employment_type: filter.employment_type,
};
}
if (filter.work_mode) {
where = {
...where,
work_mode: filter.work_mode,
};
}
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.job_listings.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(
'job_listings',
'job_title',
query,
),
],
};
}
const records = await db.job_listings.findAll({
attributes: [ 'id', 'job_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['job_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.job_title,
}));
}
};

View File

@ -0,0 +1,697 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class MessagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.create(
{
id: data.id || undefined,
message_type: data.message_type
||
null
,
text_body: data.text_body
||
null
,
link_url: data.link_url
||
null
,
sent_at: data.sent_at
||
null
,
read_at: data.read_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await messages.setChat( data.chat || null, {
transaction,
});
await messages.setSender( data.sender || null, {
transaction,
});
await messages.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.messages.getTableName(),
belongsToColumn: 'image_attachments',
belongsToId: messages.id,
},
data.image_attachments,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.messages.getTableName(),
belongsToColumn: 'file_attachments',
belongsToId: messages.id,
},
data.file_attachments,
options,
);
return messages;
}
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 messagesData = data.map((item, index) => ({
id: item.id || undefined,
message_type: item.message_type
||
null
,
text_body: item.text_body
||
null
,
link_url: item.link_url
||
null
,
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 messages = await db.messages.bulkCreate(messagesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < messages.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.messages.getTableName(),
belongsToColumn: 'image_attachments',
belongsToId: messages[i].id,
},
data[i].image_attachments,
options,
);
}
for (let i = 0; i < messages.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.messages.getTableName(),
belongsToColumn: 'file_attachments',
belongsToId: messages[i].id,
},
data[i].file_attachments,
options,
);
}
return messages;
}
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 messages = await db.messages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.message_type !== undefined) updatePayload.message_type = data.message_type;
if (data.text_body !== undefined) updatePayload.text_body = data.text_body;
if (data.link_url !== undefined) updatePayload.link_url = data.link_url;
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 messages.update(updatePayload, {transaction});
if (data.chat !== undefined) {
await messages.setChat(
data.chat,
{ transaction }
);
}
if (data.sender !== undefined) {
await messages.setSender(
data.sender,
{ transaction }
);
}
if (data.organizations !== undefined) {
await messages.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.messages.getTableName(),
belongsToColumn: 'image_attachments',
belongsToId: messages.id,
},
data.image_attachments,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.messages.getTableName(),
belongsToColumn: 'file_attachments',
belongsToId: messages.id,
},
data.file_attachments,
options,
);
return messages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of messages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of messages) {
await record.destroy({transaction});
}
});
return messages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findByPk(id, options);
await messages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await messages.destroy({
transaction
});
return messages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findOne(
{ where },
{ transaction },
);
if (!messages) {
return messages;
}
const output = messages.get({plain: true});
output.chat = await messages.getChat({
transaction
});
output.sender = await messages.getSender({
transaction
});
output.image_attachments = await messages.getImage_attachments({
transaction
});
output.file_attachments = await messages.getFile_attachments({
transaction
});
output.organizations = await messages.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.chats,
as: 'chat',
where: filter.chat ? {
[Op.or]: [
{ id: { [Op.in]: filter.chat.split('|').map(term => Utils.uuid(term)) } },
{
chat_title: {
[Op.or]: filter.chat.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'sender',
where: filter.sender ? {
[Op.or]: [
{ id: { [Op.in]: filter.sender.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.sender.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'image_attachments',
},
{
model: db.file,
as: 'file_attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.text_body) {
where = {
...where,
[Op.and]: Utils.ilike(
'messages',
'text_body',
filter.text_body,
),
};
}
if (filter.link_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'messages',
'link_url',
filter.link_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.message_type) {
where = {
...where,
message_type: filter.message_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.messages.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(
'messages',
'text_body',
query,
),
],
};
}
const records = await db.messages.findAll({
attributes: [ 'id', 'text_body' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['text_body', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.text_body,
}));
}
};

View File

@ -0,0 +1,606 @@
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,
quantity: data.quantity
||
null
,
unit_price: data.unit_price
||
null
,
line_total: data.line_total
||
null
,
variant_label: data.variant_label
||
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,
quantity: item.quantity
||
null
,
unit_price: item.unit_price
||
null
,
line_total: item.line_total
||
null
,
variant_label: item.variant_label
||
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.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.unit_price !== undefined) updatePayload.unit_price = data.unit_price;
if (data.line_total !== undefined) updatePayload.line_total = data.line_total;
if (data.variant_label !== undefined) updatePayload.variant_label = data.variant_label;
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.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.variant_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'order_items',
'variant_label',
filter.variant_label,
),
};
}
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_priceRange) {
const [start, end] = filter.unit_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unit_price: {
...where.unit_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unit_price: {
...where.unit_price,
[Op.lte]: end,
},
};
}
}
if (filter.line_totalRange) {
const [start, end] = filter.line_totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
line_total: {
...where.line_total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
line_total: {
...where.line_total,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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',
'variant_label',
query,
),
],
};
}
const records = await db.order_items.findAll({
attributes: [ 'id', 'variant_label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['variant_label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.variant_label,
}));
}
};

View File

@ -0,0 +1,781 @@
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 OrdersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const orders = await db.orders.create(
{
id: data.id || undefined,
order_number: data.order_number
||
null
,
order_status: data.order_status
||
null
,
subtotal_amount: data.subtotal_amount
||
null
,
shipping_amount: data.shipping_amount
||
null
,
total_amount: data.total_amount
||
null
,
placed_at: data.placed_at
||
null
,
paid_at: data.paid_at
||
null
,
buyer_note: data.buyer_note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await orders.setBuyer( data.buyer || null, {
transaction,
});
await orders.setStore( data.store || null, {
transaction,
});
await orders.setShipping_address( data.shipping_address || null, {
transaction,
});
await orders.setOrganizations( data.organizations || null, {
transaction,
});
return orders;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const ordersData = data.map((item, index) => ({
id: item.id || undefined,
order_number: item.order_number
||
null
,
order_status: item.order_status
||
null
,
subtotal_amount: item.subtotal_amount
||
null
,
shipping_amount: item.shipping_amount
||
null
,
total_amount: item.total_amount
||
null
,
placed_at: item.placed_at
||
null
,
paid_at: item.paid_at
||
null
,
buyer_note: item.buyer_note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const orders = await db.orders.bulkCreate(ordersData, { transaction });
// For each item created, replace relation files
return orders;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const orders = await db.orders.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.order_number !== undefined) updatePayload.order_number = data.order_number;
if (data.order_status !== undefined) updatePayload.order_status = data.order_status;
if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
if (data.shipping_amount !== undefined) updatePayload.shipping_amount = data.shipping_amount;
if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
if (data.placed_at !== undefined) updatePayload.placed_at = data.placed_at;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.buyer_note !== undefined) updatePayload.buyer_note = data.buyer_note;
updatePayload.updatedById = currentUser.id;
await orders.update(updatePayload, {transaction});
if (data.buyer !== undefined) {
await orders.setBuyer(
data.buyer,
{ transaction }
);
}
if (data.store !== undefined) {
await orders.setStore(
data.store,
{ transaction }
);
}
if (data.shipping_address !== undefined) {
await orders.setShipping_address(
data.shipping_address,
{ transaction }
);
}
if (data.organizations !== undefined) {
await orders.setOrganizations(
data.organizations,
{ transaction }
);
}
return orders;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const orders = await db.orders.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of orders) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of orders) {
await record.destroy({transaction});
}
});
return orders;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const orders = await db.orders.findByPk(id, options);
await orders.update({
deletedBy: currentUser.id
}, {
transaction,
});
await orders.destroy({
transaction
});
return orders;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const orders = await db.orders.findOne(
{ where },
{ transaction },
);
if (!orders) {
return orders;
}
const output = orders.get({plain: true});
output.order_items_order = await orders.getOrder_items_order({
transaction
});
output.payments_order = await orders.getPayments_order({
transaction
});
output.product_reviews_order = await orders.getProduct_reviews_order({
transaction
});
output.shipments_order = await orders.getShipments_order({
transaction
});
output.commissions_order = await orders.getCommissions_order({
transaction
});
output.buyer = await orders.getBuyer({
transaction
});
output.store = await orders.getStore({
transaction
});
output.shipping_address = await orders.getShipping_address({
transaction
});
output.organizations = await orders.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'buyer',
where: filter.buyer ? {
[Op.or]: [
{ id: { [Op.in]: filter.buyer.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.buyer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.stores,
as: 'store',
where: filter.store ? {
[Op.or]: [
{ id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
{
store_name: {
[Op.or]: filter.store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.addresses,
as: 'shipping_address',
where: filter.shipping_address ? {
[Op.or]: [
{ id: { [Op.in]: filter.shipping_address.split('|').map(term => Utils.uuid(term)) } },
{
label: {
[Op.or]: filter.shipping_address.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.order_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'orders',
'order_number',
filter.order_number,
),
};
}
if (filter.buyer_note) {
where = {
...where,
[Op.and]: Utils.ilike(
'orders',
'buyer_note',
filter.buyer_note,
),
};
}
if (filter.subtotal_amountRange) {
const [start, end] = filter.subtotal_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
subtotal_amount: {
...where.subtotal_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
subtotal_amount: {
...where.subtotal_amount,
[Op.lte]: end,
},
};
}
}
if (filter.shipping_amountRange) {
const [start, end] = filter.shipping_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
shipping_amount: {
...where.shipping_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
shipping_amount: {
...where.shipping_amount,
[Op.lte]: end,
},
};
}
}
if (filter.total_amountRange) {
const [start, end] = filter.total_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_amount: {
...where.total_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_amount: {
...where.total_amount,
[Op.lte]: end,
},
};
}
}
if (filter.placed_atRange) {
const [start, end] = filter.placed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
placed_at: {
...where.placed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
placed_at: {
...where.placed_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.order_status) {
where = {
...where,
order_status: filter.order_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.orders.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'orders',
'order_number',
query,
),
],
};
}
const records = await db.orders.findAll({
attributes: [ 'id', 'order_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['order_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.order_number,
}));
}
};

View File

@ -0,0 +1,536 @@
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.trust_profiles_organizations = await organizations.getTrust_profiles_organizations({
transaction
});
output.identity_verifications_organizations = await organizations.getIdentity_verifications_organizations({
transaction
});
output.wallets_organizations = await organizations.getWallets_organizations({
transaction
});
output.wallet_transactions_organizations = await organizations.getWallet_transactions_organizations({
transaction
});
output.chats_organizations = await organizations.getChats_organizations({
transaction
});
output.chat_participants_organizations = await organizations.getChat_participants_organizations({
transaction
});
output.messages_organizations = await organizations.getMessages_organizations({
transaction
});
output.stores_organizations = await organizations.getStores_organizations({
transaction
});
output.addresses_organizations = await organizations.getAddresses_organizations({
transaction
});
output.product_categories_organizations = await organizations.getProduct_categories_organizations({
transaction
});
output.products_organizations = await organizations.getProducts_organizations({
transaction
});
output.orders_organizations = await organizations.getOrders_organizations({
transaction
});
output.order_items_organizations = await organizations.getOrder_items_organizations({
transaction
});
output.payments_organizations = await organizations.getPayments_organizations({
transaction
});
output.product_reviews_organizations = await organizations.getProduct_reviews_organizations({
transaction
});
output.shipments_organizations = await organizations.getShipments_organizations({
transaction
});
output.posts_organizations = await organizations.getPosts_organizations({
transaction
});
output.deep_dive_links_organizations = await organizations.getDeep_dive_links_organizations({
transaction
});
output.citations_organizations = await organizations.getCitations_organizations({
transaction
});
output.post_engagements_organizations = await organizations.getPost_engagements_organizations({
transaction
});
output.rewards_organizations = await organizations.getRewards_organizations({
transaction
});
output.forum_spaces_organizations = await organizations.getForum_spaces_organizations({
transaction
});
output.forum_threads_organizations = await organizations.getForum_threads_organizations({
transaction
});
output.forum_posts_organizations = await organizations.getForum_posts_organizations({
transaction
});
output.job_companies_organizations = await organizations.getJob_companies_organizations({
transaction
});
output.job_listings_organizations = await organizations.getJob_listings_organizations({
transaction
});
output.job_applications_organizations = await organizations.getJob_applications_organizations({
transaction
});
output.user_credentials_organizations = await organizations.getUser_credentials_organizations({
transaction
});
output.affiliate_programs_organizations = await organizations.getAffiliate_programs_organizations({
transaction
});
output.affiliate_memberships_organizations = await organizations.getAffiliate_memberships_organizations({
transaction
});
output.commissions_organizations = await organizations.getCommissions_organizations({
transaction
});
output.geo_rules_organizations = await organizations.getGeo_rules_organizations({
transaction
});
output.facta_queries_organizations = await organizations.getFacta_queries_organizations({
transaction
});
output.facta_answers_organizations = await organizations.getFacta_answers_organizations({
transaction
});
output.subscriptions_organizations = await organizations.getSubscriptions_organizations({
transaction
});
output.api_clients_organizations = await organizations.getApi_clients_organizations({
transaction
});
output.audit_events_organizations = await organizations.getAudit_events_organizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'organizations',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.organizations.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'organizations',
'name',
query,
),
],
};
}
const records = await db.organizations.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,683 @@
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
,
method: data.method
||
null
,
status: data.status
||
null
,
amount: data.amount
||
null
,
initiated_at: data.initiated_at
||
null
,
captured_at: data.captured_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payments.setOrder( data.order || null, {
transaction,
});
await payments.setPayer( data.payer || null, {
transaction,
});
await payments.setWallet_transaction( data.wallet_transaction || null, {
transaction,
});
await payments.setOrganizations( data.organizations || null, {
transaction,
});
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
,
method: item.method
||
null
,
status: item.status
||
null
,
amount: item.amount
||
null
,
initiated_at: item.initiated_at
||
null
,
captured_at: item.captured_at
||
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
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.method !== undefined) updatePayload.method = data.method;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.initiated_at !== undefined) updatePayload.initiated_at = data.initiated_at;
if (data.captured_at !== undefined) updatePayload.captured_at = data.captured_at;
updatePayload.updatedById = currentUser.id;
await payments.update(updatePayload, {transaction});
if (data.order !== undefined) {
await payments.setOrder(
data.order,
{ transaction }
);
}
if (data.payer !== undefined) {
await payments.setPayer(
data.payer,
{ transaction }
);
}
if (data.wallet_transaction !== undefined) {
await payments.setWallet_transaction(
data.wallet_transaction,
{ transaction }
);
}
if (data.organizations !== undefined) {
await payments.setOrganizations(
data.organizations,
{ transaction }
);
}
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.order = await payments.getOrder({
transaction
});
output.payer = await payments.getPayer({
transaction
});
output.wallet_transaction = await payments.getWallet_transaction({
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.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.users,
as: 'payer',
where: filter.payer ? {
[Op.or]: [
{ id: { [Op.in]: filter.payer.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.payer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.wallet_transactions,
as: 'wallet_transaction',
where: filter.wallet_transaction ? {
[Op.or]: [
{ id: { [Op.in]: filter.wallet_transaction.split('|').map(term => Utils.uuid(term)) } },
{
reference_code: {
[Op.or]: filter.wallet_transaction.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.payment_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'payment_reference',
filter.payment_reference,
),
};
}
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.initiated_atRange) {
const [start, end] = filter.initiated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
initiated_at: {
...where.initiated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
initiated_at: {
...where.initiated_at,
[Op.lte]: end,
},
};
}
}
if (filter.captured_atRange) {
const [start, end] = filter.captured_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
captured_at: {
...where.captured_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
captured_at: {
...where.captured_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.method) {
where = {
...where,
method: filter.method,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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,370 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PermissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return permissions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const permissionsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const permissions = await db.permissions.bulkCreate(permissionsData, { transaction });
// For each item created, replace relation files
return permissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const permissions = await db.permissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await permissions.update(updatePayload, {transaction});
return permissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of permissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of permissions) {
await record.destroy({transaction});
}
});
return permissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findByPk(id, options);
await permissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await permissions.destroy({
transaction
});
return permissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findOne(
{ where },
{ transaction },
);
if (!permissions) {
return permissions;
}
const output = permissions.get({plain: true});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'permissions',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.permissions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'permissions',
'name',
query,
),
],
};
}
const records = await db.permissions.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,574 @@
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 Post_engagementsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const post_engagements = await db.post_engagements.create(
{
id: data.id || undefined,
engagement_type: data.engagement_type
||
null
,
comment_text: data.comment_text
||
null
,
engaged_at: data.engaged_at
||
null
,
is_reward_eligible: data.is_reward_eligible
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await post_engagements.setPost( data.post || null, {
transaction,
});
await post_engagements.setUser( data.user || null, {
transaction,
});
await post_engagements.setOrganizations( data.organizations || null, {
transaction,
});
return post_engagements;
}
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 post_engagementsData = data.map((item, index) => ({
id: item.id || undefined,
engagement_type: item.engagement_type
||
null
,
comment_text: item.comment_text
||
null
,
engaged_at: item.engaged_at
||
null
,
is_reward_eligible: item.is_reward_eligible
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const post_engagements = await db.post_engagements.bulkCreate(post_engagementsData, { transaction });
// For each item created, replace relation files
return post_engagements;
}
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 post_engagements = await db.post_engagements.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.engagement_type !== undefined) updatePayload.engagement_type = data.engagement_type;
if (data.comment_text !== undefined) updatePayload.comment_text = data.comment_text;
if (data.engaged_at !== undefined) updatePayload.engaged_at = data.engaged_at;
if (data.is_reward_eligible !== undefined) updatePayload.is_reward_eligible = data.is_reward_eligible;
updatePayload.updatedById = currentUser.id;
await post_engagements.update(updatePayload, {transaction});
if (data.post !== undefined) {
await post_engagements.setPost(
data.post,
{ transaction }
);
}
if (data.user !== undefined) {
await post_engagements.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await post_engagements.setOrganizations(
data.organizations,
{ transaction }
);
}
return post_engagements;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const post_engagements = await db.post_engagements.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of post_engagements) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of post_engagements) {
await record.destroy({transaction});
}
});
return post_engagements;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const post_engagements = await db.post_engagements.findByPk(id, options);
await post_engagements.update({
deletedBy: currentUser.id
}, {
transaction,
});
await post_engagements.destroy({
transaction
});
return post_engagements;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const post_engagements = await db.post_engagements.findOne(
{ where },
{ transaction },
);
if (!post_engagements) {
return post_engagements;
}
const output = post_engagements.get({plain: true});
output.post = await post_engagements.getPost({
transaction
});
output.user = await post_engagements.getUser({
transaction
});
output.organizations = await post_engagements.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.posts,
as: 'post',
where: filter.post ? {
[Op.or]: [
{ id: { [Op.in]: filter.post.split('|').map(term => Utils.uuid(term)) } },
{
caption: {
[Op.or]: filter.post.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.comment_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'post_engagements',
'comment_text',
filter.comment_text,
),
};
}
if (filter.engaged_atRange) {
const [start, end] = filter.engaged_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
engaged_at: {
...where.engaged_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
engaged_at: {
...where.engaged_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.engagement_type) {
where = {
...where,
engagement_type: filter.engagement_type,
};
}
if (filter.is_reward_eligible) {
where = {
...where,
is_reward_eligible: filter.is_reward_eligible,
};
}
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.post_engagements.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(
'post_engagements',
'comment_text',
query,
),
],
};
}
const records = await db.post_engagements.findAll({
attributes: [ 'id', 'comment_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['comment_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.comment_text,
}));
}
};

680
backend/src/db/api/posts.js Normal file
View File

@ -0,0 +1,680 @@
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 PostsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const posts = await db.posts.create(
{
id: data.id || undefined,
post_type: data.post_type
||
null
,
caption: data.caption
||
null
,
visibility: data.visibility
||
null
,
status: data.status
||
null
,
published_at: data.published_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await posts.setAuthor( data.author || null, {
transaction,
});
await posts.setDeep_dive_link( data.deep_dive_link || null, {
transaction,
});
await posts.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.posts.getTableName(),
belongsToColumn: 'media_images',
belongsToId: posts.id,
},
data.media_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.posts.getTableName(),
belongsToColumn: 'media_files',
belongsToId: posts.id,
},
data.media_files,
options,
);
return posts;
}
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 postsData = data.map((item, index) => ({
id: item.id || undefined,
post_type: item.post_type
||
null
,
caption: item.caption
||
null
,
visibility: item.visibility
||
null
,
status: item.status
||
null
,
published_at: item.published_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const posts = await db.posts.bulkCreate(postsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < posts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.posts.getTableName(),
belongsToColumn: 'media_images',
belongsToId: posts[i].id,
},
data[i].media_images,
options,
);
}
for (let i = 0; i < posts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.posts.getTableName(),
belongsToColumn: 'media_files',
belongsToId: posts[i].id,
},
data[i].media_files,
options,
);
}
return posts;
}
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 posts = await db.posts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.post_type !== undefined) updatePayload.post_type = data.post_type;
if (data.caption !== undefined) updatePayload.caption = data.caption;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
updatePayload.updatedById = currentUser.id;
await posts.update(updatePayload, {transaction});
if (data.author !== undefined) {
await posts.setAuthor(
data.author,
{ transaction }
);
}
if (data.deep_dive_link !== undefined) {
await posts.setDeep_dive_link(
data.deep_dive_link,
{ transaction }
);
}
if (data.organizations !== undefined) {
await posts.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.posts.getTableName(),
belongsToColumn: 'media_images',
belongsToId: posts.id,
},
data.media_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.posts.getTableName(),
belongsToColumn: 'media_files',
belongsToId: posts.id,
},
data.media_files,
options,
);
return posts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const posts = await db.posts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of posts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of posts) {
await record.destroy({transaction});
}
});
return posts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const posts = await db.posts.findByPk(id, options);
await posts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await posts.destroy({
transaction
});
return posts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const posts = await db.posts.findOne(
{ where },
{ transaction },
);
if (!posts) {
return posts;
}
const output = posts.get({plain: true});
output.post_engagements_post = await posts.getPost_engagements_post({
transaction
});
output.author = await posts.getAuthor({
transaction
});
output.media_images = await posts.getMedia_images({
transaction
});
output.media_files = await posts.getMedia_files({
transaction
});
output.deep_dive_link = await posts.getDeep_dive_link({
transaction
});
output.organizations = await posts.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.users,
as: 'author',
where: filter.author ? {
[Op.or]: [
{ id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.deep_dive_links,
as: 'deep_dive_link',
where: filter.deep_dive_link ? {
[Op.or]: [
{ id: { [Op.in]: filter.deep_dive_link.split('|').map(term => Utils.uuid(term)) } },
{
title_text: {
[Op.or]: filter.deep_dive_link.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'media_images',
},
{
model: db.file,
as: 'media_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.caption) {
where = {
...where,
[Op.and]: Utils.ilike(
'posts',
'caption',
filter.caption,
),
};
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.post_type) {
where = {
...where,
post_type: filter.post_type,
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
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.posts.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(
'posts',
'caption',
query,
),
],
};
}
const records = await db.posts.findAll({
attributes: [ 'id', 'caption' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['caption', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.caption,
}));
}
};

View File

@ -0,0 +1,493 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Product_categoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const product_categories = await db.product_categories.create(
{
id: data.id || undefined,
category_name: data.category_name
||
null
,
category_slug: data.category_slug
||
null
,
visibility: data.visibility
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await product_categories.setOrganizations( data.organizations || null, {
transaction,
});
return product_categories;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const product_categoriesData = data.map((item, index) => ({
id: item.id || undefined,
category_name: item.category_name
||
null
,
category_slug: item.category_slug
||
null
,
visibility: item.visibility
||
null
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const product_categories = await db.product_categories.bulkCreate(product_categoriesData, { transaction });
// For each item created, replace relation files
return product_categories;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const product_categories = await db.product_categories.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.category_name !== undefined) updatePayload.category_name = data.category_name;
if (data.category_slug !== undefined) updatePayload.category_slug = data.category_slug;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await product_categories.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await product_categories.setOrganizations(
data.organizations,
{ transaction }
);
}
return product_categories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const product_categories = await db.product_categories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of product_categories) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of product_categories) {
await record.destroy({transaction});
}
});
return product_categories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const product_categories = await db.product_categories.findByPk(id, options);
await product_categories.update({
deletedBy: currentUser.id
}, {
transaction,
});
await product_categories.destroy({
transaction
});
return product_categories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const product_categories = await db.product_categories.findOne(
{ where },
{ transaction },
);
if (!product_categories) {
return product_categories;
}
const output = product_categories.get({plain: true});
output.products_category = await product_categories.getProducts_category({
transaction
});
output.organizations = await product_categories.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.category_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_categories',
'category_name',
filter.category_name,
),
};
}
if (filter.category_slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_categories',
'category_slug',
filter.category_slug,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_categories',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
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.product_categories.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'product_categories',
'category_name',
query,
),
],
};
}
const records = await db.product_categories.findAll({
attributes: [ 'id', 'category_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['category_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.category_name,
}));
}
};

View File

@ -0,0 +1,668 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Product_reviewsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const product_reviews = await db.product_reviews.create(
{
id: data.id || undefined,
rating: data.rating
||
null
,
review_text: data.review_text
||
null
,
moderation_status: data.moderation_status
||
null
,
reviewed_at: data.reviewed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await product_reviews.setProduct( data.product || null, {
transaction,
});
await product_reviews.setBuyer( data.buyer || null, {
transaction,
});
await product_reviews.setOrder( data.order || null, {
transaction,
});
await product_reviews.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.product_reviews.getTableName(),
belongsToColumn: 'review_images',
belongsToId: product_reviews.id,
},
data.review_images,
options,
);
return product_reviews;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const product_reviewsData = data.map((item, index) => ({
id: item.id || undefined,
rating: item.rating
||
null
,
review_text: item.review_text
||
null
,
moderation_status: item.moderation_status
||
null
,
reviewed_at: item.reviewed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const product_reviews = await db.product_reviews.bulkCreate(product_reviewsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < product_reviews.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.product_reviews.getTableName(),
belongsToColumn: 'review_images',
belongsToId: product_reviews[i].id,
},
data[i].review_images,
options,
);
}
return product_reviews;
}
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 product_reviews = await db.product_reviews.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.rating !== undefined) updatePayload.rating = data.rating;
if (data.review_text !== undefined) updatePayload.review_text = data.review_text;
if (data.moderation_status !== undefined) updatePayload.moderation_status = data.moderation_status;
if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
updatePayload.updatedById = currentUser.id;
await product_reviews.update(updatePayload, {transaction});
if (data.product !== undefined) {
await product_reviews.setProduct(
data.product,
{ transaction }
);
}
if (data.buyer !== undefined) {
await product_reviews.setBuyer(
data.buyer,
{ transaction }
);
}
if (data.order !== undefined) {
await product_reviews.setOrder(
data.order,
{ transaction }
);
}
if (data.organizations !== undefined) {
await product_reviews.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.product_reviews.getTableName(),
belongsToColumn: 'review_images',
belongsToId: product_reviews.id,
},
data.review_images,
options,
);
return product_reviews;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const product_reviews = await db.product_reviews.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of product_reviews) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of product_reviews) {
await record.destroy({transaction});
}
});
return product_reviews;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const product_reviews = await db.product_reviews.findByPk(id, options);
await product_reviews.update({
deletedBy: currentUser.id
}, {
transaction,
});
await product_reviews.destroy({
transaction
});
return product_reviews;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const product_reviews = await db.product_reviews.findOne(
{ where },
{ transaction },
);
if (!product_reviews) {
return product_reviews;
}
const output = product_reviews.get({plain: true});
output.product = await product_reviews.getProduct({
transaction
});
output.buyer = await product_reviews.getBuyer({
transaction
});
output.order = await product_reviews.getOrder({
transaction
});
output.review_images = await product_reviews.getReview_images({
transaction
});
output.organizations = await product_reviews.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.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: 'buyer',
where: filter.buyer ? {
[Op.or]: [
{ id: { [Op.in]: filter.buyer.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.buyer.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: 'review_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.review_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_reviews',
'review_text',
filter.review_text,
),
};
}
if (filter.ratingRange) {
const [start, end] = filter.ratingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rating: {
...where.rating,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rating: {
...where.rating,
[Op.lte]: end,
},
};
}
}
if (filter.reviewed_atRange) {
const [start, end] = filter.reviewed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reviewed_at: {
...where.reviewed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reviewed_at: {
...where.reviewed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.moderation_status) {
where = {
...where,
moderation_status: filter.moderation_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.product_reviews.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'product_reviews',
'review_text',
query,
),
],
};
}
const records = await db.product_reviews.findAll({
attributes: [ 'id', 'review_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['review_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.review_text,
}));
}
};

View File

@ -0,0 +1,766 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ProductsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const products = await db.products.create(
{
id: data.id || undefined,
product_name: data.product_name
||
null
,
sku: data.sku
||
null
,
description: data.description
||
null
,
product_type: data.product_type
||
null
,
price: data.price
||
null
,
cost_price: data.cost_price
||
null
,
stock_quantity: data.stock_quantity
||
null
,
status: data.status
||
null
,
local_priority_eligible: data.local_priority_eligible
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await products.setStore( data.store || null, {
transaction,
});
await products.setCategory( data.category || null, {
transaction,
});
await products.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'product_images',
belongsToId: products.id,
},
data.product_images,
options,
);
return products;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const productsData = data.map((item, index) => ({
id: item.id || undefined,
product_name: item.product_name
||
null
,
sku: item.sku
||
null
,
description: item.description
||
null
,
product_type: item.product_type
||
null
,
price: item.price
||
null
,
cost_price: item.cost_price
||
null
,
stock_quantity: item.stock_quantity
||
null
,
status: item.status
||
null
,
local_priority_eligible: item.local_priority_eligible
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const products = await db.products.bulkCreate(productsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < products.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'product_images',
belongsToId: products[i].id,
},
data[i].product_images,
options,
);
}
return products;
}
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 products = await db.products.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.product_name !== undefined) updatePayload.product_name = data.product_name;
if (data.sku !== undefined) updatePayload.sku = data.sku;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.product_type !== undefined) updatePayload.product_type = data.product_type;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.cost_price !== undefined) updatePayload.cost_price = data.cost_price;
if (data.stock_quantity !== undefined) updatePayload.stock_quantity = data.stock_quantity;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.local_priority_eligible !== undefined) updatePayload.local_priority_eligible = data.local_priority_eligible;
updatePayload.updatedById = currentUser.id;
await products.update(updatePayload, {transaction});
if (data.store !== undefined) {
await products.setStore(
data.store,
{ transaction }
);
}
if (data.category !== undefined) {
await products.setCategory(
data.category,
{ transaction }
);
}
if (data.organizations !== undefined) {
await products.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'product_images',
belongsToId: products.id,
},
data.product_images,
options,
);
return products;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of products) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of products) {
await record.destroy({transaction});
}
});
return products;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findByPk(id, options);
await products.update({
deletedBy: currentUser.id
}, {
transaction,
});
await products.destroy({
transaction
});
return products;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findOne(
{ where },
{ transaction },
);
if (!products) {
return products;
}
const output = products.get({plain: true});
output.order_items_product = await products.getOrder_items_product({
transaction
});
output.product_reviews_product = await products.getProduct_reviews_product({
transaction
});
output.store = await products.getStore({
transaction
});
output.category = await products.getCategory({
transaction
});
output.product_images = await products.getProduct_images({
transaction
});
output.organizations = await products.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.stores,
as: 'store',
where: filter.store ? {
[Op.or]: [
{ id: { [Op.in]: filter.store.split('|').map(term => Utils.uuid(term)) } },
{
store_name: {
[Op.or]: filter.store.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.product_categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
category_name: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'product_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.product_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'product_name',
filter.product_name,
),
};
}
if (filter.sku) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'sku',
filter.sku,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'description',
filter.description,
),
};
}
if (filter.priceRange) {
const [start, end] = filter.priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price: {
...where.price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price: {
...where.price,
[Op.lte]: end,
},
};
}
}
if (filter.cost_priceRange) {
const [start, end] = filter.cost_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cost_price: {
...where.cost_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cost_price: {
...where.cost_price,
[Op.lte]: end,
},
};
}
}
if (filter.stock_quantityRange) {
const [start, end] = filter.stock_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
stock_quantity: {
...where.stock_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
stock_quantity: {
...where.stock_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.product_type) {
where = {
...where,
product_type: filter.product_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.local_priority_eligible) {
where = {
...where,
local_priority_eligible: filter.local_priority_eligible,
};
}
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.products.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'products',
'product_name',
query,
),
],
};
}
const records = await db.products.findAll({
attributes: [ 'id', 'product_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['product_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.product_name,
}));
}
};

View File

@ -0,0 +1,646 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class RewardsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const rewards = await db.rewards.create(
{
id: data.id || undefined,
reward_type: data.reward_type
||
null
,
points_amount: data.points_amount
||
null
,
cash_value_amount: data.cash_value_amount
||
null
,
status: data.status
||
null
,
awarded_at: data.awarded_at
||
null
,
expires_at: data.expires_at
||
null
,
reason_note: data.reason_note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await rewards.setUser( data.user || null, {
transaction,
});
await rewards.setOrganizations( data.organizations || null, {
transaction,
});
return rewards;
}
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 rewardsData = data.map((item, index) => ({
id: item.id || undefined,
reward_type: item.reward_type
||
null
,
points_amount: item.points_amount
||
null
,
cash_value_amount: item.cash_value_amount
||
null
,
status: item.status
||
null
,
awarded_at: item.awarded_at
||
null
,
expires_at: item.expires_at
||
null
,
reason_note: item.reason_note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const rewards = await db.rewards.bulkCreate(rewardsData, { transaction });
// For each item created, replace relation files
return rewards;
}
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 rewards = await db.rewards.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.reward_type !== undefined) updatePayload.reward_type = data.reward_type;
if (data.points_amount !== undefined) updatePayload.points_amount = data.points_amount;
if (data.cash_value_amount !== undefined) updatePayload.cash_value_amount = data.cash_value_amount;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.awarded_at !== undefined) updatePayload.awarded_at = data.awarded_at;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.reason_note !== undefined) updatePayload.reason_note = data.reason_note;
updatePayload.updatedById = currentUser.id;
await rewards.update(updatePayload, {transaction});
if (data.user !== undefined) {
await rewards.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await rewards.setOrganizations(
data.organizations,
{ transaction }
);
}
return rewards;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const rewards = await db.rewards.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of rewards) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of rewards) {
await record.destroy({transaction});
}
});
return rewards;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const rewards = await db.rewards.findByPk(id, options);
await rewards.update({
deletedBy: currentUser.id
}, {
transaction,
});
await rewards.destroy({
transaction
});
return rewards;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const rewards = await db.rewards.findOne(
{ where },
{ transaction },
);
if (!rewards) {
return rewards;
}
const output = rewards.get({plain: true});
output.user = await rewards.getUser({
transaction
});
output.organizations = await rewards.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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reason_note) {
where = {
...where,
[Op.and]: Utils.ilike(
'rewards',
'reason_note',
filter.reason_note,
),
};
}
if (filter.points_amountRange) {
const [start, end] = filter.points_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
points_amount: {
...where.points_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
points_amount: {
...where.points_amount,
[Op.lte]: end,
},
};
}
}
if (filter.cash_value_amountRange) {
const [start, end] = filter.cash_value_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cash_value_amount: {
...where.cash_value_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cash_value_amount: {
...where.cash_value_amount,
[Op.lte]: end,
},
};
}
}
if (filter.awarded_atRange) {
const [start, end] = filter.awarded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
awarded_at: {
...where.awarded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
awarded_at: {
...where.awarded_at,
[Op.lte]: end,
},
};
}
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.reward_type) {
where = {
...where,
reward_type: filter.reward_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.rewards.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(
'rewards',
'reason_note',
query,
),
],
};
}
const records = await db.rewards.findAll({
attributes: [ 'id', 'reason_note' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reason_note', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reason_note,
}));
}
};

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

@ -0,0 +1,472 @@
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,609 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ShipmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shipments = await db.shipments.create(
{
id: data.id || undefined,
carrier: data.carrier
||
null
,
tracking_number: data.tracking_number
||
null
,
shipment_status: data.shipment_status
||
null
,
shipped_at: data.shipped_at
||
null
,
delivered_at: data.delivered_at
||
null
,
shipping_fee: data.shipping_fee
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await shipments.setOrder( data.order || null, {
transaction,
});
await shipments.setOrganizations( data.organizations || null, {
transaction,
});
return shipments;
}
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 shipmentsData = data.map((item, index) => ({
id: item.id || undefined,
carrier: item.carrier
||
null
,
tracking_number: item.tracking_number
||
null
,
shipment_status: item.shipment_status
||
null
,
shipped_at: item.shipped_at
||
null
,
delivered_at: item.delivered_at
||
null
,
shipping_fee: item.shipping_fee
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const shipments = await db.shipments.bulkCreate(shipmentsData, { transaction });
// For each item created, replace relation files
return shipments;
}
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 shipments = await db.shipments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.carrier !== undefined) updatePayload.carrier = data.carrier;
if (data.tracking_number !== undefined) updatePayload.tracking_number = data.tracking_number;
if (data.shipment_status !== undefined) updatePayload.shipment_status = data.shipment_status;
if (data.shipped_at !== undefined) updatePayload.shipped_at = data.shipped_at;
if (data.delivered_at !== undefined) updatePayload.delivered_at = data.delivered_at;
if (data.shipping_fee !== undefined) updatePayload.shipping_fee = data.shipping_fee;
updatePayload.updatedById = currentUser.id;
await shipments.update(updatePayload, {transaction});
if (data.order !== undefined) {
await shipments.setOrder(
data.order,
{ transaction }
);
}
if (data.organizations !== undefined) {
await shipments.setOrganizations(
data.organizations,
{ transaction }
);
}
return shipments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shipments = await db.shipments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of shipments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of shipments) {
await record.destroy({transaction});
}
});
return shipments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const shipments = await db.shipments.findByPk(id, options);
await shipments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await shipments.destroy({
transaction
});
return shipments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const shipments = await db.shipments.findOne(
{ where },
{ transaction },
);
if (!shipments) {
return shipments;
}
const output = shipments.get({plain: true});
output.order = await shipments.getOrder({
transaction
});
output.organizations = await shipments.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.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.tracking_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'shipments',
'tracking_number',
filter.tracking_number,
),
};
}
if (filter.shipped_atRange) {
const [start, end] = filter.shipped_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
shipped_at: {
...where.shipped_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
shipped_at: {
...where.shipped_at,
[Op.lte]: end,
},
};
}
}
if (filter.delivered_atRange) {
const [start, end] = filter.delivered_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
delivered_at: {
...where.delivered_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
delivered_at: {
...where.delivered_at,
[Op.lte]: end,
},
};
}
}
if (filter.shipping_feeRange) {
const [start, end] = filter.shipping_feeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
shipping_fee: {
...where.shipping_fee,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
shipping_fee: {
...where.shipping_fee,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.carrier) {
where = {
...where,
carrier: filter.carrier,
};
}
if (filter.shipment_status) {
where = {
...where,
shipment_status: filter.shipment_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.shipments.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(
'shipments',
'tracking_number',
query,
),
],
};
}
const records = await db.shipments.findAll({
attributes: [ 'id', 'tracking_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['tracking_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.tracking_number,
}));
}
};

View File

@ -0,0 +1,685 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class StoresDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stores = await db.stores.create(
{
id: data.id || undefined,
store_name: data.store_name
||
null
,
store_slug: data.store_slug
||
null
,
store_type: data.store_type
||
null
,
status: data.status
||
null
,
description: data.description
||
null
,
support_phone: data.support_phone
||
null
,
support_email: data.support_email
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await stores.setOwner( data.owner || null, {
transaction,
});
await stores.setPrimary_address( data.primary_address || null, {
transaction,
});
await stores.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stores.getTableName(),
belongsToColumn: 'store_images',
belongsToId: stores.id,
},
data.store_images,
options,
);
return 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 storesData = data.map((item, index) => ({
id: item.id || undefined,
store_name: item.store_name
||
null
,
store_slug: item.store_slug
||
null
,
store_type: item.store_type
||
null
,
status: item.status
||
null
,
description: item.description
||
null
,
support_phone: item.support_phone
||
null
,
support_email: item.support_email
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const stores = await db.stores.bulkCreate(storesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < stores.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stores.getTableName(),
belongsToColumn: 'store_images',
belongsToId: stores[i].id,
},
data[i].store_images,
options,
);
}
return 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 stores = await db.stores.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.store_name !== undefined) updatePayload.store_name = data.store_name;
if (data.store_slug !== undefined) updatePayload.store_slug = data.store_slug;
if (data.store_type !== undefined) updatePayload.store_type = data.store_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.support_phone !== undefined) updatePayload.support_phone = data.support_phone;
if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
updatePayload.updatedById = currentUser.id;
await stores.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await stores.setOwner(
data.owner,
{ transaction }
);
}
if (data.primary_address !== undefined) {
await stores.setPrimary_address(
data.primary_address,
{ transaction }
);
}
if (data.organizations !== undefined) {
await stores.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stores.getTableName(),
belongsToColumn: 'store_images',
belongsToId: stores.id,
},
data.store_images,
options,
);
return stores;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stores = await db.stores.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of stores) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of stores) {
await record.destroy({transaction});
}
});
return stores;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stores = await db.stores.findByPk(id, options);
await stores.update({
deletedBy: currentUser.id
}, {
transaction,
});
await stores.destroy({
transaction
});
return stores;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const stores = await db.stores.findOne(
{ where },
{ transaction },
);
if (!stores) {
return stores;
}
const output = stores.get({plain: true});
output.products_store = await stores.getProducts_store({
transaction
});
output.orders_store = await stores.getOrders_store({
transaction
});
output.affiliate_programs_producer_store = await stores.getAffiliate_programs_producer_store({
transaction
});
output.owner = await stores.getOwner({
transaction
});
output.store_images = await stores.getStore_images({
transaction
});
output.primary_address = await stores.getPrimary_address({
transaction
});
output.organizations = await 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.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.addresses,
as: 'primary_address',
where: filter.primary_address ? {
[Op.or]: [
{ id: { [Op.in]: filter.primary_address.split('|').map(term => Utils.uuid(term)) } },
{
label: {
[Op.or]: filter.primary_address.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'store_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.store_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'stores',
'store_name',
filter.store_name,
),
};
}
if (filter.store_slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'stores',
'store_slug',
filter.store_slug,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'stores',
'description',
filter.description,
),
};
}
if (filter.support_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'stores',
'support_phone',
filter.support_phone,
),
};
}
if (filter.support_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'stores',
'support_email',
filter.support_email,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.store_type) {
where = {
...where,
store_type: filter.store_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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(
'stores',
'store_name',
query,
),
],
};
}
const records = await db.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,
}));
}
};

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 SubscriptionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.create(
{
id: data.id || undefined,
plan: data.plan
||
null
,
status: data.status
||
null
,
started_at: data.started_at
||
null
,
renews_at: data.renews_at
||
null
,
ended_at: data.ended_at
||
null
,
price_amount: data.price_amount
||
null
,
billing_cycle: data.billing_cycle
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await subscriptions.setUser( data.user || null, {
transaction,
});
await subscriptions.setOrganizations( data.organizations || null, {
transaction,
});
return subscriptions;
}
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 subscriptionsData = data.map((item, index) => ({
id: item.id || undefined,
plan: item.plan
||
null
,
status: item.status
||
null
,
started_at: item.started_at
||
null
,
renews_at: item.renews_at
||
null
,
ended_at: item.ended_at
||
null
,
price_amount: item.price_amount
||
null
,
billing_cycle: item.billing_cycle
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const subscriptions = await db.subscriptions.bulkCreate(subscriptionsData, { transaction });
// For each item created, replace relation files
return subscriptions;
}
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 subscriptions = await db.subscriptions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.plan !== undefined) updatePayload.plan = data.plan;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.renews_at !== undefined) updatePayload.renews_at = data.renews_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.price_amount !== undefined) updatePayload.price_amount = data.price_amount;
if (data.billing_cycle !== undefined) updatePayload.billing_cycle = data.billing_cycle;
updatePayload.updatedById = currentUser.id;
await subscriptions.update(updatePayload, {transaction});
if (data.user !== undefined) {
await subscriptions.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await subscriptions.setOrganizations(
data.organizations,
{ transaction }
);
}
return subscriptions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of subscriptions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of subscriptions) {
await record.destroy({transaction});
}
});
return subscriptions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.findByPk(id, options);
await subscriptions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await subscriptions.destroy({
transaction
});
return subscriptions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.findOne(
{ where },
{ transaction },
);
if (!subscriptions) {
return subscriptions;
}
const output = subscriptions.get({plain: true});
output.user = await subscriptions.getUser({
transaction
});
output.organizations = await subscriptions.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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.billing_cycle) {
where = {
...where,
[Op.and]: Utils.ilike(
'subscriptions',
'billing_cycle',
filter.billing_cycle,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
started_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
renews_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.renews_atRange) {
const [start, end] = filter.renews_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
renews_at: {
...where.renews_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
renews_at: {
...where.renews_at,
[Op.lte]: end,
},
};
}
}
if (filter.ended_atRange) {
const [start, end] = filter.ended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.lte]: end,
},
};
}
}
if (filter.price_amountRange) {
const [start, end] = filter.price_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_amount: {
...where.price_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_amount: {
...where.price_amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.plan) {
where = {
...where,
plan: filter.plan,
};
}
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.subscriptions.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(
'subscriptions',
'billing_cycle',
query,
),
],
};
}
const records = await db.subscriptions.findAll({
attributes: [ 'id', 'billing_cycle' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['billing_cycle', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.billing_cycle,
}));
}
};

View File

@ -0,0 +1,603 @@
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 Trust_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trust_profiles = await db.trust_profiles.create(
{
id: data.id || undefined,
trust_score: data.trust_score
||
null
,
trust_tier: data.trust_tier
||
null
,
score_last_calculated_at: data.score_last_calculated_at
||
null
,
is_human_verified: data.is_human_verified
||
false
,
is_business_verified: data.is_business_verified
||
false
,
is_identity_verified: data.is_identity_verified
||
false
,
is_tax_verified: data.is_tax_verified
||
false
,
risk_flags_summary: data.risk_flags_summary
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await trust_profiles.setOrganizations( data.organizations || null, {
transaction,
});
return trust_profiles;
}
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 trust_profilesData = data.map((item, index) => ({
id: item.id || undefined,
trust_score: item.trust_score
||
null
,
trust_tier: item.trust_tier
||
null
,
score_last_calculated_at: item.score_last_calculated_at
||
null
,
is_human_verified: item.is_human_verified
||
false
,
is_business_verified: item.is_business_verified
||
false
,
is_identity_verified: item.is_identity_verified
||
false
,
is_tax_verified: item.is_tax_verified
||
false
,
risk_flags_summary: item.risk_flags_summary
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const trust_profiles = await db.trust_profiles.bulkCreate(trust_profilesData, { transaction });
// For each item created, replace relation files
return trust_profiles;
}
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 trust_profiles = await db.trust_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.trust_score !== undefined) updatePayload.trust_score = data.trust_score;
if (data.trust_tier !== undefined) updatePayload.trust_tier = data.trust_tier;
if (data.score_last_calculated_at !== undefined) updatePayload.score_last_calculated_at = data.score_last_calculated_at;
if (data.is_human_verified !== undefined) updatePayload.is_human_verified = data.is_human_verified;
if (data.is_business_verified !== undefined) updatePayload.is_business_verified = data.is_business_verified;
if (data.is_identity_verified !== undefined) updatePayload.is_identity_verified = data.is_identity_verified;
if (data.is_tax_verified !== undefined) updatePayload.is_tax_verified = data.is_tax_verified;
if (data.risk_flags_summary !== undefined) updatePayload.risk_flags_summary = data.risk_flags_summary;
updatePayload.updatedById = currentUser.id;
await trust_profiles.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await trust_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
return trust_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trust_profiles = await db.trust_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of trust_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of trust_profiles) {
await record.destroy({transaction});
}
});
return trust_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const trust_profiles = await db.trust_profiles.findByPk(id, options);
await trust_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await trust_profiles.destroy({
transaction
});
return trust_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const trust_profiles = await db.trust_profiles.findOne(
{ where },
{ transaction },
);
if (!trust_profiles) {
return trust_profiles;
}
const output = trust_profiles.get({plain: true});
output.organizations = await trust_profiles.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.risk_flags_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'trust_profiles',
'risk_flags_summary',
filter.risk_flags_summary,
),
};
}
if (filter.trust_scoreRange) {
const [start, end] = filter.trust_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
trust_score: {
...where.trust_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
trust_score: {
...where.trust_score,
[Op.lte]: end,
},
};
}
}
if (filter.score_last_calculated_atRange) {
const [start, end] = filter.score_last_calculated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score_last_calculated_at: {
...where.score_last_calculated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score_last_calculated_at: {
...where.score_last_calculated_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.trust_tier) {
where = {
...where,
trust_tier: filter.trust_tier,
};
}
if (filter.is_human_verified) {
where = {
...where,
is_human_verified: filter.is_human_verified,
};
}
if (filter.is_business_verified) {
where = {
...where,
is_business_verified: filter.is_business_verified,
};
}
if (filter.is_identity_verified) {
where = {
...where,
is_identity_verified: filter.is_identity_verified,
};
}
if (filter.is_tax_verified) {
where = {
...where,
is_tax_verified: filter.is_tax_verified,
};
}
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.trust_profiles.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(
'trust_profiles',
'risk_flags_summary',
query,
),
],
};
}
const records = await db.trust_profiles.findAll({
attributes: [ 'id', 'risk_flags_summary' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['risk_flags_summary', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.risk_flags_summary,
}));
}
};

View File

@ -0,0 +1,662 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class User_credentialsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_credentials = await db.user_credentials.create(
{
id: data.id || undefined,
credential_type: data.credential_type
||
null
,
title_text: data.title_text
||
null
,
issuer_name: data.issuer_name
||
null
,
issued_at: data.issued_at
||
null
,
valid_until: data.valid_until
||
null
,
verification_status: data.verification_status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await user_credentials.setUser( data.user || null, {
transaction,
});
await user_credentials.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.user_credentials.getTableName(),
belongsToColumn: 'proof_files',
belongsToId: user_credentials.id,
},
data.proof_files,
options,
);
return user_credentials;
}
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 user_credentialsData = data.map((item, index) => ({
id: item.id || undefined,
credential_type: item.credential_type
||
null
,
title_text: item.title_text
||
null
,
issuer_name: item.issuer_name
||
null
,
issued_at: item.issued_at
||
null
,
valid_until: item.valid_until
||
null
,
verification_status: item.verification_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 user_credentials = await db.user_credentials.bulkCreate(user_credentialsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < user_credentials.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.user_credentials.getTableName(),
belongsToColumn: 'proof_files',
belongsToId: user_credentials[i].id,
},
data[i].proof_files,
options,
);
}
return user_credentials;
}
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 user_credentials = await db.user_credentials.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.credential_type !== undefined) updatePayload.credential_type = data.credential_type;
if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
if (data.issuer_name !== undefined) updatePayload.issuer_name = data.issuer_name;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.valid_until !== undefined) updatePayload.valid_until = data.valid_until;
if (data.verification_status !== undefined) updatePayload.verification_status = data.verification_status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await user_credentials.update(updatePayload, {transaction});
if (data.user !== undefined) {
await user_credentials.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await user_credentials.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.user_credentials.getTableName(),
belongsToColumn: 'proof_files',
belongsToId: user_credentials.id,
},
data.proof_files,
options,
);
return user_credentials;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_credentials = await db.user_credentials.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_credentials) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_credentials) {
await record.destroy({transaction});
}
});
return user_credentials;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_credentials = await db.user_credentials.findByPk(id, options);
await user_credentials.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_credentials.destroy({
transaction
});
return user_credentials;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_credentials = await db.user_credentials.findOne(
{ where },
{ transaction },
);
if (!user_credentials) {
return user_credentials;
}
const output = user_credentials.get({plain: true});
output.user = await user_credentials.getUser({
transaction
});
output.proof_files = await user_credentials.getProof_files({
transaction
});
output.organizations = await user_credentials.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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'proof_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_credentials',
'title_text',
filter.title_text,
),
};
}
if (filter.issuer_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_credentials',
'issuer_name',
filter.issuer_name,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_credentials',
'notes',
filter.notes,
),
};
}
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.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.credential_type) {
where = {
...where,
credential_type: filter.credential_type,
};
}
if (filter.verification_status) {
where = {
...where,
verification_status: filter.verification_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.user_credentials.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(
'user_credentials',
'title_text',
query,
),
],
};
}
const records = await db.user_credentials.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,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,722 @@
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 Wallet_transactionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const wallet_transactions = await db.wallet_transactions.create(
{
id: data.id || undefined,
direction: data.direction
||
null
,
transaction_type: data.transaction_type
||
null
,
status: data.status
||
null
,
amount: data.amount
||
null
,
fee_amount: data.fee_amount
||
null
,
reference_code: data.reference_code
||
null
,
counterparty_label: data.counterparty_label
||
null
,
initiated_at: data.initiated_at
||
null
,
settled_at: data.settled_at
||
null
,
memo: data.memo
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await wallet_transactions.setWallet( data.wallet || null, {
transaction,
});
await wallet_transactions.setOrganizations( data.organizations || null, {
transaction,
});
return wallet_transactions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const wallet_transactionsData = data.map((item, index) => ({
id: item.id || undefined,
direction: item.direction
||
null
,
transaction_type: item.transaction_type
||
null
,
status: item.status
||
null
,
amount: item.amount
||
null
,
fee_amount: item.fee_amount
||
null
,
reference_code: item.reference_code
||
null
,
counterparty_label: item.counterparty_label
||
null
,
initiated_at: item.initiated_at
||
null
,
settled_at: item.settled_at
||
null
,
memo: item.memo
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const wallet_transactions = await db.wallet_transactions.bulkCreate(wallet_transactionsData, { transaction });
// For each item created, replace relation files
return wallet_transactions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const wallet_transactions = await db.wallet_transactions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.direction !== undefined) updatePayload.direction = data.direction;
if (data.transaction_type !== undefined) updatePayload.transaction_type = data.transaction_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.fee_amount !== undefined) updatePayload.fee_amount = data.fee_amount;
if (data.reference_code !== undefined) updatePayload.reference_code = data.reference_code;
if (data.counterparty_label !== undefined) updatePayload.counterparty_label = data.counterparty_label;
if (data.initiated_at !== undefined) updatePayload.initiated_at = data.initiated_at;
if (data.settled_at !== undefined) updatePayload.settled_at = data.settled_at;
if (data.memo !== undefined) updatePayload.memo = data.memo;
updatePayload.updatedById = currentUser.id;
await wallet_transactions.update(updatePayload, {transaction});
if (data.wallet !== undefined) {
await wallet_transactions.setWallet(
data.wallet,
{ transaction }
);
}
if (data.organizations !== undefined) {
await wallet_transactions.setOrganizations(
data.organizations,
{ transaction }
);
}
return wallet_transactions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const wallet_transactions = await db.wallet_transactions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of wallet_transactions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of wallet_transactions) {
await record.destroy({transaction});
}
});
return wallet_transactions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const wallet_transactions = await db.wallet_transactions.findByPk(id, options);
await wallet_transactions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await wallet_transactions.destroy({
transaction
});
return wallet_transactions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const wallet_transactions = await db.wallet_transactions.findOne(
{ where },
{ transaction },
);
if (!wallet_transactions) {
return wallet_transactions;
}
const output = wallet_transactions.get({plain: true});
output.payments_wallet_transaction = await wallet_transactions.getPayments_wallet_transaction({
transaction
});
output.commissions_wallet_transaction = await wallet_transactions.getCommissions_wallet_transaction({
transaction
});
output.wallet = await wallet_transactions.getWallet({
transaction
});
output.organizations = await wallet_transactions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.wallets,
as: 'wallet',
where: filter.wallet ? {
[Op.or]: [
{ id: { [Op.in]: filter.wallet.split('|').map(term => Utils.uuid(term)) } },
{
wallet_code: {
[Op.or]: filter.wallet.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_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallet_transactions',
'reference_code',
filter.reference_code,
),
};
}
if (filter.counterparty_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallet_transactions',
'counterparty_label',
filter.counterparty_label,
),
};
}
if (filter.memo) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallet_transactions',
'memo',
filter.memo,
),
};
}
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.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.initiated_atRange) {
const [start, end] = filter.initiated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
initiated_at: {
...where.initiated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
initiated_at: {
...where.initiated_at,
[Op.lte]: end,
},
};
}
}
if (filter.settled_atRange) {
const [start, end] = filter.settled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
settled_at: {
...where.settled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
settled_at: {
...where.settled_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.direction) {
where = {
...where,
direction: filter.direction,
};
}
if (filter.transaction_type) {
where = {
...where,
transaction_type: filter.transaction_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.wallet_transactions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'wallet_transactions',
'reference_code',
query,
),
],
};
}
const records = await db.wallet_transactions.findAll({
attributes: [ 'id', 'reference_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reference_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reference_code,
}));
}
};

View File

@ -0,0 +1,617 @@
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 WalletsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const wallets = await db.wallets.create(
{
id: data.id || undefined,
wallet_code: data.wallet_code
||
null
,
status: data.status
||
null
,
available_balance: data.available_balance
||
null
,
pending_balance: data.pending_balance
||
null
,
currency: data.currency
||
null
,
opened_at: data.opened_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await wallets.setOwner( data.owner || null, {
transaction,
});
await wallets.setOrganizations( data.organizations || null, {
transaction,
});
return wallets;
}
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 walletsData = data.map((item, index) => ({
id: item.id || undefined,
wallet_code: item.wallet_code
||
null
,
status: item.status
||
null
,
available_balance: item.available_balance
||
null
,
pending_balance: item.pending_balance
||
null
,
currency: item.currency
||
null
,
opened_at: item.opened_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const wallets = await db.wallets.bulkCreate(walletsData, { transaction });
// For each item created, replace relation files
return wallets;
}
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 wallets = await db.wallets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.wallet_code !== undefined) updatePayload.wallet_code = data.wallet_code;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.available_balance !== undefined) updatePayload.available_balance = data.available_balance;
if (data.pending_balance !== undefined) updatePayload.pending_balance = data.pending_balance;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
updatePayload.updatedById = currentUser.id;
await wallets.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await wallets.setOwner(
data.owner,
{ transaction }
);
}
if (data.organizations !== undefined) {
await wallets.setOrganizations(
data.organizations,
{ transaction }
);
}
return wallets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const wallets = await db.wallets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of wallets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of wallets) {
await record.destroy({transaction});
}
});
return wallets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const wallets = await db.wallets.findByPk(id, options);
await wallets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await wallets.destroy({
transaction
});
return wallets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const wallets = await db.wallets.findOne(
{ where },
{ transaction },
);
if (!wallets) {
return wallets;
}
const output = wallets.get({plain: true});
output.wallet_transactions_wallet = await wallets.getWallet_transactions_wallet({
transaction
});
output.owner = await wallets.getOwner({
transaction
});
output.organizations = await wallets.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.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.wallet_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallets',
'wallet_code',
filter.wallet_code,
),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallets',
'currency',
filter.currency,
),
};
}
if (filter.available_balanceRange) {
const [start, end] = filter.available_balanceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
available_balance: {
...where.available_balance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
available_balance: {
...where.available_balance,
[Op.lte]: end,
},
};
}
}
if (filter.pending_balanceRange) {
const [start, end] = filter.pending_balanceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pending_balance: {
...where.pending_balance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pending_balance: {
...where.pending_balance,
[Op.lte]: end,
},
};
}
}
if (filter.opened_atRange) {
const [start, end] = filter.opened_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.wallets.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(
'wallets',
'wallet_code',
query,
),
],
};
}
const records = await db.wallets.findAll({
attributes: [ 'id', 'wallet_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['wallet_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.wallet_code,
}));
}
};

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_universe_mvp',
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,226 @@
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 addresses = sequelize.define(
'addresses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
label: {
type: DataTypes.TEXT,
},
recipient_name: {
type: DataTypes.TEXT,
},
phone_number: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
province: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
district: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
street_address: {
type: DataTypes.TEXT,
},
latitude: {
type: DataTypes.DECIMAL,
},
longitude: {
type: DataTypes.DECIMAL,
},
is_default: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
addresses.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.addresses.hasMany(db.stores, {
as: 'stores_primary_address',
foreignKey: {
name: 'primary_addressId',
},
constraints: false,
});
db.addresses.hasMany(db.orders, {
as: 'orders_shipping_address',
foreignKey: {
name: 'shipping_addressId',
},
constraints: false,
});
db.addresses.hasMany(db.job_companies, {
as: 'job_companies_hq_address',
foreignKey: {
name: 'hq_addressId',
},
constraints: false,
});
//end loop
db.addresses.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.addresses.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.addresses.belongsTo(db.users, {
as: 'createdBy',
});
db.addresses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return addresses;
};

View File

@ -0,0 +1,184 @@
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 affiliate_memberships = sequelize.define(
'affiliate_memberships',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"applied",
"approved",
"rejected",
"suspended",
"left"
],
},
applied_at: {
type: DataTypes.DATE,
},
approved_at: {
type: DataTypes.DATE,
},
referral_code: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
affiliate_memberships.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.affiliate_memberships.hasMany(db.commissions, {
as: 'commissions_membership',
foreignKey: {
name: 'membershipId',
},
constraints: false,
});
//end loop
db.affiliate_memberships.belongsTo(db.affiliate_programs, {
as: 'program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
db.affiliate_memberships.belongsTo(db.users, {
as: 'member',
foreignKey: {
name: 'memberId',
},
constraints: false,
});
db.affiliate_memberships.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.affiliate_memberships.belongsTo(db.users, {
as: 'createdBy',
});
db.affiliate_memberships.belongsTo(db.users, {
as: 'updatedBy',
});
};
return affiliate_memberships;
};

View File

@ -0,0 +1,187 @@
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 affiliate_programs = sequelize.define(
'affiliate_programs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
program_name: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"active",
"paused",
"closed"
],
},
commission_rate_percent: {
type: DataTypes.DECIMAL,
},
terms_text: {
type: DataTypes.TEXT,
},
min_trust_score_to_join: {
type: DataTypes.INTEGER,
},
starts_at: {
type: DataTypes.DATE,
},
ends_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
affiliate_programs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.affiliate_programs.hasMany(db.affiliate_memberships, {
as: 'affiliate_memberships_program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
//end loop
db.affiliate_programs.belongsTo(db.stores, {
as: 'producer_store',
foreignKey: {
name: 'producer_storeId',
},
constraints: false,
});
db.affiliate_programs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.affiliate_programs.belongsTo(db.users, {
as: 'createdBy',
});
db.affiliate_programs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return affiliate_programs;
};

View File

@ -0,0 +1,197 @@
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 api_clients = sequelize.define(
'api_clients',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
client_name: {
type: DataTypes.TEXT,
},
client_type: {
type: DataTypes.ENUM,
values: [
"enterprise",
"university",
"government",
"partner"
],
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"suspended",
"revoked"
],
},
contact_email: {
type: DataTypes.TEXT,
},
contact_phone: {
type: DataTypes.TEXT,
},
api_key_label: {
type: DataTypes.TEXT,
},
issued_at: {
type: DataTypes.DATE,
},
last_used_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
api_clients.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.api_clients.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.api_clients.belongsTo(db.users, {
as: 'createdBy',
});
db.api_clients.belongsTo(db.users, {
as: 'updatedBy',
});
};
return api_clients;
};

View File

@ -0,0 +1,197 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_events = sequelize.define(
'audit_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_type: {
type: DataTypes.ENUM,
values: [
"login",
"verification_submitted",
"verification_reviewed",
"trust_score_changed",
"payment_initiated",
"payment_settled",
"content_published",
"content_removed",
"admin_action",
"api_call"
],
},
entity_name: {
type: DataTypes.TEXT,
},
entity_key: {
type: DataTypes.TEXT,
},
ip_address: {
type: DataTypes.TEXT,
},
user_agent: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
details_json: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
audit_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.audit_events.belongsTo(db.users, {
as: 'actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.audit_events.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.audit_events.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_events;
};

View File

@ -0,0 +1,159 @@
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 chat_participants = sequelize.define(
'chat_participants',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
role: {
type: DataTypes.ENUM,
values: [
"owner",
"admin",
"member"
],
},
joined_at: {
type: DataTypes.DATE,
},
is_muted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
chat_participants.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.chat_participants.belongsTo(db.chats, {
as: 'chat',
foreignKey: {
name: 'chatId',
},
constraints: false,
});
db.chat_participants.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.chat_participants.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.chat_participants.belongsTo(db.users, {
as: 'createdBy',
});
db.chat_participants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return chat_participants;
};

View File

@ -0,0 +1,184 @@
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 chats = sequelize.define(
'chats',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
chat_type: {
type: DataTypes.ENUM,
values: [
"direct",
"group",
"business_thread"
],
},
chat_title: {
type: DataTypes.TEXT,
},
last_message_at: {
type: DataTypes.DATE,
},
is_encrypted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
chats.associate = (db) => {
db.chats.belongsToMany(db.chat_participants, {
as: 'participants',
foreignKey: {
name: 'chats_participantsId',
},
constraints: false,
through: 'chatsParticipantsChat_participants',
});
db.chats.belongsToMany(db.chat_participants, {
as: 'participants_filter',
foreignKey: {
name: 'chats_participantsId',
},
constraints: false,
through: 'chatsParticipantsChat_participants',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.chats.hasMany(db.chat_participants, {
as: 'chat_participants_chat',
foreignKey: {
name: 'chatId',
},
constraints: false,
});
db.chats.hasMany(db.messages, {
as: 'messages_chat',
foreignKey: {
name: 'chatId',
},
constraints: false,
});
//end loop
db.chats.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.chats.belongsTo(db.users, {
as: 'createdBy',
});
db.chats.belongsTo(db.users, {
as: 'updatedBy',
});
};
return chats;
};

View File

@ -0,0 +1,208 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const citations = sequelize.define(
'citations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
source_type: {
type: DataTypes.ENUM,
values: [
"journal",
"government",
"education",
"organization",
"dataset",
"book",
"transcript",
"other"
],
},
source_title: {
type: DataTypes.TEXT,
},
source_url: {
type: DataTypes.TEXT,
},
publisher: {
type: DataTypes.TEXT,
},
published_at: {
type: DataTypes.DATE,
},
quote_excerpt: {
type: DataTypes.TEXT,
},
doi_or_identifier: {
type: DataTypes.TEXT,
},
credibility_grade: {
type: DataTypes.ENUM,
values: [
"a",
"b",
"c",
"d",
"unknown"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
citations.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.citations.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.citations.belongsTo(db.users, {
as: 'createdBy',
});
db.citations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return citations;
};

View File

@ -0,0 +1,188 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const commissions = sequelize.define(
'commissions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"payable",
"paid",
"reversed"
],
},
gross_profit_amount: {
type: DataTypes.DECIMAL,
},
commission_amount: {
type: DataTypes.DECIMAL,
},
commission_rate_percent: {
type: DataTypes.DECIMAL,
},
earned_at: {
type: DataTypes.DATE,
},
paid_at: {
type: DataTypes.DATE,
},
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.affiliate_memberships, {
as: 'membership',
foreignKey: {
name: 'membershipId',
},
constraints: false,
});
db.commissions.belongsTo(db.orders, {
as: 'order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.commissions.belongsTo(db.wallet_transactions, {
as: 'wallet_transaction',
foreignKey: {
name: 'wallet_transactionId',
},
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,194 @@
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 deep_dive_links = sequelize.define(
'deep_dive_links',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title_text: {
type: DataTypes.TEXT,
},
summary: {
type: DataTypes.TEXT,
},
validation_status: {
type: DataTypes.ENUM,
values: [
"pending",
"valid",
"needs_review",
"rejected"
],
},
ai_confidence: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
deep_dive_links.associate = (db) => {
db.deep_dive_links.belongsToMany(db.citations, {
as: 'citations',
foreignKey: {
name: 'deep_dive_links_citationsId',
},
constraints: false,
through: 'deep_dive_linksCitationsCitations',
});
db.deep_dive_links.belongsToMany(db.citations, {
as: 'citations_filter',
foreignKey: {
name: 'deep_dive_links_citationsId',
},
constraints: false,
through: 'deep_dive_linksCitationsCitations',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.deep_dive_links.hasMany(db.posts, {
as: 'posts_deep_dive_link',
foreignKey: {
name: 'deep_dive_linkId',
},
constraints: false,
});
//end loop
db.deep_dive_links.belongsTo(db.users, {
as: 'creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.deep_dive_links.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.deep_dive_links.hasMany(db.file, {
as: 'evidence_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.deep_dive_links.getTableName(),
belongsToColumn: 'evidence_files',
},
});
db.deep_dive_links.belongsTo(db.users, {
as: 'createdBy',
});
db.deep_dive_links.belongsTo(db.users, {
as: 'updatedBy',
});
};
return deep_dive_links;
};

View File

@ -0,0 +1,204 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const facta_answers = sequelize.define(
'facta_answers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
executive_summary: {
type: DataTypes.TEXT,
},
truth_score_percent: {
type: DataTypes.DECIMAL,
},
verification_status: {
type: DataTypes.ENUM,
values: [
"verified",
"partially_verified",
"unverified",
"conflicting"
],
},
ready_to_cite_text: {
type: DataTypes.TEXT,
},
neutral_perspective: {
type: DataTypes.TEXT,
},
pro_perspective: {
type: DataTypes.TEXT,
},
contra_perspective: {
type: DataTypes.TEXT,
},
generated_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
facta_answers.associate = (db) => {
db.facta_answers.belongsToMany(db.citations, {
as: 'citations',
foreignKey: {
name: 'facta_answers_citationsId',
},
constraints: false,
through: 'facta_answersCitationsCitations',
});
db.facta_answers.belongsToMany(db.citations, {
as: 'citations_filter',
foreignKey: {
name: 'facta_answers_citationsId',
},
constraints: false,
through: 'facta_answersCitationsCitations',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.facta_answers.belongsTo(db.facta_queries, {
as: 'facta_query',
foreignKey: {
name: 'facta_queryId',
},
constraints: false,
});
db.facta_answers.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.facta_answers.belongsTo(db.users, {
as: 'createdBy',
});
db.facta_answers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return facta_answers;
};

View File

@ -0,0 +1,185 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const facta_queries = sequelize.define(
'facta_queries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
query_text: {
type: DataTypes.TEXT,
},
mode: {
type: DataTypes.ENUM,
values: [
"web_search",
"database_search",
"hybrid"
],
},
sensitivity: {
type: DataTypes.ENUM,
values: [
"general",
"professional",
"high_stakes"
],
},
queried_at: {
type: DataTypes.DATE,
},
is_history_saved: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
facta_queries.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.facta_queries.hasMany(db.facta_answers, {
as: 'facta_answers_facta_query',
foreignKey: {
name: 'facta_queryId',
},
constraints: false,
});
//end loop
db.facta_queries.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.facta_queries.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.facta_queries.belongsTo(db.users, {
as: 'createdBy',
});
db.facta_queries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return facta_queries;
};

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,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 forum_posts = sequelize.define(
'forum_posts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
body_text: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"visible",
"hidden",
"removed"
],
},
posted_at: {
type: DataTypes.DATE,
},
upvotes_count: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
forum_posts.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.forum_posts.belongsTo(db.forum_threads, {
as: 'thread',
foreignKey: {
name: 'threadId',
},
constraints: false,
});
db.forum_posts.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.forum_posts.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.forum_posts.belongsTo(db.users, {
as: 'createdBy',
});
db.forum_posts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return forum_posts;
};

View File

@ -0,0 +1,181 @@
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 forum_spaces = sequelize.define(
'forum_spaces',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
space_name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
center_latitude: {
type: DataTypes.DECIMAL,
},
center_longitude: {
type: DataTypes.DECIMAL,
},
radius_meters: {
type: DataTypes.INTEGER,
},
min_trust_score_to_post: {
type: DataTypes.INTEGER,
},
visibility: {
type: DataTypes.ENUM,
values: [
"public",
"members_only"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
forum_spaces.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.forum_spaces.hasMany(db.forum_threads, {
as: 'forum_threads_space',
foreignKey: {
name: 'spaceId',
},
constraints: false,
});
//end loop
db.forum_spaces.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.forum_spaces.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.forum_spaces.belongsTo(db.users, {
as: 'createdBy',
});
db.forum_spaces.belongsTo(db.users, {
as: 'updatedBy',
});
};
return forum_spaces;
};

View File

@ -0,0 +1,185 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const forum_threads = sequelize.define(
'forum_threads',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
thread_title: {
type: DataTypes.TEXT,
},
thread_body: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"locked",
"removed"
],
},
created_on: {
type: DataTypes.DATE,
},
last_activity_at: {
type: DataTypes.DATE,
},
upvotes_count: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
forum_threads.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.forum_threads.hasMany(db.forum_posts, {
as: 'forum_posts_thread',
foreignKey: {
name: 'threadId',
},
constraints: false,
});
//end loop
db.forum_threads.belongsTo(db.forum_spaces, {
as: 'space',
foreignKey: {
name: 'spaceId',
},
constraints: false,
});
db.forum_threads.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.forum_threads.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.forum_threads.belongsTo(db.users, {
as: 'createdBy',
});
db.forum_threads.belongsTo(db.users, {
as: 'updatedBy',
});
};
return forum_threads;
};

View File

@ -0,0 +1,177 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const geo_rules = sequelize.define(
'geo_rules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
rule_name: {
type: DataTypes.TEXT,
},
rule_type: {
type: DataTypes.ENUM,
values: [
"geofence_access",
"local_priority",
"supply_routing"
],
},
center_latitude: {
type: DataTypes.DECIMAL,
},
center_longitude: {
type: DataTypes.DECIMAL,
},
radius_meters: {
type: DataTypes.INTEGER,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"inactive"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
geo_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.geo_rules.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.geo_rules.belongsTo(db.users, {
as: 'createdBy',
});
db.geo_rules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return geo_rules;
};

View File

@ -0,0 +1,233 @@
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 identity_verifications = sequelize.define(
'identity_verifications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
verification_type: {
type: DataTypes.ENUM,
values: [
"ktp",
"npwp",
"business_legal",
"face_biometric",
"education_credential",
"employment_credential",
"address_proof"
],
},
status: {
type: DataTypes.ENUM,
values: [
"submitted",
"in_review",
"approved",
"rejected",
"expired"
],
},
submitted_at: {
type: DataTypes.DATE,
},
reviewed_at: {
type: DataTypes.DATE,
},
expires_at: {
type: DataTypes.DATE,
},
document_number: {
type: DataTypes.TEXT,
},
match_confidence: {
type: DataTypes.DECIMAL,
},
review_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
identity_verifications.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.identity_verifications.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.identity_verifications.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.identity_verifications.hasMany(db.file, {
as: 'document_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.identity_verifications.getTableName(),
belongsToColumn: 'document_files',
},
});
db.identity_verifications.hasMany(db.file, {
as: 'selfie_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.identity_verifications.getTableName(),
belongsToColumn: 'selfie_images',
},
});
db.identity_verifications.belongsTo(db.users, {
as: 'createdBy',
});
db.identity_verifications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return identity_verifications;
};

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,185 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const job_applications = sequelize.define(
'job_applications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"submitted",
"shortlisted",
"interview",
"offer",
"hired",
"rejected",
"withdrawn"
],
},
cover_letter: {
type: DataTypes.TEXT,
},
applied_at: {
type: DataTypes.DATE,
},
last_updated_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
job_applications.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.job_applications.belongsTo(db.job_listings, {
as: 'job_listing',
foreignKey: {
name: 'job_listingId',
},
constraints: false,
});
db.job_applications.belongsTo(db.users, {
as: 'applicant',
foreignKey: {
name: 'applicantId',
},
constraints: false,
});
db.job_applications.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.job_applications.hasMany(db.file, {
as: 'resume_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.job_applications.getTableName(),
belongsToColumn: 'resume_files',
},
});
db.job_applications.belongsTo(db.users, {
as: 'createdBy',
});
db.job_applications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return job_applications;
};

View File

@ -0,0 +1,216 @@
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 job_companies = sequelize.define(
'job_companies',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
company_name: {
type: DataTypes.TEXT,
},
company_legal_name: {
type: DataTypes.TEXT,
},
company_website: {
type: DataTypes.TEXT,
},
company_size: {
type: DataTypes.ENUM,
values: [
"micro",
"small",
"medium",
"large",
"enterprise"
],
},
verification_status: {
type: DataTypes.ENUM,
values: [
"unverified",
"pending",
"verified",
"rejected"
],
},
about: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
job_companies.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.job_companies.hasMany(db.job_listings, {
as: 'job_listings_company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
//end loop
db.job_companies.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.job_companies.belongsTo(db.addresses, {
as: 'hq_address',
foreignKey: {
name: 'hq_addressId',
},
constraints: false,
});
db.job_companies.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.job_companies.hasMany(db.file, {
as: 'company_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.job_companies.getTableName(),
belongsToColumn: 'company_images',
},
});
db.job_companies.belongsTo(db.users, {
as: 'createdBy',
});
db.job_companies.belongsTo(db.users, {
as: 'updatedBy',
});
};
return job_companies;
};

View File

@ -0,0 +1,238 @@
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 job_listings = sequelize.define(
'job_listings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
job_title: {
type: DataTypes.TEXT,
},
employment_type: {
type: DataTypes.ENUM,
values: [
"full_time",
"part_time",
"contract",
"internship",
"freelance"
],
},
work_mode: {
type: DataTypes.ENUM,
values: [
"on_site",
"hybrid",
"remote"
],
},
location_text: {
type: DataTypes.TEXT,
},
salary_min: {
type: DataTypes.DECIMAL,
},
salary_max: {
type: DataTypes.DECIMAL,
},
description: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"open",
"closed",
"paused"
],
},
posted_at: {
type: DataTypes.DATE,
},
closes_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
job_listings.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.job_listings.hasMany(db.job_applications, {
as: 'job_applications_job_listing',
foreignKey: {
name: 'job_listingId',
},
constraints: false,
});
//end loop
db.job_listings.belongsTo(db.job_companies, {
as: 'company',
foreignKey: {
name: 'companyId',
},
constraints: false,
});
db.job_listings.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.job_listings.belongsTo(db.users, {
as: 'createdBy',
});
db.job_listings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return job_listings;
};

View File

@ -0,0 +1,202 @@
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 messages = sequelize.define(
'messages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
message_type: {
type: DataTypes.ENUM,
values: [
"text",
"image",
"file",
"product_card",
"order_card",
"payment_request",
"system"
],
},
text_body: {
type: DataTypes.TEXT,
},
link_url: {
type: DataTypes.TEXT,
},
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,
},
);
messages.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.messages.belongsTo(db.chats, {
as: 'chat',
foreignKey: {
name: 'chatId',
},
constraints: false,
});
db.messages.belongsTo(db.users, {
as: 'sender',
foreignKey: {
name: 'senderId',
},
constraints: false,
});
db.messages.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.messages.hasMany(db.file, {
as: 'image_attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.messages.getTableName(),
belongsToColumn: 'image_attachments',
},
});
db.messages.hasMany(db.file, {
as: 'file_attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.messages.getTableName(),
belongsToColumn: 'file_attachments',
},
});
db.messages.belongsTo(db.users, {
as: 'createdBy',
});
db.messages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return messages;
};

View File

@ -0,0 +1,151 @@
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,
},
quantity: {
type: DataTypes.INTEGER,
},
unit_price: {
type: DataTypes.DECIMAL,
},
line_total: {
type: DataTypes.DECIMAL,
},
variant_label: {
type: DataTypes.TEXT,
},
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
//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,254 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const orders = sequelize.define(
'orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
order_number: {
type: DataTypes.TEXT,
},
order_status: {
type: DataTypes.ENUM,
values: [
"pending_payment",
"paid",
"processing",
"shipped",
"delivered",
"completed",
"cancelled",
"refunded"
],
},
subtotal_amount: {
type: DataTypes.DECIMAL,
},
shipping_amount: {
type: DataTypes.DECIMAL,
},
total_amount: {
type: DataTypes.DECIMAL,
},
placed_at: {
type: DataTypes.DATE,
},
paid_at: {
type: DataTypes.DATE,
},
buyer_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.payments, {
as: 'payments_order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.orders.hasMany(db.product_reviews, {
as: 'product_reviews_order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.orders.hasMany(db.shipments, {
as: 'shipments_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.users, {
as: 'buyer',
foreignKey: {
name: 'buyerId',
},
constraints: false,
});
db.orders.belongsTo(db.stores, {
as: 'store',
foreignKey: {
name: 'storeId',
},
constraints: false,
});
db.orders.belongsTo(db.addresses, {
as: 'shipping_address',
foreignKey: {
name: 'shipping_addressId',
},
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,410 @@
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.trust_profiles, {
as: 'trust_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.identity_verifications, {
as: 'identity_verifications_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.wallets, {
as: 'wallets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.wallet_transactions, {
as: 'wallet_transactions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.chats, {
as: 'chats_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.chat_participants, {
as: 'chat_participants_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.messages, {
as: 'messages_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.stores, {
as: 'stores_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.addresses, {
as: 'addresses_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.product_categories, {
as: 'product_categories_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.products, {
as: 'products_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.payments, {
as: 'payments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.product_reviews, {
as: 'product_reviews_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.shipments, {
as: 'shipments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.posts, {
as: 'posts_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.deep_dive_links, {
as: 'deep_dive_links_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.citations, {
as: 'citations_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.post_engagements, {
as: 'post_engagements_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.rewards, {
as: 'rewards_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.forum_spaces, {
as: 'forum_spaces_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.forum_threads, {
as: 'forum_threads_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.forum_posts, {
as: 'forum_posts_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.job_companies, {
as: 'job_companies_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.job_listings, {
as: 'job_listings_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.job_applications, {
as: 'job_applications_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.user_credentials, {
as: 'user_credentials_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.affiliate_programs, {
as: 'affiliate_programs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.affiliate_memberships, {
as: 'affiliate_memberships_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.commissions, {
as: 'commissions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.geo_rules, {
as: 'geo_rules_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.facta_queries, {
as: 'facta_queries_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.facta_answers, {
as: 'facta_answers_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.subscriptions, {
as: 'subscriptions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.api_clients, {
as: 'api_clients_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.audit_events, {
as: 'audit_events_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
//end loop
db.organizations.belongsTo(db.users, {
as: 'createdBy',
});
db.organizations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return organizations;
};

View File

@ -0,0 +1,206 @@
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,
},
method: {
type: DataTypes.ENUM,
values: [
"wallet",
"bank_transfer",
"card",
"qris"
],
},
status: {
type: DataTypes.ENUM,
values: [
"initiated",
"authorized",
"captured",
"failed",
"refunded"
],
},
amount: {
type: DataTypes.DECIMAL,
},
initiated_at: {
type: DataTypes.DATE,
},
captured_at: {
type: DataTypes.DATE,
},
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.orders, {
as: 'order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.payments.belongsTo(db.users, {
as: 'payer',
foreignKey: {
name: 'payerId',
},
constraints: false,
});
db.payments.belongsTo(db.wallet_transactions, {
as: 'wallet_transaction',
foreignKey: {
name: 'wallet_transactionId',
},
constraints: false,
});
db.payments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.payments.belongsTo(db.users, {
as: 'createdBy',
});
db.payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payments;
};

View File

@ -0,0 +1,106 @@
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,172 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const post_engagements = sequelize.define(
'post_engagements',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
engagement_type: {
type: DataTypes.ENUM,
values: [
"view",
"like",
"comment",
"share",
"save"
],
},
comment_text: {
type: DataTypes.TEXT,
},
engaged_at: {
type: DataTypes.DATE,
},
is_reward_eligible: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
post_engagements.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.post_engagements.belongsTo(db.posts, {
as: 'post',
foreignKey: {
name: 'postId',
},
constraints: false,
});
db.post_engagements.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.post_engagements.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.post_engagements.belongsTo(db.users, {
as: 'createdBy',
});
db.post_engagements.belongsTo(db.users, {
as: 'updatedBy',
});
};
return post_engagements;
};

View File

@ -0,0 +1,225 @@
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 posts = sequelize.define(
'posts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
post_type: {
type: DataTypes.ENUM,
values: [
"short_video",
"live_stream",
"text",
"image_gallery"
],
},
caption: {
type: DataTypes.TEXT,
},
visibility: {
type: DataTypes.ENUM,
values: [
"public",
"followers",
"private"
],
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"removed"
],
},
published_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
posts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.posts.hasMany(db.post_engagements, {
as: 'post_engagements_post',
foreignKey: {
name: 'postId',
},
constraints: false,
});
//end loop
db.posts.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.posts.belongsTo(db.deep_dive_links, {
as: 'deep_dive_link',
foreignKey: {
name: 'deep_dive_linkId',
},
constraints: false,
});
db.posts.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.posts.hasMany(db.file, {
as: 'media_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.posts.getTableName(),
belongsToColumn: 'media_images',
},
});
db.posts.hasMany(db.file, {
as: 'media_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.posts.getTableName(),
belongsToColumn: 'media_files',
},
});
db.posts.belongsTo(db.users, {
as: 'createdBy',
});
db.posts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return posts;
};

View File

@ -0,0 +1,152 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const product_categories = sequelize.define(
'product_categories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
category_name: {
type: DataTypes.TEXT,
},
category_slug: {
type: DataTypes.TEXT,
},
visibility: {
type: DataTypes.ENUM,
values: [
"public",
"internal"
],
},
description: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
product_categories.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.product_categories.hasMany(db.products, {
as: 'products_category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
//end loop
db.product_categories.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.product_categories.belongsTo(db.users, {
as: 'createdBy',
});
db.product_categories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return product_categories;
};

View File

@ -0,0 +1,181 @@
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 product_reviews = sequelize.define(
'product_reviews',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
rating: {
type: DataTypes.INTEGER,
},
review_text: {
type: DataTypes.TEXT,
},
moderation_status: {
type: DataTypes.ENUM,
values: [
"visible",
"hidden",
"flagged"
],
},
reviewed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
product_reviews.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.product_reviews.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.product_reviews.belongsTo(db.users, {
as: 'buyer',
foreignKey: {
name: 'buyerId',
},
constraints: false,
});
db.product_reviews.belongsTo(db.orders, {
as: 'order',
foreignKey: {
name: 'orderId',
},
constraints: false,
});
db.product_reviews.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.product_reviews.hasMany(db.file, {
as: 'review_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.product_reviews.getTableName(),
belongsToColumn: 'review_images',
},
});
db.product_reviews.belongsTo(db.users, {
as: 'createdBy',
});
db.product_reviews.belongsTo(db.users, {
as: 'updatedBy',
});
};
return product_reviews;
};

View File

@ -0,0 +1,242 @@
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,
},
description: {
type: DataTypes.TEXT,
},
product_type: {
type: DataTypes.ENUM,
values: [
"physical",
"digital",
"service"
],
},
price: {
type: DataTypes.DECIMAL,
},
cost_price: {
type: DataTypes.DECIMAL,
},
stock_quantity: {
type: DataTypes.INTEGER,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"active",
"out_of_stock",
"archived"
],
},
local_priority_eligible: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
products.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.products.hasMany(db.order_items, {
as: 'order_items_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.product_reviews, {
as: 'product_reviews_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
//end loop
db.products.belongsTo(db.stores, {
as: 'store',
foreignKey: {
name: 'storeId',
},
constraints: false,
});
db.products.belongsTo(db.product_categories, {
as: 'category',
foreignKey: {
name: 'categoryId',
},
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,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 rewards = sequelize.define(
'rewards',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
reward_type: {
type: DataTypes.ENUM,
values: [
"viewer_engagement",
"creator_bonus",
"referral_bonus",
"research_contribution",
"moderation_bounty"
],
},
points_amount: {
type: DataTypes.INTEGER,
},
cash_value_amount: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"available",
"redeemed",
"expired",
"revoked"
],
},
awarded_at: {
type: DataTypes.DATE,
},
expires_at: {
type: DataTypes.DATE,
},
reason_note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
rewards.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.rewards.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.rewards.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.rewards.belongsTo(db.users, {
as: 'createdBy',
});
db.rewards.belongsTo(db.users, {
as: 'updatedBy',
});
};
return rewards;
};

View File

@ -0,0 +1,149 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const 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;
};

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