Initial version

This commit is contained in:
Flatlogic Bot 2026-02-24 14:16:25 +00:00
commit b94ceaf876
719 changed files with 254865 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>Xpansion Creator Platform</h2>
<p>Creator platform for discovery, tipping, alerts, overlays, and merch with customizable dark RGB themes.</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 @@
# Xpansion Creator Platform
## This project was generated by [Flatlogic Platform](https://flatlogic.com).
- Frontend: [React.js](https://flatlogic.com/templates?framework%5B%5D=react&sort=default)
- Backend: [NodeJS](https://flatlogic.com/templates?backend%5B%5D=nodejs&sort=default)
<details><summary>Backend Folder Structure</summary>
The generated application has the following backend folder structure:
`src` folder which contains your working files that will be used later to create the build. The src folder contains folders as:
- `auth` - config the library for authentication and authorization;
- `db` - contains such folders as:
- `api` - documentation that is automatically generated by jsdoc or other tools;
- `migrations` - is a skeleton of the database or all the actions that users do with the database;
- `models`- what will represent the database for the backend;
- `seeders` - the entity that creates the data for the database.
- `routes` - this folder would contain all the routes that you have created using Express Router and what they do would be exported from a Controller file;
- `services` - contains such folders as `emails` and `notifications`.
</details>
- Database: PostgreSQL
- app-shel: Core application framework that provides essential infrastructure services
for the entire application.
-----------------------
### We offer 2 ways how to start the project locally: by running Frontend and Backend or with Docker.
-----------------------
## To start the project:
### Backend:
> Please change current folder: `cd backend`
#### Install local dependencies:
`yarn install`
------------
#### Adjust local db:
##### 1. Install postgres:
MacOS:
`brew install postgres`
> if you dont have brew please install it (https://brew.sh) and repeat step `brew install postgres`.
Ubuntu:
`sudo apt update`
`sudo apt install postgresql postgresql-contrib`
##### 2. Create db and admin user:
Before run and test connection, make sure you have created a database as described in the above configuration. You can use the `psql` command to create a user and database.
`psql postgres --u postgres`
Next, type this command for creating a new user with password then give access for creating the database.
`postgres-# CREATE ROLE admin WITH LOGIN PASSWORD 'admin_pass';`
`postgres-# ALTER ROLE admin CREATEDB;`
Quit `psql` then log in again using the new user that previously created.
`postgres-# \q`
`psql postgres -U admin`
Type this command to creating a new database.
`postgres=> CREATE DATABASE db_{your_project_name};`
Then give that new user privileges to the new database then quit the `psql`.
`postgres=> GRANT ALL PRIVILEGES ON DATABASE db_{your_project_name} TO admin;`
`postgres=> \q`
------------
#### Create database:
`yarn db:create`
#### Start production build:
`yarn start`
### Frontend:
> Please change current folder: `cd frontend`
## To start the project with Docker:
### Description:
The project contains the **docker folder** and the `Dockerfile`.
The `Dockerfile` is used to Deploy the project to Google Cloud.
The **docker folder** contains a couple of helper scripts:
- `docker-compose.yml` (all our services: web, backend, db are described here)
- `start-backend.sh` (starts backend, but only after the database)
- `wait-for-it.sh` (imported from https://github.com/vishnubob/wait-for-it)
> To avoid breaking the application, we recommend you don't edit the following files: everything that includes the **docker folder** and `Dokerfile`.
## Run services:
1. Install docker compose (https://docs.docker.com/compose/install/)
2. Move to `docker` folder. All next steps should be done from this folder.
``` cd docker ```
3. Make executables from `wait-for-it.sh` and `start-backend.sh`:
``` chmod +x start-backend.sh && chmod +x wait-for-it.sh ```
4. Download dependend projects for services.
5. Review the docker-compose.yml file. Make sure that all services have Dockerfiles. Only db service doesn't require a Dockerfile.
6. Make sure you have needed ports (see them in `ports`) available on your local machine.
7. Start services:
7.1. With an empty database `rm -rf data && docker-compose up`
7.2. With a stored (from previus runs) database data `docker-compose up`
8. Check http://localhost:3000
9. Stop services:
9.1. Just press `Ctr+C`
## Most common errors:
1. `connection refused`
There could be many reasons, but the most common are:
- The port is not open on the destination machine.
- The port is open on the destination machine, but its backlog of pending connections is full.
- A firewall between the client and server is blocking access (also check local firewalls).
After checking for firewalls and that the port is open, use telnet to connect to the IP/port to test connectivity. This removes any potential issues from your application.
***MacOS:***
If you suspect that your SSH service might be down, you can run this command to find out:
`sudo service ssh status`
If the command line returns a status of down, then youve likely found the reason behind your connectivity error.
***Ubuntu:***
Sometimes a connection refused error can also indicate that there is an IP address conflict on your network. You can search for possible IP conflicts by running:
`arp-scan -I eth0 -l | grep <ipaddress>`
`arp-scan -I eth0 -l | grep <ipaddress>`
and
`arping <ipaddress>`
2. `yarn db:create` creates database with the assembled tables (on MacOS with Postgres database)
The workaround - put the next commands to your Postgres database terminal:
`DROP SCHEMA public CASCADE;`
`CREATE SCHEMA public;`
`GRANT ALL ON SCHEMA public TO postgres;`
`GRANT ALL ON SCHEMA public TO public;`
Afterwards, continue to start your project in the backend directory by running:
`yarn start`

14
backend/.env Normal file
View File

@ -0,0 +1,14 @@
DB_NAME=app_38738
DB_USER=app_38738
DB_PASS=f96d81e6-8872-4cbc-86b5-98334c9e8273
DB_HOST=127.0.0.1
DB_PORT=5432
PORT=3000
GOOGLE_CLIENT_ID=671001533244-kf1k1gmp6mnl0r030qmvdu6v36ghmim6.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=Yo4qbKZniqvojzUQ60iKlxqR
MS_CLIENT_ID=4696f457-31af-40de-897c-e00d7d4cff73
MS_CLIENT_SECRET=m8jzZ.5UpHF3=-dXzyxiZ4e[F8OF54@p
EMAIL_USER=AKIAVEW7G4PQUBGM52OF
EMAIL_PASS=BLnD4hKGb6YkSz3gaQrf8fnyLi3C3/EdjOOsLEDTDPTz
SECRET_KEY=HUEyqESqgQ1yTwzVlO6wprC9Kf1J1xuA
PEXELS_KEY=Vc99rnmOhHhJAbgGQoKLZtsaIVfkeownoQNbTj78VemUjKh08ZYRbf18

4
backend/.eslintignore Normal file
View File

@ -0,0 +1,4 @@
# Ignore generated and runtime files
node_modules/
tmp/
logs/

15
backend/.eslintrc.cjs Normal file
View File

@ -0,0 +1,15 @@
module.exports = {
env: {
node: true,
es2021: true
},
extends: [
'eslint:recommended'
],
plugins: [
'import'
],
rules: {
'import/no-unresolved': 'error'
}
};

11
backend/.prettierrc Normal file
View File

@ -0,0 +1,11 @@
{
"singleQuote": true,
"tabWidth": 2,
"printWidth": 80,
"trailingComma": "all",
"quoteProps": "as-needed",
"jsxSingleQuote": true,
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always"
}

7
backend/.sequelizerc Normal file
View File

@ -0,0 +1,7 @@
const path = require('path');
module.exports = {
"config": path.resolve("src", "db", "db.config.js"),
"models-path": path.resolve("src", "db", "models"),
"seeders-path": path.resolve("src", "db", "seeders"),
"migrations-path": path.resolve("src", "db", "migrations")
};

23
backend/Dockerfile Normal file
View File

@ -0,0 +1,23 @@
FROM node:20.15.1-alpine
RUN apk update && apk add bash
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN yarn install
# If you are building your code for production
# RUN npm ci --only=production
# Bundle app source
COPY . .
EXPOSE 8080
CMD [ "yarn", "start" ]

56
backend/README.md Normal file
View File

@ -0,0 +1,56 @@
#Xpansion Creator Platform - 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_xpansion_creator_platform;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_xpansion_creator_platform 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": "xpansioncreatorplatform",
"description": "Xpansion Creator Platform - 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: "f96d81e6",
user_pass: "98334c9e8273",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'f96d81e6-8872-4cbc-86b5-98334c9e8273',
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: 'Xpansion Creator Platform <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: 'FanSupport',
},
project_uuid: 'f96d81e6-8872-4cbc-86b5-98334c9e8273',
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 = 'Neon-lit city street at 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,630 @@
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 Alert_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const alert_profiles = await db.alert_profiles.create(
{
id: data.id || undefined,
profile_name: data.profile_name
||
null
,
brand_primary_hex: data.brand_primary_hex
||
null
,
brand_accent_hex: data.brand_accent_hex
||
null
,
animation_style: data.animation_style
||
null
,
tts_enabled: data.tts_enabled
||
false
,
tts_voice: data.tts_voice
||
null
,
template_style: data.template_style
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await alert_profiles.setOwner_user( data.owner_user || null, {
transaction,
});
await alert_profiles.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.alert_profiles.getTableName(),
belongsToColumn: 'default_sound_files',
belongsToId: alert_profiles.id,
},
data.default_sound_files,
options,
);
return alert_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 alert_profilesData = data.map((item, index) => ({
id: item.id || undefined,
profile_name: item.profile_name
||
null
,
brand_primary_hex: item.brand_primary_hex
||
null
,
brand_accent_hex: item.brand_accent_hex
||
null
,
animation_style: item.animation_style
||
null
,
tts_enabled: item.tts_enabled
||
false
,
tts_voice: item.tts_voice
||
null
,
template_style: item.template_style
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const alert_profiles = await db.alert_profiles.bulkCreate(alert_profilesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < alert_profiles.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.alert_profiles.getTableName(),
belongsToColumn: 'default_sound_files',
belongsToId: alert_profiles[i].id,
},
data[i].default_sound_files,
options,
);
}
return alert_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 alert_profiles = await db.alert_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.profile_name !== undefined) updatePayload.profile_name = data.profile_name;
if (data.brand_primary_hex !== undefined) updatePayload.brand_primary_hex = data.brand_primary_hex;
if (data.brand_accent_hex !== undefined) updatePayload.brand_accent_hex = data.brand_accent_hex;
if (data.animation_style !== undefined) updatePayload.animation_style = data.animation_style;
if (data.tts_enabled !== undefined) updatePayload.tts_enabled = data.tts_enabled;
if (data.tts_voice !== undefined) updatePayload.tts_voice = data.tts_voice;
if (data.template_style !== undefined) updatePayload.template_style = data.template_style;
updatePayload.updatedById = currentUser.id;
await alert_profiles.update(updatePayload, {transaction});
if (data.owner_user !== undefined) {
await alert_profiles.setOwner_user(
data.owner_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await alert_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.alert_profiles.getTableName(),
belongsToColumn: 'default_sound_files',
belongsToId: alert_profiles.id,
},
data.default_sound_files,
options,
);
return alert_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const alert_profiles = await db.alert_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of alert_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of alert_profiles) {
await record.destroy({transaction});
}
});
return alert_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const alert_profiles = await db.alert_profiles.findByPk(id, options);
await alert_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await alert_profiles.destroy({
transaction
});
return alert_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const alert_profiles = await db.alert_profiles.findOne(
{ where },
{ transaction },
);
if (!alert_profiles) {
return alert_profiles;
}
const output = alert_profiles.get({plain: true});
output.alerts_alert_profile = await alert_profiles.getAlerts_alert_profile({
transaction
});
output.owner_user = await alert_profiles.getOwner_user({
transaction
});
output.default_sound_files = await alert_profiles.getDefault_sound_files({
transaction
});
output.organizations = await alert_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.users,
as: 'owner_user',
where: filter.owner_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'default_sound_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.profile_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'alert_profiles',
'profile_name',
filter.profile_name,
),
};
}
if (filter.brand_primary_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'alert_profiles',
'brand_primary_hex',
filter.brand_primary_hex,
),
};
}
if (filter.brand_accent_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'alert_profiles',
'brand_accent_hex',
filter.brand_accent_hex,
),
};
}
if (filter.tts_voice) {
where = {
...where,
[Op.and]: Utils.ilike(
'alert_profiles',
'tts_voice',
filter.tts_voice,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.animation_style) {
where = {
...where,
animation_style: filter.animation_style,
};
}
if (filter.tts_enabled) {
where = {
...where,
tts_enabled: filter.tts_enabled,
};
}
if (filter.template_style) {
where = {
...where,
template_style: filter.template_style,
};
}
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.alert_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(
'alert_profiles',
'profile_name',
query,
),
],
};
}
const records = await db.alert_profiles.findAll({
attributes: [ 'id', 'profile_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['profile_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.profile_name,
}));
}
};

View File

@ -0,0 +1,770 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class AlertsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const alerts = await db.alerts.create(
{
id: data.id || undefined,
alert_type: data.alert_type
||
null
,
title: data.title
||
null
,
body: data.body
||
null
,
amount: data.amount
||
null
,
currency: data.currency
||
null
,
status: data.status
||
null
,
created_at_time: data.created_at_time
||
null
,
shown_at: data.shown_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await alerts.setCreator( data.creator || null, {
transaction,
});
await alerts.setAlert_profile( data.alert_profile || null, {
transaction,
});
await alerts.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.alerts.getTableName(),
belongsToColumn: 'media_images',
belongsToId: alerts.id,
},
data.media_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.alerts.getTableName(),
belongsToColumn: 'sound_files',
belongsToId: alerts.id,
},
data.sound_files,
options,
);
return alerts;
}
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 alertsData = data.map((item, index) => ({
id: item.id || undefined,
alert_type: item.alert_type
||
null
,
title: item.title
||
null
,
body: item.body
||
null
,
amount: item.amount
||
null
,
currency: item.currency
||
null
,
status: item.status
||
null
,
created_at_time: item.created_at_time
||
null
,
shown_at: item.shown_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const alerts = await db.alerts.bulkCreate(alertsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < alerts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.alerts.getTableName(),
belongsToColumn: 'media_images',
belongsToId: alerts[i].id,
},
data[i].media_images,
options,
);
}
for (let i = 0; i < alerts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.alerts.getTableName(),
belongsToColumn: 'sound_files',
belongsToId: alerts[i].id,
},
data[i].sound_files,
options,
);
}
return alerts;
}
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 alerts = await db.alerts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.alert_type !== undefined) updatePayload.alert_type = data.alert_type;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.created_at_time !== undefined) updatePayload.created_at_time = data.created_at_time;
if (data.shown_at !== undefined) updatePayload.shown_at = data.shown_at;
updatePayload.updatedById = currentUser.id;
await alerts.update(updatePayload, {transaction});
if (data.creator !== undefined) {
await alerts.setCreator(
data.creator,
{ transaction }
);
}
if (data.alert_profile !== undefined) {
await alerts.setAlert_profile(
data.alert_profile,
{ transaction }
);
}
if (data.organizations !== undefined) {
await alerts.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.alerts.getTableName(),
belongsToColumn: 'media_images',
belongsToId: alerts.id,
},
data.media_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.alerts.getTableName(),
belongsToColumn: 'sound_files',
belongsToId: alerts.id,
},
data.sound_files,
options,
);
return alerts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const alerts = await db.alerts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of alerts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of alerts) {
await record.destroy({transaction});
}
});
return alerts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const alerts = await db.alerts.findByPk(id, options);
await alerts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await alerts.destroy({
transaction
});
return alerts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const alerts = await db.alerts.findOne(
{ where },
{ transaction },
);
if (!alerts) {
return alerts;
}
const output = alerts.get({plain: true});
output.creator = await alerts.getCreator({
transaction
});
output.alert_profile = await alerts.getAlert_profile({
transaction
});
output.media_images = await alerts.getMedia_images({
transaction
});
output.sound_files = await alerts.getSound_files({
transaction
});
output.organizations = await alerts.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.creator_profiles,
as: 'creator',
where: filter.creator ? {
[Op.or]: [
{ id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
{
handle: {
[Op.or]: filter.creator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.alert_profiles,
as: 'alert_profile',
where: filter.alert_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.alert_profile.split('|').map(term => Utils.uuid(term)) } },
{
profile_name: {
[Op.or]: filter.alert_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'media_images',
},
{
model: db.file,
as: 'sound_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'alerts',
'title',
filter.title,
),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'alerts',
'body',
filter.body,
),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'alerts',
'currency',
filter.currency,
),
};
}
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.created_at_timeRange) {
const [start, end] = filter.created_at_timeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_time: {
...where.created_at_time,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_time: {
...where.created_at_time,
[Op.lte]: end,
},
};
}
}
if (filter.shown_atRange) {
const [start, end] = filter.shown_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
shown_at: {
...where.shown_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
shown_at: {
...where.shown_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.alert_type) {
where = {
...where,
alert_type: filter.alert_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.alerts.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(
'alerts',
'title',
query,
),
],
};
}
const records = await db.alerts.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,553 @@
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 CommentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const comments = await db.comments.create(
{
id: data.id || undefined,
target_type: data.target_type
||
null
,
target_key: data.target_key
||
null
,
body: data.body
||
null
,
posted_at: data.posted_at
||
null
,
is_hidden: data.is_hidden
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await comments.setAuthor_user( data.author_user || null, {
transaction,
});
await comments.setOrganizations( data.organizations || null, {
transaction,
});
return comments;
}
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 commentsData = data.map((item, index) => ({
id: item.id || undefined,
target_type: item.target_type
||
null
,
target_key: item.target_key
||
null
,
body: item.body
||
null
,
posted_at: item.posted_at
||
null
,
is_hidden: item.is_hidden
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const comments = await db.comments.bulkCreate(commentsData, { transaction });
// For each item created, replace relation files
return comments;
}
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 comments = await db.comments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.target_type !== undefined) updatePayload.target_type = data.target_type;
if (data.target_key !== undefined) updatePayload.target_key = data.target_key;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
if (data.is_hidden !== undefined) updatePayload.is_hidden = data.is_hidden;
updatePayload.updatedById = currentUser.id;
await comments.update(updatePayload, {transaction});
if (data.author_user !== undefined) {
await comments.setAuthor_user(
data.author_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await comments.setOrganizations(
data.organizations,
{ transaction }
);
}
return comments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const comments = await db.comments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of comments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of comments) {
await record.destroy({transaction});
}
});
return comments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const comments = await db.comments.findByPk(id, options);
await comments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await comments.destroy({
transaction
});
return comments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const comments = await db.comments.findOne(
{ where },
{ transaction },
);
if (!comments) {
return comments;
}
const output = comments.get({plain: true});
output.author_user = await comments.getAuthor_user({
transaction
});
output.organizations = await comments.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_user',
where: filter.author_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.author_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.target_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'comments',
'target_key',
filter.target_key,
),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'comments',
'body',
filter.body,
),
};
}
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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.target_type) {
where = {
...where,
target_type: filter.target_type,
};
}
if (filter.is_hidden) {
where = {
...where,
is_hidden: filter.is_hidden,
};
}
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.comments.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(
'comments',
'body',
query,
),
],
};
}
const records = await db.comments.findAll({
attributes: [ 'id', 'body' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['body', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.body,
}));
}
};

View File

@ -0,0 +1,805 @@
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 Creator_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const creator_profiles = await db.creator_profiles.create(
{
id: data.id || undefined,
handle: data.handle
||
null
,
creator_type: data.creator_type
||
null
,
is_verified: data.is_verified
||
false
,
is_adult_creator: data.is_adult_creator
||
false
,
slogan: data.slogan
||
null
,
about: data.about
||
null
,
business_email: data.business_email
||
null
,
support_email: data.support_email
||
null
,
preferred_language: data.preferred_language
||
null
,
category_tags: data.category_tags
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await creator_profiles.setUser( data.user || null, {
transaction,
});
await creator_profiles.setProfile_style( data.profile_style || null, {
transaction,
});
await creator_profiles.setTip_page( data.tip_page || null, {
transaction,
});
await creator_profiles.setMerch_store( data.merch_store || null, {
transaction,
});
await creator_profiles.setOrganizations( data.organizations || null, {
transaction,
});
return creator_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 creator_profilesData = data.map((item, index) => ({
id: item.id || undefined,
handle: item.handle
||
null
,
creator_type: item.creator_type
||
null
,
is_verified: item.is_verified
||
false
,
is_adult_creator: item.is_adult_creator
||
false
,
slogan: item.slogan
||
null
,
about: item.about
||
null
,
business_email: item.business_email
||
null
,
support_email: item.support_email
||
null
,
preferred_language: item.preferred_language
||
null
,
category_tags: item.category_tags
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const creator_profiles = await db.creator_profiles.bulkCreate(creator_profilesData, { transaction });
// For each item created, replace relation files
return creator_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 creator_profiles = await db.creator_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.handle !== undefined) updatePayload.handle = data.handle;
if (data.creator_type !== undefined) updatePayload.creator_type = data.creator_type;
if (data.is_verified !== undefined) updatePayload.is_verified = data.is_verified;
if (data.is_adult_creator !== undefined) updatePayload.is_adult_creator = data.is_adult_creator;
if (data.slogan !== undefined) updatePayload.slogan = data.slogan;
if (data.about !== undefined) updatePayload.about = data.about;
if (data.business_email !== undefined) updatePayload.business_email = data.business_email;
if (data.support_email !== undefined) updatePayload.support_email = data.support_email;
if (data.preferred_language !== undefined) updatePayload.preferred_language = data.preferred_language;
if (data.category_tags !== undefined) updatePayload.category_tags = data.category_tags;
updatePayload.updatedById = currentUser.id;
await creator_profiles.update(updatePayload, {transaction});
if (data.user !== undefined) {
await creator_profiles.setUser(
data.user,
{ transaction }
);
}
if (data.profile_style !== undefined) {
await creator_profiles.setProfile_style(
data.profile_style,
{ transaction }
);
}
if (data.tip_page !== undefined) {
await creator_profiles.setTip_page(
data.tip_page,
{ transaction }
);
}
if (data.merch_store !== undefined) {
await creator_profiles.setMerch_store(
data.merch_store,
{ transaction }
);
}
if (data.organizations !== undefined) {
await creator_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
return creator_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const creator_profiles = await db.creator_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of creator_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of creator_profiles) {
await record.destroy({transaction});
}
});
return creator_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const creator_profiles = await db.creator_profiles.findByPk(id, options);
await creator_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await creator_profiles.destroy({
transaction
});
return creator_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const creator_profiles = await db.creator_profiles.findOne(
{ where },
{ transaction },
);
if (!creator_profiles) {
return creator_profiles;
}
const output = creator_profiles.get({plain: true});
output.follows_followed_creator = await creator_profiles.getFollows_followed_creator({
transaction
});
output.discovery_items_creator = await creator_profiles.getDiscovery_items_creator({
transaction
});
output.streams_creator = await creator_profiles.getStreams_creator({
transaction
});
output.videos_creator = await creator_profiles.getVideos_creator({
transaction
});
output.tip_pages_creator = await creator_profiles.getTip_pages_creator({
transaction
});
output.alerts_creator = await creator_profiles.getAlerts_creator({
transaction
});
output.overlay_profiles_creator = await creator_profiles.getOverlay_profiles_creator({
transaction
});
output.merch_stores_creator = await creator_profiles.getMerch_stores_creator({
transaction
});
output.private_mailboxes_owner_creator = await creator_profiles.getPrivate_mailboxes_owner_creator({
transaction
});
output.user = await creator_profiles.getUser({
transaction
});
output.profile_style = await creator_profiles.getProfile_style({
transaction
});
output.tip_page = await creator_profiles.getTip_page({
transaction
});
output.merch_store = await creator_profiles.getMerch_store({
transaction
});
output.organizations = await creator_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.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.profile_styles,
as: 'profile_style',
where: filter.profile_style ? {
[Op.or]: [
{ id: { [Op.in]: filter.profile_style.split('|').map(term => Utils.uuid(term)) } },
{
style_name: {
[Op.or]: filter.profile_style.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.tip_pages,
as: 'tip_page',
where: filter.tip_page ? {
[Op.or]: [
{ id: { [Op.in]: filter.tip_page.split('|').map(term => Utils.uuid(term)) } },
{
slug: {
[Op.or]: filter.tip_page.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.merch_stores,
as: 'merch_store',
where: filter.merch_store ? {
[Op.or]: [
{ id: { [Op.in]: filter.merch_store.split('|').map(term => Utils.uuid(term)) } },
{
store_name: {
[Op.or]: filter.merch_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.handle) {
where = {
...where,
[Op.and]: Utils.ilike(
'creator_profiles',
'handle',
filter.handle,
),
};
}
if (filter.slogan) {
where = {
...where,
[Op.and]: Utils.ilike(
'creator_profiles',
'slogan',
filter.slogan,
),
};
}
if (filter.about) {
where = {
...where,
[Op.and]: Utils.ilike(
'creator_profiles',
'about',
filter.about,
),
};
}
if (filter.business_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'creator_profiles',
'business_email',
filter.business_email,
),
};
}
if (filter.support_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'creator_profiles',
'support_email',
filter.support_email,
),
};
}
if (filter.preferred_language) {
where = {
...where,
[Op.and]: Utils.ilike(
'creator_profiles',
'preferred_language',
filter.preferred_language,
),
};
}
if (filter.category_tags) {
where = {
...where,
[Op.and]: Utils.ilike(
'creator_profiles',
'category_tags',
filter.category_tags,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.creator_type) {
where = {
...where,
creator_type: filter.creator_type,
};
}
if (filter.is_verified) {
where = {
...where,
is_verified: filter.is_verified,
};
}
if (filter.is_adult_creator) {
where = {
...where,
is_adult_creator: filter.is_adult_creator,
};
}
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.creator_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(
'creator_profiles',
'handle',
query,
),
],
};
}
const records = await db.creator_profiles.findAll({
attributes: [ 'id', 'handle' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['handle', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.handle,
}));
}
};

View File

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

View File

@ -0,0 +1,630 @@
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 Discovery_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const discovery_items = await db.discovery_items.create(
{
id: data.id || undefined,
item_type: data.item_type
||
null
,
title: data.title
||
null
,
subtitle: data.subtitle
||
null
,
score: data.score
||
null
,
status: data.status
||
null
,
published_at: data.published_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await discovery_items.setCreator( data.creator || null, {
transaction,
});
await discovery_items.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.discovery_items.getTableName(),
belongsToColumn: 'thumbnail_images',
belongsToId: discovery_items.id,
},
data.thumbnail_images,
options,
);
return discovery_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 discovery_itemsData = data.map((item, index) => ({
id: item.id || undefined,
item_type: item.item_type
||
null
,
title: item.title
||
null
,
subtitle: item.subtitle
||
null
,
score: item.score
||
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 discovery_items = await db.discovery_items.bulkCreate(discovery_itemsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < discovery_items.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.discovery_items.getTableName(),
belongsToColumn: 'thumbnail_images',
belongsToId: discovery_items[i].id,
},
data[i].thumbnail_images,
options,
);
}
return discovery_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 discovery_items = await db.discovery_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.subtitle !== undefined) updatePayload.subtitle = data.subtitle;
if (data.score !== undefined) updatePayload.score = data.score;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
updatePayload.updatedById = currentUser.id;
await discovery_items.update(updatePayload, {transaction});
if (data.creator !== undefined) {
await discovery_items.setCreator(
data.creator,
{ transaction }
);
}
if (data.organizations !== undefined) {
await discovery_items.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.discovery_items.getTableName(),
belongsToColumn: 'thumbnail_images',
belongsToId: discovery_items.id,
},
data.thumbnail_images,
options,
);
return discovery_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const discovery_items = await db.discovery_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of discovery_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of discovery_items) {
await record.destroy({transaction});
}
});
return discovery_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const discovery_items = await db.discovery_items.findByPk(id, options);
await discovery_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await discovery_items.destroy({
transaction
});
return discovery_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const discovery_items = await db.discovery_items.findOne(
{ where },
{ transaction },
);
if (!discovery_items) {
return discovery_items;
}
const output = discovery_items.get({plain: true});
output.creator = await discovery_items.getCreator({
transaction
});
output.thumbnail_images = await discovery_items.getThumbnail_images({
transaction
});
output.organizations = await discovery_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.creator_profiles,
as: 'creator',
where: filter.creator ? {
[Op.or]: [
{ id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
{
handle: {
[Op.or]: filter.creator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'thumbnail_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'discovery_items',
'title',
filter.title,
),
};
}
if (filter.subtitle) {
where = {
...where,
[Op.and]: Utils.ilike(
'discovery_items',
'subtitle',
filter.subtitle,
),
};
}
if (filter.scoreRange) {
const [start, end] = filter.scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score: {
...where.score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score: {
...where.score,
[Op.lte]: end,
},
};
}
}
if (filter.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.item_type) {
where = {
...where,
item_type: filter.item_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.discovery_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(
'discovery_items',
'title',
query,
),
],
};
}
const records = await db.discovery_items.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,555 @@
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 Fan_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const fan_profiles = await db.fan_profiles.create(
{
id: data.id || undefined,
nickname: data.nickname
||
null
,
bio: data.bio
||
null
,
hide_social_activity: data.hide_social_activity
||
false
,
xp_coins_balance: data.xp_coins_balance
||
null
,
adult_mode_enabled: data.adult_mode_enabled
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await fan_profiles.setUser( data.user || null, {
transaction,
});
await fan_profiles.setOrganizations( data.organizations || null, {
transaction,
});
return fan_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 fan_profilesData = data.map((item, index) => ({
id: item.id || undefined,
nickname: item.nickname
||
null
,
bio: item.bio
||
null
,
hide_social_activity: item.hide_social_activity
||
false
,
xp_coins_balance: item.xp_coins_balance
||
null
,
adult_mode_enabled: item.adult_mode_enabled
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const fan_profiles = await db.fan_profiles.bulkCreate(fan_profilesData, { transaction });
// For each item created, replace relation files
return fan_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 fan_profiles = await db.fan_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.nickname !== undefined) updatePayload.nickname = data.nickname;
if (data.bio !== undefined) updatePayload.bio = data.bio;
if (data.hide_social_activity !== undefined) updatePayload.hide_social_activity = data.hide_social_activity;
if (data.xp_coins_balance !== undefined) updatePayload.xp_coins_balance = data.xp_coins_balance;
if (data.adult_mode_enabled !== undefined) updatePayload.adult_mode_enabled = data.adult_mode_enabled;
updatePayload.updatedById = currentUser.id;
await fan_profiles.update(updatePayload, {transaction});
if (data.user !== undefined) {
await fan_profiles.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await fan_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
return fan_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const fan_profiles = await db.fan_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of fan_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of fan_profiles) {
await record.destroy({transaction});
}
});
return fan_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const fan_profiles = await db.fan_profiles.findByPk(id, options);
await fan_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await fan_profiles.destroy({
transaction
});
return fan_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const fan_profiles = await db.fan_profiles.findOne(
{ where },
{ transaction },
);
if (!fan_profiles) {
return fan_profiles;
}
const output = fan_profiles.get({plain: true});
output.user = await fan_profiles.getUser({
transaction
});
output.organizations = await fan_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.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.nickname) {
where = {
...where,
[Op.and]: Utils.ilike(
'fan_profiles',
'nickname',
filter.nickname,
),
};
}
if (filter.bio) {
where = {
...where,
[Op.and]: Utils.ilike(
'fan_profiles',
'bio',
filter.bio,
),
};
}
if (filter.xp_coins_balanceRange) {
const [start, end] = filter.xp_coins_balanceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
xp_coins_balance: {
...where.xp_coins_balance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
xp_coins_balance: {
...where.xp_coins_balance,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.hide_social_activity) {
where = {
...where,
hide_social_activity: filter.hide_social_activity,
};
}
if (filter.adult_mode_enabled) {
where = {
...where,
adult_mode_enabled: filter.adult_mode_enabled,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.fan_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(
'fan_profiles',
'nickname',
query,
),
],
};
}
const records = await db.fan_profiles.findAll({
attributes: [ 'id', 'nickname' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['nickname', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.nickname,
}));
}
};

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,522 @@
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 FollowsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const follows = await db.follows.create(
{
id: data.id || undefined,
followed_at: data.followed_at
||
null
,
notifications_enabled: data.notifications_enabled
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await follows.setFollower_user( data.follower_user || null, {
transaction,
});
await follows.setFollowed_creator( data.followed_creator || null, {
transaction,
});
await follows.setOrganizations( data.organizations || null, {
transaction,
});
return follows;
}
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 followsData = data.map((item, index) => ({
id: item.id || undefined,
followed_at: item.followed_at
||
null
,
notifications_enabled: item.notifications_enabled
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const follows = await db.follows.bulkCreate(followsData, { transaction });
// For each item created, replace relation files
return follows;
}
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 follows = await db.follows.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.followed_at !== undefined) updatePayload.followed_at = data.followed_at;
if (data.notifications_enabled !== undefined) updatePayload.notifications_enabled = data.notifications_enabled;
updatePayload.updatedById = currentUser.id;
await follows.update(updatePayload, {transaction});
if (data.follower_user !== undefined) {
await follows.setFollower_user(
data.follower_user,
{ transaction }
);
}
if (data.followed_creator !== undefined) {
await follows.setFollowed_creator(
data.followed_creator,
{ transaction }
);
}
if (data.organizations !== undefined) {
await follows.setOrganizations(
data.organizations,
{ transaction }
);
}
return follows;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const follows = await db.follows.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of follows) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of follows) {
await record.destroy({transaction});
}
});
return follows;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const follows = await db.follows.findByPk(id, options);
await follows.update({
deletedBy: currentUser.id
}, {
transaction,
});
await follows.destroy({
transaction
});
return follows;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const follows = await db.follows.findOne(
{ where },
{ transaction },
);
if (!follows) {
return follows;
}
const output = follows.get({plain: true});
output.follower_user = await follows.getFollower_user({
transaction
});
output.followed_creator = await follows.getFollowed_creator({
transaction
});
output.organizations = await follows.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: 'follower_user',
where: filter.follower_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.follower_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.follower_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.creator_profiles,
as: 'followed_creator',
where: filter.followed_creator ? {
[Op.or]: [
{ id: { [Op.in]: filter.followed_creator.split('|').map(term => Utils.uuid(term)) } },
{
handle: {
[Op.or]: filter.followed_creator.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.followed_atRange) {
const [start, end] = filter.followed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
followed_at: {
...where.followed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
followed_at: {
...where.followed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.notifications_enabled) {
where = {
...where,
notifications_enabled: filter.notifications_enabled,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.follows.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(
'follows',
'followed_at',
query,
),
],
};
}
const records = await db.follows.findAll({
attributes: [ 'id', 'followed_at' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['followed_at', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.followed_at,
}));
}
};

View File

@ -0,0 +1,620 @@
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 Merch_storesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const merch_stores = await db.merch_stores.create(
{
id: data.id || undefined,
store_name: data.store_name
||
null
,
store_description: data.store_description
||
null
,
is_active: data.is_active
||
false
,
policies_text: data.policies_text
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await merch_stores.setCreator( data.creator || null, {
transaction,
});
await merch_stores.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.merch_stores.getTableName(),
belongsToColumn: 'logo_images',
belongsToId: merch_stores.id,
},
data.logo_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.merch_stores.getTableName(),
belongsToColumn: 'banner_images',
belongsToId: merch_stores.id,
},
data.banner_images,
options,
);
return merch_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 merch_storesData = data.map((item, index) => ({
id: item.id || undefined,
store_name: item.store_name
||
null
,
store_description: item.store_description
||
null
,
is_active: item.is_active
||
false
,
policies_text: item.policies_text
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const merch_stores = await db.merch_stores.bulkCreate(merch_storesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < merch_stores.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.merch_stores.getTableName(),
belongsToColumn: 'logo_images',
belongsToId: merch_stores[i].id,
},
data[i].logo_images,
options,
);
}
for (let i = 0; i < merch_stores.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.merch_stores.getTableName(),
belongsToColumn: 'banner_images',
belongsToId: merch_stores[i].id,
},
data[i].banner_images,
options,
);
}
return merch_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 merch_stores = await db.merch_stores.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.store_name !== undefined) updatePayload.store_name = data.store_name;
if (data.store_description !== undefined) updatePayload.store_description = data.store_description;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.policies_text !== undefined) updatePayload.policies_text = data.policies_text;
updatePayload.updatedById = currentUser.id;
await merch_stores.update(updatePayload, {transaction});
if (data.creator !== undefined) {
await merch_stores.setCreator(
data.creator,
{ transaction }
);
}
if (data.organizations !== undefined) {
await merch_stores.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.merch_stores.getTableName(),
belongsToColumn: 'logo_images',
belongsToId: merch_stores.id,
},
data.logo_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.merch_stores.getTableName(),
belongsToColumn: 'banner_images',
belongsToId: merch_stores.id,
},
data.banner_images,
options,
);
return merch_stores;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const merch_stores = await db.merch_stores.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of merch_stores) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of merch_stores) {
await record.destroy({transaction});
}
});
return merch_stores;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const merch_stores = await db.merch_stores.findByPk(id, options);
await merch_stores.update({
deletedBy: currentUser.id
}, {
transaction,
});
await merch_stores.destroy({
transaction
});
return merch_stores;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const merch_stores = await db.merch_stores.findOne(
{ where },
{ transaction },
);
if (!merch_stores) {
return merch_stores;
}
const output = merch_stores.get({plain: true});
output.creator_profiles_merch_store = await merch_stores.getCreator_profiles_merch_store({
transaction
});
output.products_merch_store = await merch_stores.getProducts_merch_store({
transaction
});
output.orders_merch_store = await merch_stores.getOrders_merch_store({
transaction
});
output.shipping_profiles_merch_store = await merch_stores.getShipping_profiles_merch_store({
transaction
});
output.creator = await merch_stores.getCreator({
transaction
});
output.logo_images = await merch_stores.getLogo_images({
transaction
});
output.banner_images = await merch_stores.getBanner_images({
transaction
});
output.organizations = await merch_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.creator_profiles,
as: 'creator',
where: filter.creator ? {
[Op.or]: [
{ id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
{
handle: {
[Op.or]: filter.creator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'logo_images',
},
{
model: db.file,
as: 'banner_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.store_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'merch_stores',
'store_name',
filter.store_name,
),
};
}
if (filter.store_description) {
where = {
...where,
[Op.and]: Utils.ilike(
'merch_stores',
'store_description',
filter.store_description,
),
};
}
if (filter.policies_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'merch_stores',
'policies_text',
filter.policies_text,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.merch_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(
'merch_stores',
'store_name',
query,
),
],
};
}
const records = await db.merch_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,610 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class 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,
subject: data.subject
||
null
,
body: data.body
||
null
,
status: data.status
||
null
,
sent_at: data.sent_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await messages.setMailbox( data.mailbox || null, {
transaction,
});
await messages.setFrom_user( data.from_user || null, {
transaction,
});
await messages.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.messages.getTableName(),
belongsToColumn: 'attachment_files',
belongsToId: messages.id,
},
data.attachment_files,
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,
subject: item.subject
||
null
,
body: item.body
||
null
,
status: item.status
||
null
,
sent_at: item.sent_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: 'attachment_files',
belongsToId: messages[i].id,
},
data[i].attachment_files,
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.subject !== undefined) updatePayload.subject = data.subject;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
updatePayload.updatedById = currentUser.id;
await messages.update(updatePayload, {transaction});
if (data.mailbox !== undefined) {
await messages.setMailbox(
data.mailbox,
{ transaction }
);
}
if (data.from_user !== undefined) {
await messages.setFrom_user(
data.from_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await messages.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.messages.getTableName(),
belongsToColumn: 'attachment_files',
belongsToId: messages.id,
},
data.attachment_files,
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.mailbox = await messages.getMailbox({
transaction
});
output.from_user = await messages.getFrom_user({
transaction
});
output.attachment_files = await messages.getAttachment_files({
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.private_mailboxes,
as: 'mailbox',
where: filter.mailbox ? {
[Op.or]: [
{ id: { [Op.in]: filter.mailbox.split('|').map(term => Utils.uuid(term)) } },
{
public_label: {
[Op.or]: filter.mailbox.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'from_user',
where: filter.from_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.from_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.from_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'attachment_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.subject) {
where = {
...where,
[Op.and]: Utils.ilike(
'messages',
'subject',
filter.subject,
),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'messages',
'body',
filter.body,
),
};
}
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.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.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',
'subject',
query,
),
],
};
}
const records = await db.messages.findAll({
attributes: [ 'id', 'subject' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['subject', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.subject,
}));
}
};

View File

@ -0,0 +1,635 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class 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
,
product_name_snapshot: data.product_name_snapshot
||
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.setVariant( data.variant || 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
,
product_name_snapshot: item.product_name_snapshot
||
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.product_name_snapshot !== undefined) updatePayload.product_name_snapshot = data.product_name_snapshot;
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.variant !== undefined) {
await order_items.setVariant(
data.variant,
{ 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.variant = await order_items.getVariant({
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)) } },
{
currency: {
[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)) } },
{
name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.product_variants,
as: 'variant',
where: filter.variant ? {
[Op.or]: [
{ id: { [Op.in]: filter.variant.split('|').map(term => Utils.uuid(term)) } },
{
variant_name: {
[Op.or]: filter.variant.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.product_name_snapshot) {
where = {
...where,
[Op.and]: Utils.ilike(
'order_items',
'product_name_snapshot',
filter.product_name_snapshot,
),
};
}
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',
'product_name_snapshot',
query,
),
],
};
}
const records = await db.order_items.findAll({
attributes: [ 'id', 'product_name_snapshot' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['product_name_snapshot', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.product_name_snapshot,
}));
}
};

View File

@ -0,0 +1,790 @@
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,
subtotal: data.subtotal
||
null
,
shipping_cost: data.shipping_cost
||
null
,
tax_total: data.tax_total
||
null
,
total: data.total
||
null
,
currency: data.currency
||
null
,
status: data.status
||
null
,
payment_method: data.payment_method
||
null
,
placed_at: data.placed_at
||
null
,
paid_at: data.paid_at
||
null
,
fulfilled_at: data.fulfilled_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await orders.setBuyer_user( data.buyer_user || null, {
transaction,
});
await orders.setMerch_store( data.merch_store || 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,
subtotal: item.subtotal
||
null
,
shipping_cost: item.shipping_cost
||
null
,
tax_total: item.tax_total
||
null
,
total: item.total
||
null
,
currency: item.currency
||
null
,
status: item.status
||
null
,
payment_method: item.payment_method
||
null
,
placed_at: item.placed_at
||
null
,
paid_at: item.paid_at
||
null
,
fulfilled_at: item.fulfilled_at
||
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.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
if (data.shipping_cost !== undefined) updatePayload.shipping_cost = data.shipping_cost;
if (data.tax_total !== undefined) updatePayload.tax_total = data.tax_total;
if (data.total !== undefined) updatePayload.total = data.total;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.payment_method !== undefined) updatePayload.payment_method = data.payment_method;
if (data.placed_at !== undefined) updatePayload.placed_at = data.placed_at;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.fulfilled_at !== undefined) updatePayload.fulfilled_at = data.fulfilled_at;
updatePayload.updatedById = currentUser.id;
await orders.update(updatePayload, {transaction});
if (data.buyer_user !== undefined) {
await orders.setBuyer_user(
data.buyer_user,
{ transaction }
);
}
if (data.merch_store !== undefined) {
await orders.setMerch_store(
data.merch_store,
{ 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.buyer_user = await orders.getBuyer_user({
transaction
});
output.merch_store = await orders.getMerch_store({
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_user',
where: filter.buyer_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.buyer_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.buyer_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.merch_stores,
as: 'merch_store',
where: filter.merch_store ? {
[Op.or]: [
{ id: { [Op.in]: filter.merch_store.split('|').map(term => Utils.uuid(term)) } },
{
store_name: {
[Op.or]: filter.merch_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.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'orders',
'currency',
filter.currency,
),
};
}
if (filter.subtotalRange) {
const [start, end] = filter.subtotalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
subtotal: {
...where.subtotal,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
subtotal: {
...where.subtotal,
[Op.lte]: end,
},
};
}
}
if (filter.shipping_costRange) {
const [start, end] = filter.shipping_costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
shipping_cost: {
...where.shipping_cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
shipping_cost: {
...where.shipping_cost,
[Op.lte]: end,
},
};
}
}
if (filter.tax_totalRange) {
const [start, end] = filter.tax_totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tax_total: {
...where.tax_total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tax_total: {
...where.tax_total,
[Op.lte]: end,
},
};
}
}
if (filter.totalRange) {
const [start, end] = filter.totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total: {
...where.total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total: {
...where.total,
[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.fulfilled_atRange) {
const [start, end] = filter.fulfilled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
fulfilled_at: {
...where.fulfilled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
fulfilled_at: {
...where.fulfilled_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.payment_method) {
where = {
...where,
payment_method: filter.payment_method,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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',
'currency',
query,
),
],
};
}
const records = await db.orders.findAll({
attributes: [ 'id', 'currency' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['currency', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.currency,
}));
}
};

View File

@ -0,0 +1,496 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class OrganizationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return organizations;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const organizationsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const organizations = await db.organizations.bulkCreate(organizationsData, { transaction });
// For each item created, replace relation files
return organizations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const organizations = await db.organizations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await organizations.update(updatePayload, {transaction});
return organizations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of organizations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of organizations) {
await record.destroy({transaction});
}
});
return organizations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findByPk(id, options);
await organizations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await organizations.destroy({
transaction
});
return organizations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findOne(
{ where },
{ transaction },
);
if (!organizations) {
return organizations;
}
const output = organizations.get({plain: true});
output.users_organizations = await organizations.getUsers_organizations({
transaction
});
output.creator_profiles_organizations = await organizations.getCreator_profiles_organizations({
transaction
});
output.fan_profiles_organizations = await organizations.getFan_profiles_organizations({
transaction
});
output.follows_organizations = await organizations.getFollows_organizations({
transaction
});
output.theme_profiles_organizations = await organizations.getTheme_profiles_organizations({
transaction
});
output.profile_styles_organizations = await organizations.getProfile_styles_organizations({
transaction
});
output.discovery_items_organizations = await organizations.getDiscovery_items_organizations({
transaction
});
output.streams_organizations = await organizations.getStreams_organizations({
transaction
});
output.videos_organizations = await organizations.getVideos_organizations({
transaction
});
output.comments_organizations = await organizations.getComments_organizations({
transaction
});
output.playlists_organizations = await organizations.getPlaylists_organizations({
transaction
});
output.playlist_items_organizations = await organizations.getPlaylist_items_organizations({
transaction
});
output.tip_pages_organizations = await organizations.getTip_pages_organizations({
transaction
});
output.tips_organizations = await organizations.getTips_organizations({
transaction
});
output.alert_profiles_organizations = await organizations.getAlert_profiles_organizations({
transaction
});
output.alerts_organizations = await organizations.getAlerts_organizations({
transaction
});
output.overlay_profiles_organizations = await organizations.getOverlay_profiles_organizations({
transaction
});
output.widget_catalog_items_organizations = await organizations.getWidget_catalog_items_organizations({
transaction
});
output.overlay_widgets_organizations = await organizations.getOverlay_widgets_organizations({
transaction
});
output.merch_stores_organizations = await organizations.getMerch_stores_organizations({
transaction
});
output.products_organizations = await organizations.getProducts_organizations({
transaction
});
output.product_variants_organizations = await organizations.getProduct_variants_organizations({
transaction
});
output.orders_organizations = await organizations.getOrders_organizations({
transaction
});
output.order_items_organizations = await organizations.getOrder_items_organizations({
transaction
});
output.shipping_profiles_organizations = await organizations.getShipping_profiles_organizations({
transaction
});
output.private_mailboxes_organizations = await organizations.getPrivate_mailboxes_organizations({
transaction
});
output.messages_organizations = await organizations.getMessages_organizations({
transaction
});
output.reports_organizations = await organizations.getReports_organizations({
transaction
});
output.demo_wallets_organizations = await organizations.getDemo_wallets_organizations({
transaction
});
output.wallet_transactions_organizations = await organizations.getWallet_transactions_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,590 @@
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 Overlay_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const overlay_profiles = await db.overlay_profiles.create(
{
id: data.id || undefined,
name: data.name
||
null
,
overlay_type: data.overlay_type
||
null
,
access_token: data.access_token
||
null
,
is_active: data.is_active
||
false
,
canvas_settings_json: data.canvas_settings_json
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await overlay_profiles.setCreator( data.creator || null, {
transaction,
});
await overlay_profiles.setOrganizations( data.organizations || null, {
transaction,
});
await overlay_profiles.setOverlay_widgets(data.overlay_widgets || [], {
transaction,
});
return overlay_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 overlay_profilesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
overlay_type: item.overlay_type
||
null
,
access_token: item.access_token
||
null
,
is_active: item.is_active
||
false
,
canvas_settings_json: item.canvas_settings_json
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const overlay_profiles = await db.overlay_profiles.bulkCreate(overlay_profilesData, { transaction });
// For each item created, replace relation files
return overlay_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 overlay_profiles = await db.overlay_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.overlay_type !== undefined) updatePayload.overlay_type = data.overlay_type;
if (data.access_token !== undefined) updatePayload.access_token = data.access_token;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.canvas_settings_json !== undefined) updatePayload.canvas_settings_json = data.canvas_settings_json;
updatePayload.updatedById = currentUser.id;
await overlay_profiles.update(updatePayload, {transaction});
if (data.creator !== undefined) {
await overlay_profiles.setCreator(
data.creator,
{ transaction }
);
}
if (data.organizations !== undefined) {
await overlay_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.overlay_widgets !== undefined) {
await overlay_profiles.setOverlay_widgets(data.overlay_widgets, { transaction });
}
return overlay_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const overlay_profiles = await db.overlay_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of overlay_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of overlay_profiles) {
await record.destroy({transaction});
}
});
return overlay_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const overlay_profiles = await db.overlay_profiles.findByPk(id, options);
await overlay_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await overlay_profiles.destroy({
transaction
});
return overlay_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const overlay_profiles = await db.overlay_profiles.findOne(
{ where },
{ transaction },
);
if (!overlay_profiles) {
return overlay_profiles;
}
const output = overlay_profiles.get({plain: true});
output.streams_overlay_profile = await overlay_profiles.getStreams_overlay_profile({
transaction
});
output.overlay_widgets_overlay_profile = await overlay_profiles.getOverlay_widgets_overlay_profile({
transaction
});
output.creator = await overlay_profiles.getCreator({
transaction
});
output.overlay_widgets = await overlay_profiles.getOverlay_widgets({
transaction
});
output.organizations = await overlay_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.creator_profiles,
as: 'creator',
where: filter.creator ? {
[Op.or]: [
{ id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
{
handle: {
[Op.or]: filter.creator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.overlay_widgets,
as: 'overlay_widgets',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'overlay_profiles',
'name',
filter.name,
),
};
}
if (filter.access_token) {
where = {
...where,
[Op.and]: Utils.ilike(
'overlay_profiles',
'access_token',
filter.access_token,
),
};
}
if (filter.canvas_settings_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'overlay_profiles',
'canvas_settings_json',
filter.canvas_settings_json,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.overlay_type) {
where = {
...where,
overlay_type: filter.overlay_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.overlay_widgets) {
const searchTerms = filter.overlay_widgets.split('|');
include = [
{
model: db.overlay_widgets,
as: 'overlay_widgets_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
instance_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) {
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.overlay_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(
'overlay_profiles',
'name',
query,
),
],
};
}
const records = await db.overlay_profiles.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,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 Overlay_widgetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const overlay_widgets = await db.overlay_widgets.create(
{
id: data.id || undefined,
instance_name: data.instance_name
||
null
,
config_json: data.config_json
||
null
,
x: data.x
||
null
,
y: data.y
||
null
,
width: data.width
||
null
,
height: data.height
||
null
,
z_index: data.z_index
||
null
,
is_visible: data.is_visible
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await overlay_widgets.setOverlay_profile( data.overlay_profile || null, {
transaction,
});
await overlay_widgets.setCatalog_item( data.catalog_item || null, {
transaction,
});
await overlay_widgets.setOrganizations( data.organizations || null, {
transaction,
});
return overlay_widgets;
}
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 overlay_widgetsData = data.map((item, index) => ({
id: item.id || undefined,
instance_name: item.instance_name
||
null
,
config_json: item.config_json
||
null
,
x: item.x
||
null
,
y: item.y
||
null
,
width: item.width
||
null
,
height: item.height
||
null
,
z_index: item.z_index
||
null
,
is_visible: item.is_visible
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const overlay_widgets = await db.overlay_widgets.bulkCreate(overlay_widgetsData, { transaction });
// For each item created, replace relation files
return overlay_widgets;
}
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 overlay_widgets = await db.overlay_widgets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.instance_name !== undefined) updatePayload.instance_name = data.instance_name;
if (data.config_json !== undefined) updatePayload.config_json = data.config_json;
if (data.x !== undefined) updatePayload.x = data.x;
if (data.y !== undefined) updatePayload.y = data.y;
if (data.width !== undefined) updatePayload.width = data.width;
if (data.height !== undefined) updatePayload.height = data.height;
if (data.z_index !== undefined) updatePayload.z_index = data.z_index;
if (data.is_visible !== undefined) updatePayload.is_visible = data.is_visible;
updatePayload.updatedById = currentUser.id;
await overlay_widgets.update(updatePayload, {transaction});
if (data.overlay_profile !== undefined) {
await overlay_widgets.setOverlay_profile(
data.overlay_profile,
{ transaction }
);
}
if (data.catalog_item !== undefined) {
await overlay_widgets.setCatalog_item(
data.catalog_item,
{ transaction }
);
}
if (data.organizations !== undefined) {
await overlay_widgets.setOrganizations(
data.organizations,
{ transaction }
);
}
return overlay_widgets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const overlay_widgets = await db.overlay_widgets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of overlay_widgets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of overlay_widgets) {
await record.destroy({transaction});
}
});
return overlay_widgets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const overlay_widgets = await db.overlay_widgets.findByPk(id, options);
await overlay_widgets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await overlay_widgets.destroy({
transaction
});
return overlay_widgets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const overlay_widgets = await db.overlay_widgets.findOne(
{ where },
{ transaction },
);
if (!overlay_widgets) {
return overlay_widgets;
}
const output = overlay_widgets.get({plain: true});
output.overlay_profile = await overlay_widgets.getOverlay_profile({
transaction
});
output.catalog_item = await overlay_widgets.getCatalog_item({
transaction
});
output.organizations = await overlay_widgets.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.overlay_profiles,
as: 'overlay_profile',
where: filter.overlay_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.overlay_profile.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.overlay_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.widget_catalog_items,
as: 'catalog_item',
where: filter.catalog_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.catalog_item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.catalog_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.instance_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'overlay_widgets',
'instance_name',
filter.instance_name,
),
};
}
if (filter.config_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'overlay_widgets',
'config_json',
filter.config_json,
),
};
}
if (filter.xRange) {
const [start, end] = filter.xRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
x: {
...where.x,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
x: {
...where.x,
[Op.lte]: end,
},
};
}
}
if (filter.yRange) {
const [start, end] = filter.yRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
y: {
...where.y,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
y: {
...where.y,
[Op.lte]: end,
},
};
}
}
if (filter.widthRange) {
const [start, end] = filter.widthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
width: {
...where.width,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
width: {
...where.width,
[Op.lte]: end,
},
};
}
}
if (filter.heightRange) {
const [start, end] = filter.heightRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
height: {
...where.height,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
height: {
...where.height,
[Op.lte]: end,
},
};
}
}
if (filter.z_indexRange) {
const [start, end] = filter.z_indexRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
z_index: {
...where.z_index,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
z_index: {
...where.z_index,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_visible) {
where = {
...where,
is_visible: filter.is_visible,
};
}
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.overlay_widgets.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(
'overlay_widgets',
'instance_name',
query,
),
],
};
}
const records = await db.overlay_widgets.findAll({
attributes: [ 'id', 'instance_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['instance_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.instance_name,
}));
}
};

View File

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

View File

@ -0,0 +1,544 @@
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 Playlist_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const playlist_items = await db.playlist_items.create(
{
id: data.id || undefined,
item_type: data.item_type
||
null
,
item_key: data.item_key
||
null
,
position: data.position
||
null
,
added_at: data.added_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await playlist_items.setPlaylist( data.playlist || null, {
transaction,
});
await playlist_items.setOrganizations( data.organizations || null, {
transaction,
});
return playlist_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 playlist_itemsData = data.map((item, index) => ({
id: item.id || undefined,
item_type: item.item_type
||
null
,
item_key: item.item_key
||
null
,
position: item.position
||
null
,
added_at: item.added_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const playlist_items = await db.playlist_items.bulkCreate(playlist_itemsData, { transaction });
// For each item created, replace relation files
return playlist_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 playlist_items = await db.playlist_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
if (data.item_key !== undefined) updatePayload.item_key = data.item_key;
if (data.position !== undefined) updatePayload.position = data.position;
if (data.added_at !== undefined) updatePayload.added_at = data.added_at;
updatePayload.updatedById = currentUser.id;
await playlist_items.update(updatePayload, {transaction});
if (data.playlist !== undefined) {
await playlist_items.setPlaylist(
data.playlist,
{ transaction }
);
}
if (data.organizations !== undefined) {
await playlist_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return playlist_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const playlist_items = await db.playlist_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of playlist_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of playlist_items) {
await record.destroy({transaction});
}
});
return playlist_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const playlist_items = await db.playlist_items.findByPk(id, options);
await playlist_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await playlist_items.destroy({
transaction
});
return playlist_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const playlist_items = await db.playlist_items.findOne(
{ where },
{ transaction },
);
if (!playlist_items) {
return playlist_items;
}
const output = playlist_items.get({plain: true});
output.playlist = await playlist_items.getPlaylist({
transaction
});
output.organizations = await playlist_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.playlists,
as: 'playlist',
where: filter.playlist ? {
[Op.or]: [
{ id: { [Op.in]: filter.playlist.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.playlist.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.item_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'playlist_items',
'item_key',
filter.item_key,
),
};
}
if (filter.positionRange) {
const [start, end] = filter.positionRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
position: {
...where.position,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
position: {
...where.position,
[Op.lte]: end,
},
};
}
}
if (filter.added_atRange) {
const [start, end] = filter.added_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
added_at: {
...where.added_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
added_at: {
...where.added_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.item_type) {
where = {
...where,
item_type: filter.item_type,
};
}
if (filter.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.playlist_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(
'playlist_items',
'item_key',
query,
),
],
};
}
const records = await db.playlist_items.findAll({
attributes: [ 'id', 'item_key' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['item_key', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.item_key,
}));
}
};

View File

@ -0,0 +1,562 @@
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 PlaylistsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const playlists = await db.playlists.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
visibility: data.visibility
||
null
,
collaborative: data.collaborative
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await playlists.setOwner_user( data.owner_user || null, {
transaction,
});
await playlists.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.playlists.getTableName(),
belongsToColumn: 'cover_images',
belongsToId: playlists.id,
},
data.cover_images,
options,
);
return playlists;
}
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 playlistsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
visibility: item.visibility
||
null
,
collaborative: item.collaborative
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const playlists = await db.playlists.bulkCreate(playlistsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < playlists.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.playlists.getTableName(),
belongsToColumn: 'cover_images',
belongsToId: playlists[i].id,
},
data[i].cover_images,
options,
);
}
return playlists;
}
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 playlists = await db.playlists.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.collaborative !== undefined) updatePayload.collaborative = data.collaborative;
updatePayload.updatedById = currentUser.id;
await playlists.update(updatePayload, {transaction});
if (data.owner_user !== undefined) {
await playlists.setOwner_user(
data.owner_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await playlists.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.playlists.getTableName(),
belongsToColumn: 'cover_images',
belongsToId: playlists.id,
},
data.cover_images,
options,
);
return playlists;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const playlists = await db.playlists.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of playlists) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of playlists) {
await record.destroy({transaction});
}
});
return playlists;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const playlists = await db.playlists.findByPk(id, options);
await playlists.update({
deletedBy: currentUser.id
}, {
transaction,
});
await playlists.destroy({
transaction
});
return playlists;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const playlists = await db.playlists.findOne(
{ where },
{ transaction },
);
if (!playlists) {
return playlists;
}
const output = playlists.get({plain: true});
output.playlist_items_playlist = await playlists.getPlaylist_items_playlist({
transaction
});
output.owner_user = await playlists.getOwner_user({
transaction
});
output.cover_images = await playlists.getCover_images({
transaction
});
output.organizations = await playlists.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_user',
where: filter.owner_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'cover_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'playlists',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'playlists',
'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.collaborative) {
where = {
...where,
collaborative: filter.collaborative,
};
}
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.playlists.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(
'playlists',
'name',
query,
),
],
};
}
const records = await db.playlists.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,518 @@
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 Private_mailboxesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const private_mailboxes = await db.private_mailboxes.create(
{
id: data.id || undefined,
public_label: data.public_label
||
null
,
is_enabled: data.is_enabled
||
false
,
allow_attachments: data.allow_attachments
||
false
,
delivery_mode: data.delivery_mode
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await private_mailboxes.setOwner_creator( data.owner_creator || null, {
transaction,
});
await private_mailboxes.setOrganizations( data.organizations || null, {
transaction,
});
return private_mailboxes;
}
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 private_mailboxesData = data.map((item, index) => ({
id: item.id || undefined,
public_label: item.public_label
||
null
,
is_enabled: item.is_enabled
||
false
,
allow_attachments: item.allow_attachments
||
false
,
delivery_mode: item.delivery_mode
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const private_mailboxes = await db.private_mailboxes.bulkCreate(private_mailboxesData, { transaction });
// For each item created, replace relation files
return private_mailboxes;
}
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 private_mailboxes = await db.private_mailboxes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.public_label !== undefined) updatePayload.public_label = data.public_label;
if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
if (data.allow_attachments !== undefined) updatePayload.allow_attachments = data.allow_attachments;
if (data.delivery_mode !== undefined) updatePayload.delivery_mode = data.delivery_mode;
updatePayload.updatedById = currentUser.id;
await private_mailboxes.update(updatePayload, {transaction});
if (data.owner_creator !== undefined) {
await private_mailboxes.setOwner_creator(
data.owner_creator,
{ transaction }
);
}
if (data.organizations !== undefined) {
await private_mailboxes.setOrganizations(
data.organizations,
{ transaction }
);
}
return private_mailboxes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const private_mailboxes = await db.private_mailboxes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of private_mailboxes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of private_mailboxes) {
await record.destroy({transaction});
}
});
return private_mailboxes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const private_mailboxes = await db.private_mailboxes.findByPk(id, options);
await private_mailboxes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await private_mailboxes.destroy({
transaction
});
return private_mailboxes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const private_mailboxes = await db.private_mailboxes.findOne(
{ where },
{ transaction },
);
if (!private_mailboxes) {
return private_mailboxes;
}
const output = private_mailboxes.get({plain: true});
output.messages_mailbox = await private_mailboxes.getMessages_mailbox({
transaction
});
output.owner_creator = await private_mailboxes.getOwner_creator({
transaction
});
output.organizations = await private_mailboxes.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.creator_profiles,
as: 'owner_creator',
where: filter.owner_creator ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_creator.split('|').map(term => Utils.uuid(term)) } },
{
handle: {
[Op.or]: filter.owner_creator.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.public_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'private_mailboxes',
'public_label',
filter.public_label,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_enabled) {
where = {
...where,
is_enabled: filter.is_enabled,
};
}
if (filter.allow_attachments) {
where = {
...where,
allow_attachments: filter.allow_attachments,
};
}
if (filter.delivery_mode) {
where = {
...where,
delivery_mode: filter.delivery_mode,
};
}
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.private_mailboxes.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(
'private_mailboxes',
'public_label',
query,
),
],
};
}
const records = await db.private_mailboxes.findAll({
attributes: [ 'id', 'public_label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['public_label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.public_label,
}));
}
};

View File

@ -0,0 +1,598 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Product_variantsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const product_variants = await db.product_variants.create(
{
id: data.id || undefined,
variant_name: data.variant_name
||
null
,
sku: data.sku
||
null
,
price_override: data.price_override
||
null
,
stock_quantity: data.stock_quantity
||
null
,
attributes_json: data.attributes_json
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await product_variants.setProduct( data.product || null, {
transaction,
});
await product_variants.setOrganizations( data.organizations || null, {
transaction,
});
return product_variants;
}
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_variantsData = data.map((item, index) => ({
id: item.id || undefined,
variant_name: item.variant_name
||
null
,
sku: item.sku
||
null
,
price_override: item.price_override
||
null
,
stock_quantity: item.stock_quantity
||
null
,
attributes_json: item.attributes_json
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const product_variants = await db.product_variants.bulkCreate(product_variantsData, { transaction });
// For each item created, replace relation files
return product_variants;
}
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_variants = await db.product_variants.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.variant_name !== undefined) updatePayload.variant_name = data.variant_name;
if (data.sku !== undefined) updatePayload.sku = data.sku;
if (data.price_override !== undefined) updatePayload.price_override = data.price_override;
if (data.stock_quantity !== undefined) updatePayload.stock_quantity = data.stock_quantity;
if (data.attributes_json !== undefined) updatePayload.attributes_json = data.attributes_json;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await product_variants.update(updatePayload, {transaction});
if (data.product !== undefined) {
await product_variants.setProduct(
data.product,
{ transaction }
);
}
if (data.organizations !== undefined) {
await product_variants.setOrganizations(
data.organizations,
{ transaction }
);
}
return product_variants;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const product_variants = await db.product_variants.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of product_variants) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of product_variants) {
await record.destroy({transaction});
}
});
return product_variants;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const product_variants = await db.product_variants.findByPk(id, options);
await product_variants.update({
deletedBy: currentUser.id
}, {
transaction,
});
await product_variants.destroy({
transaction
});
return product_variants;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const product_variants = await db.product_variants.findOne(
{ where },
{ transaction },
);
if (!product_variants) {
return product_variants;
}
const output = product_variants.get({plain: true});
output.order_items_variant = await product_variants.getOrder_items_variant({
transaction
});
output.product = await product_variants.getProduct({
transaction
});
output.organizations = await product_variants.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)) } },
{
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_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_variants',
'variant_name',
filter.variant_name,
),
};
}
if (filter.sku) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_variants',
'sku',
filter.sku,
),
};
}
if (filter.attributes_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_variants',
'attributes_json',
filter.attributes_json,
),
};
}
if (filter.price_overrideRange) {
const [start, end] = filter.price_overrideRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_override: {
...where.price_override,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_override: {
...where.price_override,
[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.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.product_variants.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_variants',
'variant_name',
query,
),
],
};
}
const records = await db.product_variants.findAll({
attributes: [ 'id', 'variant_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['variant_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.variant_name,
}));
}
};

View File

@ -0,0 +1,686 @@
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,
name: data.name
||
null
,
description: data.description
||
null
,
product_type: data.product_type
||
null
,
price: data.price
||
null
,
currency: data.currency
||
null
,
stock_quantity: data.stock_quantity
||
null
,
is_active: data.is_active
||
false
,
is_adult: data.is_adult
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await products.setMerch_store( data.merch_store || 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,
name: item.name
||
null
,
description: item.description
||
null
,
product_type: item.product_type
||
null
,
price: item.price
||
null
,
currency: item.currency
||
null
,
stock_quantity: item.stock_quantity
||
null
,
is_active: item.is_active
||
false
,
is_adult: item.is_adult
||
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.name !== undefined) updatePayload.name = data.name;
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.currency !== undefined) updatePayload.currency = data.currency;
if (data.stock_quantity !== undefined) updatePayload.stock_quantity = data.stock_quantity;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.is_adult !== undefined) updatePayload.is_adult = data.is_adult;
updatePayload.updatedById = currentUser.id;
await products.update(updatePayload, {transaction});
if (data.merch_store !== undefined) {
await products.setMerch_store(
data.merch_store,
{ 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.product_variants_product = await products.getProduct_variants_product({
transaction
});
output.order_items_product = await products.getOrder_items_product({
transaction
});
output.merch_store = await products.getMerch_store({
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.merch_stores,
as: 'merch_store',
where: filter.merch_store ? {
[Op.or]: [
{ id: { [Op.in]: filter.merch_store.split('|').map(term => Utils.uuid(term)) } },
{
store_name: {
[Op.or]: filter.merch_store.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.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'description',
filter.description,
),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'currency',
filter.currency,
),
};
}
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.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.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.is_adult) {
where = {
...where,
is_adult: filter.is_adult,
};
}
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',
'name',
query,
),
],
};
}
const records = await db.products.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,700 @@
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 Profile_stylesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const profile_styles = await db.profile_styles.create(
{
id: data.id || undefined,
style_name: data.style_name
||
null
,
username_color_hex: data.username_color_hex
||
null
,
bio_font_family: data.bio_font_family
||
null
,
panel_order_json: data.panel_order_json
||
null
,
profile_layout: data.profile_layout
||
null
,
show_pronouns_badge: data.show_pronouns_badge
||
false
,
pronouns_text: data.pronouns_text
||
null
,
custom_css: data.custom_css
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await profile_styles.setOwner_user( data.owner_user || null, {
transaction,
});
await profile_styles.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.profile_styles.getTableName(),
belongsToColumn: 'avatar_frame_images',
belongsToId: profile_styles.id,
},
data.avatar_frame_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.profile_styles.getTableName(),
belongsToColumn: 'banner_background_images',
belongsToId: profile_styles.id,
},
data.banner_background_images,
options,
);
return profile_styles;
}
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 profile_stylesData = data.map((item, index) => ({
id: item.id || undefined,
style_name: item.style_name
||
null
,
username_color_hex: item.username_color_hex
||
null
,
bio_font_family: item.bio_font_family
||
null
,
panel_order_json: item.panel_order_json
||
null
,
profile_layout: item.profile_layout
||
null
,
show_pronouns_badge: item.show_pronouns_badge
||
false
,
pronouns_text: item.pronouns_text
||
null
,
custom_css: item.custom_css
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const profile_styles = await db.profile_styles.bulkCreate(profile_stylesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < profile_styles.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.profile_styles.getTableName(),
belongsToColumn: 'avatar_frame_images',
belongsToId: profile_styles[i].id,
},
data[i].avatar_frame_images,
options,
);
}
for (let i = 0; i < profile_styles.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.profile_styles.getTableName(),
belongsToColumn: 'banner_background_images',
belongsToId: profile_styles[i].id,
},
data[i].banner_background_images,
options,
);
}
return profile_styles;
}
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 profile_styles = await db.profile_styles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.style_name !== undefined) updatePayload.style_name = data.style_name;
if (data.username_color_hex !== undefined) updatePayload.username_color_hex = data.username_color_hex;
if (data.bio_font_family !== undefined) updatePayload.bio_font_family = data.bio_font_family;
if (data.panel_order_json !== undefined) updatePayload.panel_order_json = data.panel_order_json;
if (data.profile_layout !== undefined) updatePayload.profile_layout = data.profile_layout;
if (data.show_pronouns_badge !== undefined) updatePayload.show_pronouns_badge = data.show_pronouns_badge;
if (data.pronouns_text !== undefined) updatePayload.pronouns_text = data.pronouns_text;
if (data.custom_css !== undefined) updatePayload.custom_css = data.custom_css;
updatePayload.updatedById = currentUser.id;
await profile_styles.update(updatePayload, {transaction});
if (data.owner_user !== undefined) {
await profile_styles.setOwner_user(
data.owner_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await profile_styles.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.profile_styles.getTableName(),
belongsToColumn: 'avatar_frame_images',
belongsToId: profile_styles.id,
},
data.avatar_frame_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.profile_styles.getTableName(),
belongsToColumn: 'banner_background_images',
belongsToId: profile_styles.id,
},
data.banner_background_images,
options,
);
return profile_styles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const profile_styles = await db.profile_styles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of profile_styles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of profile_styles) {
await record.destroy({transaction});
}
});
return profile_styles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const profile_styles = await db.profile_styles.findByPk(id, options);
await profile_styles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await profile_styles.destroy({
transaction
});
return profile_styles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const profile_styles = await db.profile_styles.findOne(
{ where },
{ transaction },
);
if (!profile_styles) {
return profile_styles;
}
const output = profile_styles.get({plain: true});
output.creator_profiles_profile_style = await profile_styles.getCreator_profiles_profile_style({
transaction
});
output.owner_user = await profile_styles.getOwner_user({
transaction
});
output.avatar_frame_images = await profile_styles.getAvatar_frame_images({
transaction
});
output.banner_background_images = await profile_styles.getBanner_background_images({
transaction
});
output.organizations = await profile_styles.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_user',
where: filter.owner_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'avatar_frame_images',
},
{
model: db.file,
as: 'banner_background_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.style_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'profile_styles',
'style_name',
filter.style_name,
),
};
}
if (filter.username_color_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'profile_styles',
'username_color_hex',
filter.username_color_hex,
),
};
}
if (filter.bio_font_family) {
where = {
...where,
[Op.and]: Utils.ilike(
'profile_styles',
'bio_font_family',
filter.bio_font_family,
),
};
}
if (filter.panel_order_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'profile_styles',
'panel_order_json',
filter.panel_order_json,
),
};
}
if (filter.pronouns_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'profile_styles',
'pronouns_text',
filter.pronouns_text,
),
};
}
if (filter.custom_css) {
where = {
...where,
[Op.and]: Utils.ilike(
'profile_styles',
'custom_css',
filter.custom_css,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.profile_layout) {
where = {
...where,
profile_layout: filter.profile_layout,
};
}
if (filter.show_pronouns_badge) {
where = {
...where,
show_pronouns_badge: filter.show_pronouns_badge,
};
}
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.profile_styles.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(
'profile_styles',
'style_name',
query,
),
],
};
}
const records = await db.profile_styles.findAll({
attributes: [ 'id', 'style_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['style_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.style_name,
}));
}
};

View File

@ -0,0 +1,608 @@
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 ReportsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.create(
{
id: data.id || undefined,
target_type: data.target_type
||
null
,
target_key: data.target_key
||
null
,
reason: data.reason
||
null
,
details: data.details
||
null
,
status: data.status
||
null
,
reported_at: data.reported_at
||
null
,
resolved_at: data.resolved_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await reports.setReporter_user( data.reporter_user || null, {
transaction,
});
await reports.setOrganizations( data.organizations || null, {
transaction,
});
return reports;
}
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 reportsData = data.map((item, index) => ({
id: item.id || undefined,
target_type: item.target_type
||
null
,
target_key: item.target_key
||
null
,
reason: item.reason
||
null
,
details: item.details
||
null
,
status: item.status
||
null
,
reported_at: item.reported_at
||
null
,
resolved_at: item.resolved_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const reports = await db.reports.bulkCreate(reportsData, { transaction });
// For each item created, replace relation files
return reports;
}
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 reports = await db.reports.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.target_type !== undefined) updatePayload.target_type = data.target_type;
if (data.target_key !== undefined) updatePayload.target_key = data.target_key;
if (data.reason !== undefined) updatePayload.reason = data.reason;
if (data.details !== undefined) updatePayload.details = data.details;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
updatePayload.updatedById = currentUser.id;
await reports.update(updatePayload, {transaction});
if (data.reporter_user !== undefined) {
await reports.setReporter_user(
data.reporter_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await reports.setOrganizations(
data.organizations,
{ transaction }
);
}
return reports;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of reports) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of reports) {
await record.destroy({transaction});
}
});
return reports;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.findByPk(id, options);
await reports.update({
deletedBy: currentUser.id
}, {
transaction,
});
await reports.destroy({
transaction
});
return reports;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.findOne(
{ where },
{ transaction },
);
if (!reports) {
return reports;
}
const output = reports.get({plain: true});
output.reporter_user = await reports.getReporter_user({
transaction
});
output.organizations = await reports.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: 'reporter_user',
where: filter.reporter_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.reporter_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.reporter_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.target_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'reports',
'target_key',
filter.target_key,
),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'reports',
'details',
filter.details,
),
};
}
if (filter.reported_atRange) {
const [start, end] = filter.reported_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reported_at: {
...where.reported_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reported_at: {
...where.reported_at,
[Op.lte]: end,
},
};
}
}
if (filter.resolved_atRange) {
const [start, end] = filter.resolved_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
resolved_at: {
...where.resolved_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
resolved_at: {
...where.resolved_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.target_type) {
where = {
...where,
target_type: filter.target_type,
};
}
if (filter.reason) {
where = {
...where,
reason: filter.reason,
};
}
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.reports.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(
'reports',
'details',
query,
),
],
};
}
const records = await db.reports.findAll({
attributes: [ 'id', 'details' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['details', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.details,
}));
}
};

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

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

View File

@ -0,0 +1,568 @@
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 Shipping_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shipping_profiles = await db.shipping_profiles.create(
{
id: data.id || undefined,
profile_name: data.profile_name
||
null
,
origin_country: data.origin_country
||
null
,
origin_region: data.origin_region
||
null
,
origin_postal_code: data.origin_postal_code
||
null
,
rules_json: data.rules_json
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await shipping_profiles.setMerch_store( data.merch_store || null, {
transaction,
});
await shipping_profiles.setOrganizations( data.organizations || null, {
transaction,
});
return shipping_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 shipping_profilesData = data.map((item, index) => ({
id: item.id || undefined,
profile_name: item.profile_name
||
null
,
origin_country: item.origin_country
||
null
,
origin_region: item.origin_region
||
null
,
origin_postal_code: item.origin_postal_code
||
null
,
rules_json: item.rules_json
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const shipping_profiles = await db.shipping_profiles.bulkCreate(shipping_profilesData, { transaction });
// For each item created, replace relation files
return shipping_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 shipping_profiles = await db.shipping_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.profile_name !== undefined) updatePayload.profile_name = data.profile_name;
if (data.origin_country !== undefined) updatePayload.origin_country = data.origin_country;
if (data.origin_region !== undefined) updatePayload.origin_region = data.origin_region;
if (data.origin_postal_code !== undefined) updatePayload.origin_postal_code = data.origin_postal_code;
if (data.rules_json !== undefined) updatePayload.rules_json = data.rules_json;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await shipping_profiles.update(updatePayload, {transaction});
if (data.merch_store !== undefined) {
await shipping_profiles.setMerch_store(
data.merch_store,
{ transaction }
);
}
if (data.organizations !== undefined) {
await shipping_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
return shipping_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shipping_profiles = await db.shipping_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of shipping_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of shipping_profiles) {
await record.destroy({transaction});
}
});
return shipping_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const shipping_profiles = await db.shipping_profiles.findByPk(id, options);
await shipping_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await shipping_profiles.destroy({
transaction
});
return shipping_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const shipping_profiles = await db.shipping_profiles.findOne(
{ where },
{ transaction },
);
if (!shipping_profiles) {
return shipping_profiles;
}
const output = shipping_profiles.get({plain: true});
output.merch_store = await shipping_profiles.getMerch_store({
transaction
});
output.organizations = await shipping_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.merch_stores,
as: 'merch_store',
where: filter.merch_store ? {
[Op.or]: [
{ id: { [Op.in]: filter.merch_store.split('|').map(term => Utils.uuid(term)) } },
{
store_name: {
[Op.or]: filter.merch_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.profile_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'shipping_profiles',
'profile_name',
filter.profile_name,
),
};
}
if (filter.origin_country) {
where = {
...where,
[Op.and]: Utils.ilike(
'shipping_profiles',
'origin_country',
filter.origin_country,
),
};
}
if (filter.origin_region) {
where = {
...where,
[Op.and]: Utils.ilike(
'shipping_profiles',
'origin_region',
filter.origin_region,
),
};
}
if (filter.origin_postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'shipping_profiles',
'origin_postal_code',
filter.origin_postal_code,
),
};
}
if (filter.rules_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'shipping_profiles',
'rules_json',
filter.rules_json,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.shipping_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(
'shipping_profiles',
'profile_name',
query,
),
],
};
}
const records = await db.shipping_profiles.findAll({
attributes: [ 'id', 'profile_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['profile_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.profile_name,
}));
}
};

View File

@ -0,0 +1,807 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class StreamsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const streams = await db.streams.create(
{
id: data.id || undefined,
title: data.title
||
null
,
description: data.description
||
null
,
category: data.category
||
null
,
is_live: data.is_live
||
false
,
is_adult: data.is_adult
||
false
,
scheduled_start_at: data.scheduled_start_at
||
null
,
started_at: data.started_at
||
null
,
ended_at: data.ended_at
||
null
,
viewer_count: data.viewer_count
||
null
,
stream_key_hint: data.stream_key_hint
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await streams.setCreator( data.creator || null, {
transaction,
});
await streams.setOverlay_profile( data.overlay_profile || null, {
transaction,
});
await streams.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.streams.getTableName(),
belongsToColumn: 'thumbnail_images',
belongsToId: streams.id,
},
data.thumbnail_images,
options,
);
return streams;
}
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 streamsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
description: item.description
||
null
,
category: item.category
||
null
,
is_live: item.is_live
||
false
,
is_adult: item.is_adult
||
false
,
scheduled_start_at: item.scheduled_start_at
||
null
,
started_at: item.started_at
||
null
,
ended_at: item.ended_at
||
null
,
viewer_count: item.viewer_count
||
null
,
stream_key_hint: item.stream_key_hint
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const streams = await db.streams.bulkCreate(streamsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < streams.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.streams.getTableName(),
belongsToColumn: 'thumbnail_images',
belongsToId: streams[i].id,
},
data[i].thumbnail_images,
options,
);
}
return streams;
}
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 streams = await db.streams.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.is_live !== undefined) updatePayload.is_live = data.is_live;
if (data.is_adult !== undefined) updatePayload.is_adult = data.is_adult;
if (data.scheduled_start_at !== undefined) updatePayload.scheduled_start_at = data.scheduled_start_at;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.viewer_count !== undefined) updatePayload.viewer_count = data.viewer_count;
if (data.stream_key_hint !== undefined) updatePayload.stream_key_hint = data.stream_key_hint;
updatePayload.updatedById = currentUser.id;
await streams.update(updatePayload, {transaction});
if (data.creator !== undefined) {
await streams.setCreator(
data.creator,
{ transaction }
);
}
if (data.overlay_profile !== undefined) {
await streams.setOverlay_profile(
data.overlay_profile,
{ transaction }
);
}
if (data.organizations !== undefined) {
await streams.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.streams.getTableName(),
belongsToColumn: 'thumbnail_images',
belongsToId: streams.id,
},
data.thumbnail_images,
options,
);
return streams;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const streams = await db.streams.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of streams) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of streams) {
await record.destroy({transaction});
}
});
return streams;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const streams = await db.streams.findByPk(id, options);
await streams.update({
deletedBy: currentUser.id
}, {
transaction,
});
await streams.destroy({
transaction
});
return streams;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const streams = await db.streams.findOne(
{ where },
{ transaction },
);
if (!streams) {
return streams;
}
const output = streams.get({plain: true});
output.creator = await streams.getCreator({
transaction
});
output.thumbnail_images = await streams.getThumbnail_images({
transaction
});
output.overlay_profile = await streams.getOverlay_profile({
transaction
});
output.organizations = await streams.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.creator_profiles,
as: 'creator',
where: filter.creator ? {
[Op.or]: [
{ id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
{
handle: {
[Op.or]: filter.creator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.overlay_profiles,
as: 'overlay_profile',
where: filter.overlay_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.overlay_profile.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.overlay_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'thumbnail_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'streams',
'title',
filter.title,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'streams',
'description',
filter.description,
),
};
}
if (filter.stream_key_hint) {
where = {
...where,
[Op.and]: Utils.ilike(
'streams',
'stream_key_hint',
filter.stream_key_hint,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
scheduled_start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ended_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.scheduled_start_atRange) {
const [start, end] = filter.scheduled_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_start_at: {
...where.scheduled_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_start_at: {
...where.scheduled_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.ended_atRange) {
const [start, end] = filter.ended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.lte]: end,
},
};
}
}
if (filter.viewer_countRange) {
const [start, end] = filter.viewer_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
viewer_count: {
...where.viewer_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
viewer_count: {
...where.viewer_count,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.is_live) {
where = {
...where,
is_live: filter.is_live,
};
}
if (filter.is_adult) {
where = {
...where,
is_adult: filter.is_adult,
};
}
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.streams.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(
'streams',
'title',
query,
),
],
};
}
const records = await db.streams.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,691 @@
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 Theme_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const theme_profiles = await db.theme_profiles.create(
{
id: data.id || undefined,
mode: data.mode
||
null
,
theme_name: data.theme_name
||
null
,
primary_color_hex: data.primary_color_hex
||
null
,
accent_color_hex: data.accent_color_hex
||
null
,
neon_glow_color_hex: data.neon_glow_color_hex
||
null
,
rgb_cycle_enabled: data.rgb_cycle_enabled
||
false
,
rgb_cycle_speed: data.rgb_cycle_speed
||
null
,
holiday_palette: data.holiday_palette
||
null
,
adult_palette_enabled: data.adult_palette_enabled
||
false
,
adult_primary_color_hex: data.adult_primary_color_hex
||
null
,
adult_accent_color_hex: data.adult_accent_color_hex
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await theme_profiles.setOwner_user( data.owner_user || null, {
transaction,
});
await theme_profiles.setOrganizations( data.organizations || null, {
transaction,
});
return theme_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 theme_profilesData = data.map((item, index) => ({
id: item.id || undefined,
mode: item.mode
||
null
,
theme_name: item.theme_name
||
null
,
primary_color_hex: item.primary_color_hex
||
null
,
accent_color_hex: item.accent_color_hex
||
null
,
neon_glow_color_hex: item.neon_glow_color_hex
||
null
,
rgb_cycle_enabled: item.rgb_cycle_enabled
||
false
,
rgb_cycle_speed: item.rgb_cycle_speed
||
null
,
holiday_palette: item.holiday_palette
||
null
,
adult_palette_enabled: item.adult_palette_enabled
||
false
,
adult_primary_color_hex: item.adult_primary_color_hex
||
null
,
adult_accent_color_hex: item.adult_accent_color_hex
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const theme_profiles = await db.theme_profiles.bulkCreate(theme_profilesData, { transaction });
// For each item created, replace relation files
return theme_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 theme_profiles = await db.theme_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.mode !== undefined) updatePayload.mode = data.mode;
if (data.theme_name !== undefined) updatePayload.theme_name = data.theme_name;
if (data.primary_color_hex !== undefined) updatePayload.primary_color_hex = data.primary_color_hex;
if (data.accent_color_hex !== undefined) updatePayload.accent_color_hex = data.accent_color_hex;
if (data.neon_glow_color_hex !== undefined) updatePayload.neon_glow_color_hex = data.neon_glow_color_hex;
if (data.rgb_cycle_enabled !== undefined) updatePayload.rgb_cycle_enabled = data.rgb_cycle_enabled;
if (data.rgb_cycle_speed !== undefined) updatePayload.rgb_cycle_speed = data.rgb_cycle_speed;
if (data.holiday_palette !== undefined) updatePayload.holiday_palette = data.holiday_palette;
if (data.adult_palette_enabled !== undefined) updatePayload.adult_palette_enabled = data.adult_palette_enabled;
if (data.adult_primary_color_hex !== undefined) updatePayload.adult_primary_color_hex = data.adult_primary_color_hex;
if (data.adult_accent_color_hex !== undefined) updatePayload.adult_accent_color_hex = data.adult_accent_color_hex;
updatePayload.updatedById = currentUser.id;
await theme_profiles.update(updatePayload, {transaction});
if (data.owner_user !== undefined) {
await theme_profiles.setOwner_user(
data.owner_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await theme_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
return theme_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const theme_profiles = await db.theme_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of theme_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of theme_profiles) {
await record.destroy({transaction});
}
});
return theme_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const theme_profiles = await db.theme_profiles.findByPk(id, options);
await theme_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await theme_profiles.destroy({
transaction
});
return theme_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const theme_profiles = await db.theme_profiles.findOne(
{ where },
{ transaction },
);
if (!theme_profiles) {
return theme_profiles;
}
const output = theme_profiles.get({plain: true});
output.owner_user = await theme_profiles.getOwner_user({
transaction
});
output.organizations = await theme_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.users,
as: 'owner_user',
where: filter.owner_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.theme_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'theme_profiles',
'theme_name',
filter.theme_name,
),
};
}
if (filter.primary_color_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'theme_profiles',
'primary_color_hex',
filter.primary_color_hex,
),
};
}
if (filter.accent_color_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'theme_profiles',
'accent_color_hex',
filter.accent_color_hex,
),
};
}
if (filter.neon_glow_color_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'theme_profiles',
'neon_glow_color_hex',
filter.neon_glow_color_hex,
),
};
}
if (filter.adult_primary_color_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'theme_profiles',
'adult_primary_color_hex',
filter.adult_primary_color_hex,
),
};
}
if (filter.adult_accent_color_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'theme_profiles',
'adult_accent_color_hex',
filter.adult_accent_color_hex,
),
};
}
if (filter.rgb_cycle_speedRange) {
const [start, end] = filter.rgb_cycle_speedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rgb_cycle_speed: {
...where.rgb_cycle_speed,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rgb_cycle_speed: {
...where.rgb_cycle_speed,
[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.rgb_cycle_enabled) {
where = {
...where,
rgb_cycle_enabled: filter.rgb_cycle_enabled,
};
}
if (filter.holiday_palette) {
where = {
...where,
holiday_palette: filter.holiday_palette,
};
}
if (filter.adult_palette_enabled) {
where = {
...where,
adult_palette_enabled: filter.adult_palette_enabled,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.theme_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(
'theme_profiles',
'theme_name',
query,
),
],
};
}
const records = await db.theme_profiles.findAll({
attributes: [ 'id', 'theme_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['theme_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.theme_name,
}));
}
};

View File

@ -0,0 +1,812 @@
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 Tip_pagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tip_pages = await db.tip_pages.create(
{
id: data.id || undefined,
slug: data.slug
||
null
,
headline: data.headline
||
null
,
thank_you_message: data.thank_you_message
||
null
,
background_type: data.background_type
||
null
,
background_value: data.background_value
||
null
,
accent_color_hex: data.accent_color_hex
||
null
,
preset_amount_1: data.preset_amount_1
||
null
,
preset_amount_2: data.preset_amount_2
||
null
,
preset_amount_3: data.preset_amount_3
||
null
,
allow_custom_amount: data.allow_custom_amount
||
false
,
minimum_amount: data.minimum_amount
||
null
,
tts_enabled: data.tts_enabled
||
false
,
tts_voice: data.tts_voice
||
null
,
show_supporter_feed: data.show_supporter_feed
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tip_pages.setCreator( data.creator || null, {
transaction,
});
await tip_pages.setOrganizations( data.organizations || null, {
transaction,
});
return tip_pages;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const tip_pagesData = data.map((item, index) => ({
id: item.id || undefined,
slug: item.slug
||
null
,
headline: item.headline
||
null
,
thank_you_message: item.thank_you_message
||
null
,
background_type: item.background_type
||
null
,
background_value: item.background_value
||
null
,
accent_color_hex: item.accent_color_hex
||
null
,
preset_amount_1: item.preset_amount_1
||
null
,
preset_amount_2: item.preset_amount_2
||
null
,
preset_amount_3: item.preset_amount_3
||
null
,
allow_custom_amount: item.allow_custom_amount
||
false
,
minimum_amount: item.minimum_amount
||
null
,
tts_enabled: item.tts_enabled
||
false
,
tts_voice: item.tts_voice
||
null
,
show_supporter_feed: item.show_supporter_feed
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tip_pages = await db.tip_pages.bulkCreate(tip_pagesData, { transaction });
// For each item created, replace relation files
return tip_pages;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const tip_pages = await db.tip_pages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.headline !== undefined) updatePayload.headline = data.headline;
if (data.thank_you_message !== undefined) updatePayload.thank_you_message = data.thank_you_message;
if (data.background_type !== undefined) updatePayload.background_type = data.background_type;
if (data.background_value !== undefined) updatePayload.background_value = data.background_value;
if (data.accent_color_hex !== undefined) updatePayload.accent_color_hex = data.accent_color_hex;
if (data.preset_amount_1 !== undefined) updatePayload.preset_amount_1 = data.preset_amount_1;
if (data.preset_amount_2 !== undefined) updatePayload.preset_amount_2 = data.preset_amount_2;
if (data.preset_amount_3 !== undefined) updatePayload.preset_amount_3 = data.preset_amount_3;
if (data.allow_custom_amount !== undefined) updatePayload.allow_custom_amount = data.allow_custom_amount;
if (data.minimum_amount !== undefined) updatePayload.minimum_amount = data.minimum_amount;
if (data.tts_enabled !== undefined) updatePayload.tts_enabled = data.tts_enabled;
if (data.tts_voice !== undefined) updatePayload.tts_voice = data.tts_voice;
if (data.show_supporter_feed !== undefined) updatePayload.show_supporter_feed = data.show_supporter_feed;
updatePayload.updatedById = currentUser.id;
await tip_pages.update(updatePayload, {transaction});
if (data.creator !== undefined) {
await tip_pages.setCreator(
data.creator,
{ transaction }
);
}
if (data.organizations !== undefined) {
await tip_pages.setOrganizations(
data.organizations,
{ transaction }
);
}
return tip_pages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tip_pages = await db.tip_pages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tip_pages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tip_pages) {
await record.destroy({transaction});
}
});
return tip_pages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tip_pages = await db.tip_pages.findByPk(id, options);
await tip_pages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tip_pages.destroy({
transaction
});
return tip_pages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tip_pages = await db.tip_pages.findOne(
{ where },
{ transaction },
);
if (!tip_pages) {
return tip_pages;
}
const output = tip_pages.get({plain: true});
output.creator_profiles_tip_page = await tip_pages.getCreator_profiles_tip_page({
transaction
});
output.tips_tip_page = await tip_pages.getTips_tip_page({
transaction
});
output.creator = await tip_pages.getCreator({
transaction
});
output.organizations = await tip_pages.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.creator_profiles,
as: 'creator',
where: filter.creator ? {
[Op.or]: [
{ id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
{
handle: {
[Op.or]: filter.creator.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.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'tip_pages',
'slug',
filter.slug,
),
};
}
if (filter.headline) {
where = {
...where,
[Op.and]: Utils.ilike(
'tip_pages',
'headline',
filter.headline,
),
};
}
if (filter.thank_you_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'tip_pages',
'thank_you_message',
filter.thank_you_message,
),
};
}
if (filter.background_value) {
where = {
...where,
[Op.and]: Utils.ilike(
'tip_pages',
'background_value',
filter.background_value,
),
};
}
if (filter.accent_color_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'tip_pages',
'accent_color_hex',
filter.accent_color_hex,
),
};
}
if (filter.tts_voice) {
where = {
...where,
[Op.and]: Utils.ilike(
'tip_pages',
'tts_voice',
filter.tts_voice,
),
};
}
if (filter.preset_amount_1Range) {
const [start, end] = filter.preset_amount_1Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
preset_amount_1: {
...where.preset_amount_1,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
preset_amount_1: {
...where.preset_amount_1,
[Op.lte]: end,
},
};
}
}
if (filter.preset_amount_2Range) {
const [start, end] = filter.preset_amount_2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
preset_amount_2: {
...where.preset_amount_2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
preset_amount_2: {
...where.preset_amount_2,
[Op.lte]: end,
},
};
}
}
if (filter.preset_amount_3Range) {
const [start, end] = filter.preset_amount_3Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
preset_amount_3: {
...where.preset_amount_3,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
preset_amount_3: {
...where.preset_amount_3,
[Op.lte]: end,
},
};
}
}
if (filter.minimum_amountRange) {
const [start, end] = filter.minimum_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
minimum_amount: {
...where.minimum_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
minimum_amount: {
...where.minimum_amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.background_type) {
where = {
...where,
background_type: filter.background_type,
};
}
if (filter.allow_custom_amount) {
where = {
...where,
allow_custom_amount: filter.allow_custom_amount,
};
}
if (filter.tts_enabled) {
where = {
...where,
tts_enabled: filter.tts_enabled,
};
}
if (filter.show_supporter_feed) {
where = {
...where,
show_supporter_feed: filter.show_supporter_feed,
};
}
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.tip_pages.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'tip_pages',
'slug',
query,
),
],
};
}
const records = await db.tip_pages.findAll({
attributes: [ 'id', 'slug' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['slug', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.slug,
}));
}
};

627
backend/src/db/api/tips.js Normal file
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 TipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tips = await db.tips.create(
{
id: data.id || undefined,
amount: data.amount
||
null
,
currency: data.currency
||
null
,
message: data.message
||
null
,
is_anonymous: data.is_anonymous
||
false
,
status: data.status
||
null
,
sent_at: data.sent_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tips.setTip_page( data.tip_page || null, {
transaction,
});
await tips.setFrom_user( data.from_user || null, {
transaction,
});
await tips.setOrganizations( data.organizations || null, {
transaction,
});
return tips;
}
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 tipsData = data.map((item, index) => ({
id: item.id || undefined,
amount: item.amount
||
null
,
currency: item.currency
||
null
,
message: item.message
||
null
,
is_anonymous: item.is_anonymous
||
false
,
status: item.status
||
null
,
sent_at: item.sent_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tips = await db.tips.bulkCreate(tipsData, { transaction });
// For each item created, replace relation files
return tips;
}
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 tips = await db.tips.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.message !== undefined) updatePayload.message = data.message;
if (data.is_anonymous !== undefined) updatePayload.is_anonymous = data.is_anonymous;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
updatePayload.updatedById = currentUser.id;
await tips.update(updatePayload, {transaction});
if (data.tip_page !== undefined) {
await tips.setTip_page(
data.tip_page,
{ transaction }
);
}
if (data.from_user !== undefined) {
await tips.setFrom_user(
data.from_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await tips.setOrganizations(
data.organizations,
{ transaction }
);
}
return tips;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tips = await db.tips.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tips) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tips) {
await record.destroy({transaction});
}
});
return tips;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tips = await db.tips.findByPk(id, options);
await tips.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tips.destroy({
transaction
});
return tips;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tips = await db.tips.findOne(
{ where },
{ transaction },
);
if (!tips) {
return tips;
}
const output = tips.get({plain: true});
output.tip_page = await tips.getTip_page({
transaction
});
output.from_user = await tips.getFrom_user({
transaction
});
output.organizations = await tips.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.tip_pages,
as: 'tip_page',
where: filter.tip_page ? {
[Op.or]: [
{ id: { [Op.in]: filter.tip_page.split('|').map(term => Utils.uuid(term)) } },
{
slug: {
[Op.or]: filter.tip_page.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'from_user',
where: filter.from_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.from_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.from_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.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'tips',
'currency',
filter.currency,
),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'tips',
'message',
filter.message,
),
};
}
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.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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_anonymous) {
where = {
...where,
is_anonymous: filter.is_anonymous,
};
}
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.tips.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(
'tips',
'currency',
query,
),
],
};
}
const records = await db.tips.findAll({
attributes: [ 'id', 'currency' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['currency', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.currency,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,785 @@
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 VideosDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const videos = await db.videos.create(
{
id: data.id || undefined,
title: data.title
||
null
,
description: data.description
||
null
,
visibility: data.visibility
||
null
,
is_adult: data.is_adult
||
false
,
published_at: data.published_at
||
null
,
duration_seconds: data.duration_seconds
||
null
,
view_count: data.view_count
||
null
,
like_count: data.like_count
||
null
,
comment_count: data.comment_count
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await videos.setCreator( data.creator || null, {
transaction,
});
await videos.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.videos.getTableName(),
belongsToColumn: 'thumbnail_images',
belongsToId: videos.id,
},
data.thumbnail_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.videos.getTableName(),
belongsToColumn: 'video_files',
belongsToId: videos.id,
},
data.video_files,
options,
);
return videos;
}
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 videosData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
description: item.description
||
null
,
visibility: item.visibility
||
null
,
is_adult: item.is_adult
||
false
,
published_at: item.published_at
||
null
,
duration_seconds: item.duration_seconds
||
null
,
view_count: item.view_count
||
null
,
like_count: item.like_count
||
null
,
comment_count: item.comment_count
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const videos = await db.videos.bulkCreate(videosData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < videos.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.videos.getTableName(),
belongsToColumn: 'thumbnail_images',
belongsToId: videos[i].id,
},
data[i].thumbnail_images,
options,
);
}
for (let i = 0; i < videos.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.videos.getTableName(),
belongsToColumn: 'video_files',
belongsToId: videos[i].id,
},
data[i].video_files,
options,
);
}
return videos;
}
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 videos = await db.videos.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.is_adult !== undefined) updatePayload.is_adult = data.is_adult;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
if (data.view_count !== undefined) updatePayload.view_count = data.view_count;
if (data.like_count !== undefined) updatePayload.like_count = data.like_count;
if (data.comment_count !== undefined) updatePayload.comment_count = data.comment_count;
updatePayload.updatedById = currentUser.id;
await videos.update(updatePayload, {transaction});
if (data.creator !== undefined) {
await videos.setCreator(
data.creator,
{ transaction }
);
}
if (data.organizations !== undefined) {
await videos.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.videos.getTableName(),
belongsToColumn: 'thumbnail_images',
belongsToId: videos.id,
},
data.thumbnail_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.videos.getTableName(),
belongsToColumn: 'video_files',
belongsToId: videos.id,
},
data.video_files,
options,
);
return videos;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const videos = await db.videos.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of videos) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of videos) {
await record.destroy({transaction});
}
});
return videos;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const videos = await db.videos.findByPk(id, options);
await videos.update({
deletedBy: currentUser.id
}, {
transaction,
});
await videos.destroy({
transaction
});
return videos;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const videos = await db.videos.findOne(
{ where },
{ transaction },
);
if (!videos) {
return videos;
}
const output = videos.get({plain: true});
output.creator = await videos.getCreator({
transaction
});
output.thumbnail_images = await videos.getThumbnail_images({
transaction
});
output.video_files = await videos.getVideo_files({
transaction
});
output.organizations = await videos.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.creator_profiles,
as: 'creator',
where: filter.creator ? {
[Op.or]: [
{ id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
{
handle: {
[Op.or]: filter.creator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'thumbnail_images',
},
{
model: db.file,
as: 'video_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'videos',
'title',
filter.title,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'videos',
'description',
filter.description,
),
};
}
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.duration_secondsRange) {
const [start, end] = filter.duration_secondsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.lte]: end,
},
};
}
}
if (filter.view_countRange) {
const [start, end] = filter.view_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
view_count: {
...where.view_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
view_count: {
...where.view_count,
[Op.lte]: end,
},
};
}
}
if (filter.like_countRange) {
const [start, end] = filter.like_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
like_count: {
...where.like_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
like_count: {
...where.like_count,
[Op.lte]: end,
},
};
}
}
if (filter.comment_countRange) {
const [start, end] = filter.comment_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
comment_count: {
...where.comment_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
comment_count: {
...where.comment_count,
[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.is_adult) {
where = {
...where,
is_adult: filter.is_adult,
};
}
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.videos.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(
'videos',
'title',
query,
),
],
};
}
const records = await db.videos.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,612 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class 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
,
kind: data.kind
||
null
,
amount: data.amount
||
null
,
currency: data.currency
||
null
,
reference_key: data.reference_key
||
null
,
note: data.note
||
null
,
occurred_at: data.occurred_at
||
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
,
kind: item.kind
||
null
,
amount: item.amount
||
null
,
currency: item.currency
||
null
,
reference_key: item.reference_key
||
null
,
note: item.note
||
null
,
occurred_at: item.occurred_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const 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.kind !== undefined) updatePayload.kind = data.kind;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.reference_key !== undefined) updatePayload.reference_key = data.reference_key;
if (data.note !== undefined) updatePayload.note = data.note;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
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.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.demo_wallets,
as: 'wallet',
where: filter.wallet ? {
[Op.or]: [
{ id: { [Op.in]: filter.wallet.split('|').map(term => Utils.uuid(term)) } },
{
currency: {
[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.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallet_transactions',
'currency',
filter.currency,
),
};
}
if (filter.reference_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallet_transactions',
'reference_key',
filter.reference_key,
),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallet_transactions',
'note',
filter.note,
),
};
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.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.direction) {
where = {
...where,
direction: filter.direction,
};
}
if (filter.kind) {
where = {
...where,
kind: filter.kind,
};
}
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_key',
query,
),
],
};
}
const records = await db.wallet_transactions.findAll({
attributes: [ 'id', 'reference_key' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reference_key', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reference_key,
}));
}
};

View File

@ -0,0 +1,619 @@
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 Widget_catalog_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const widget_catalog_items = await db.widget_catalog_items.create(
{
id: data.id || undefined,
name: data.name
||
null
,
icon_name: data.icon_name
||
null
,
author_name: data.author_name
||
null
,
widget_type: data.widget_type
||
null
,
description: data.description
||
null
,
is_public: data.is_public
||
false
,
is_adult_only: data.is_adult_only
||
false
,
schema_json: data.schema_json
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await widget_catalog_items.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.widget_catalog_items.getTableName(),
belongsToColumn: 'bundle_files',
belongsToId: widget_catalog_items.id,
},
data.bundle_files,
options,
);
return widget_catalog_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 widget_catalog_itemsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
icon_name: item.icon_name
||
null
,
author_name: item.author_name
||
null
,
widget_type: item.widget_type
||
null
,
description: item.description
||
null
,
is_public: item.is_public
||
false
,
is_adult_only: item.is_adult_only
||
false
,
schema_json: item.schema_json
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const widget_catalog_items = await db.widget_catalog_items.bulkCreate(widget_catalog_itemsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < widget_catalog_items.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.widget_catalog_items.getTableName(),
belongsToColumn: 'bundle_files',
belongsToId: widget_catalog_items[i].id,
},
data[i].bundle_files,
options,
);
}
return widget_catalog_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 widget_catalog_items = await db.widget_catalog_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.icon_name !== undefined) updatePayload.icon_name = data.icon_name;
if (data.author_name !== undefined) updatePayload.author_name = data.author_name;
if (data.widget_type !== undefined) updatePayload.widget_type = data.widget_type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
if (data.is_adult_only !== undefined) updatePayload.is_adult_only = data.is_adult_only;
if (data.schema_json !== undefined) updatePayload.schema_json = data.schema_json;
updatePayload.updatedById = currentUser.id;
await widget_catalog_items.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await widget_catalog_items.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.widget_catalog_items.getTableName(),
belongsToColumn: 'bundle_files',
belongsToId: widget_catalog_items.id,
},
data.bundle_files,
options,
);
return widget_catalog_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const widget_catalog_items = await db.widget_catalog_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of widget_catalog_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of widget_catalog_items) {
await record.destroy({transaction});
}
});
return widget_catalog_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const widget_catalog_items = await db.widget_catalog_items.findByPk(id, options);
await widget_catalog_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await widget_catalog_items.destroy({
transaction
});
return widget_catalog_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const widget_catalog_items = await db.widget_catalog_items.findOne(
{ where },
{ transaction },
);
if (!widget_catalog_items) {
return widget_catalog_items;
}
const output = widget_catalog_items.get({plain: true});
output.overlay_widgets_catalog_item = await widget_catalog_items.getOverlay_widgets_catalog_item({
transaction
});
output.bundle_files = await widget_catalog_items.getBundle_files({
transaction
});
output.organizations = await widget_catalog_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.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'bundle_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'widget_catalog_items',
'name',
filter.name,
),
};
}
if (filter.icon_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'widget_catalog_items',
'icon_name',
filter.icon_name,
),
};
}
if (filter.author_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'widget_catalog_items',
'author_name',
filter.author_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'widget_catalog_items',
'description',
filter.description,
),
};
}
if (filter.schema_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'widget_catalog_items',
'schema_json',
filter.schema_json,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.widget_type) {
where = {
...where,
widget_type: filter.widget_type,
};
}
if (filter.is_public) {
where = {
...where,
is_public: filter.is_public,
};
}
if (filter.is_adult_only) {
where = {
...where,
is_adult_only: filter.is_adult_only,
};
}
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.widget_catalog_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(
'widget_catalog_items',
'name',
query,
),
],
};
}
const records = await db.widget_catalog_items.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,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_xpansion_creator_platform',
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,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 alert_profiles = sequelize.define(
'alert_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
profile_name: {
type: DataTypes.TEXT,
},
brand_primary_hex: {
type: DataTypes.TEXT,
},
brand_accent_hex: {
type: DataTypes.TEXT,
},
animation_style: {
type: DataTypes.ENUM,
values: [
"slide",
"fade",
"pop",
"pulse_rgb"
],
},
tts_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
tts_voice: {
type: DataTypes.TEXT,
},
template_style: {
type: DataTypes.ENUM,
values: [
"minimal",
"classic",
"hype"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
alert_profiles.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.alert_profiles.hasMany(db.alerts, {
as: 'alerts_alert_profile',
foreignKey: {
name: 'alert_profileId',
},
constraints: false,
});
//end loop
db.alert_profiles.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.alert_profiles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.alert_profiles.hasMany(db.file, {
as: 'default_sound_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.alert_profiles.getTableName(),
belongsToColumn: 'default_sound_files',
},
});
db.alert_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.alert_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return alert_profiles;
};

View File

@ -0,0 +1,227 @@
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 alerts = sequelize.define(
'alerts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
alert_type: {
type: DataTypes.ENUM,
values: [
"tip",
"follow",
"subscription",
"membership",
"xp_coins",
"order"
],
},
title: {
type: DataTypes.TEXT,
},
body: {
type: DataTypes.TEXT,
},
amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"shown",
"dismissed",
"failed"
],
},
created_at_time: {
type: DataTypes.DATE,
},
shown_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
alerts.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.alerts.belongsTo(db.creator_profiles, {
as: 'creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.alerts.belongsTo(db.alert_profiles, {
as: 'alert_profile',
foreignKey: {
name: 'alert_profileId',
},
constraints: false,
});
db.alerts.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.alerts.hasMany(db.file, {
as: 'media_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.alerts.getTableName(),
belongsToColumn: 'media_images',
},
});
db.alerts.hasMany(db.file, {
as: 'sound_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.alerts.getTableName(),
belongsToColumn: 'sound_files',
},
});
db.alerts.belongsTo(db.users, {
as: 'createdBy',
});
db.alerts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return alerts;
};

View File

@ -0,0 +1,154 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const comments = sequelize.define(
'comments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
target_type: {
type: DataTypes.ENUM,
values: [
"video",
"stream"
],
},
target_key: {
type: DataTypes.TEXT,
},
body: {
type: DataTypes.TEXT,
},
posted_at: {
type: DataTypes.DATE,
},
is_hidden: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
comments.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.comments.belongsTo(db.users, {
as: 'author_user',
foreignKey: {
name: 'author_userId',
},
constraints: false,
});
db.comments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.comments.belongsTo(db.users, {
as: 'createdBy',
});
db.comments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return comments;
};

View File

@ -0,0 +1,306 @@
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 creator_profiles = sequelize.define(
'creator_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
handle: {
type: DataTypes.TEXT,
},
creator_type: {
type: DataTypes.ENUM,
values: [
"streamer",
"youtuber",
"vtuber",
"music_creator",
"artist",
"developer",
"adult_creator",
"other"
],
},
is_verified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_adult_creator: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
slogan: {
type: DataTypes.TEXT,
},
about: {
type: DataTypes.TEXT,
},
business_email: {
type: DataTypes.TEXT,
},
support_email: {
type: DataTypes.TEXT,
},
preferred_language: {
type: DataTypes.TEXT,
},
category_tags: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
creator_profiles.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.creator_profiles.hasMany(db.follows, {
as: 'follows_followed_creator',
foreignKey: {
name: 'followed_creatorId',
},
constraints: false,
});
db.creator_profiles.hasMany(db.discovery_items, {
as: 'discovery_items_creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.creator_profiles.hasMany(db.streams, {
as: 'streams_creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.creator_profiles.hasMany(db.videos, {
as: 'videos_creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.creator_profiles.hasMany(db.tip_pages, {
as: 'tip_pages_creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.creator_profiles.hasMany(db.alerts, {
as: 'alerts_creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.creator_profiles.hasMany(db.overlay_profiles, {
as: 'overlay_profiles_creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.creator_profiles.hasMany(db.merch_stores, {
as: 'merch_stores_creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.creator_profiles.hasMany(db.private_mailboxes, {
as: 'private_mailboxes_owner_creator',
foreignKey: {
name: 'owner_creatorId',
},
constraints: false,
});
//end loop
db.creator_profiles.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.creator_profiles.belongsTo(db.profile_styles, {
as: 'profile_style',
foreignKey: {
name: 'profile_styleId',
},
constraints: false,
});
db.creator_profiles.belongsTo(db.tip_pages, {
as: 'tip_page',
foreignKey: {
name: 'tip_pageId',
},
constraints: false,
});
db.creator_profiles.belongsTo(db.merch_stores, {
as: 'merch_store',
foreignKey: {
name: 'merch_storeId',
},
constraints: false,
});
db.creator_profiles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.creator_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.creator_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return creator_profiles;
};

View File

@ -0,0 +1,153 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const demo_wallets = sequelize.define(
'demo_wallets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
available_balance: {
type: DataTypes.DECIMAL,
},
lifetime_earned: {
type: DataTypes.DECIMAL,
},
lifetime_spent: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
payouts_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
demo_wallets.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.demo_wallets.hasMany(db.wallet_transactions, {
as: 'wallet_transactions_wallet',
foreignKey: {
name: 'walletId',
},
constraints: false,
});
//end loop
db.demo_wallets.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.demo_wallets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.demo_wallets.belongsTo(db.users, {
as: 'createdBy',
});
db.demo_wallets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return demo_wallets;
};

View File

@ -0,0 +1,186 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const discovery_items = sequelize.define(
'discovery_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
item_type: {
type: DataTypes.ENUM,
values: [
"creator",
"stream",
"video",
"product"
],
},
title: {
type: DataTypes.TEXT,
},
subtitle: {
type: DataTypes.TEXT,
},
score: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"active",
"hidden"
],
},
published_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
discovery_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.discovery_items.belongsTo(db.creator_profiles, {
as: 'creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.discovery_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.discovery_items.hasMany(db.file, {
as: 'thumbnail_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.discovery_items.getTableName(),
belongsToColumn: 'thumbnail_images',
},
});
db.discovery_items.belongsTo(db.users, {
as: 'createdBy',
});
db.discovery_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return discovery_items;
};

View File

@ -0,0 +1,148 @@
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 fan_profiles = sequelize.define(
'fan_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
nickname: {
type: DataTypes.TEXT,
},
bio: {
type: DataTypes.TEXT,
},
hide_social_activity: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
xp_coins_balance: {
type: DataTypes.INTEGER,
},
adult_mode_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
fan_profiles.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.fan_profiles.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.fan_profiles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.fan_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.fan_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return fan_profiles;
};

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,132 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const follows = sequelize.define(
'follows',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
followed_at: {
type: DataTypes.DATE,
},
notifications_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
follows.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.follows.belongsTo(db.users, {
as: 'follower_user',
foreignKey: {
name: 'follower_userId',
},
constraints: false,
});
db.follows.belongsTo(db.creator_profiles, {
as: 'followed_creator',
foreignKey: {
name: 'followed_creatorId',
},
constraints: false,
});
db.follows.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.follows.belongsTo(db.users, {
as: 'createdBy',
});
db.follows.belongsTo(db.users, {
as: 'updatedBy',
});
};
return follows;
};

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,190 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const merch_stores = sequelize.define(
'merch_stores',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
store_name: {
type: DataTypes.TEXT,
},
store_description: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
policies_text: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
merch_stores.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.merch_stores.hasMany(db.creator_profiles, {
as: 'creator_profiles_merch_store',
foreignKey: {
name: 'merch_storeId',
},
constraints: false,
});
db.merch_stores.hasMany(db.products, {
as: 'products_merch_store',
foreignKey: {
name: 'merch_storeId',
},
constraints: false,
});
db.merch_stores.hasMany(db.orders, {
as: 'orders_merch_store',
foreignKey: {
name: 'merch_storeId',
},
constraints: false,
});
db.merch_stores.hasMany(db.shipping_profiles, {
as: 'shipping_profiles_merch_store',
foreignKey: {
name: 'merch_storeId',
},
constraints: false,
});
//end loop
db.merch_stores.belongsTo(db.creator_profiles, {
as: 'creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.merch_stores.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.merch_stores.hasMany(db.file, {
as: 'logo_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.merch_stores.getTableName(),
belongsToColumn: 'logo_images',
},
});
db.merch_stores.hasMany(db.file, {
as: 'banner_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.merch_stores.getTableName(),
belongsToColumn: 'banner_images',
},
});
db.merch_stores.belongsTo(db.users, {
as: 'createdBy',
});
db.merch_stores.belongsTo(db.users, {
as: 'updatedBy',
});
};
return merch_stores;
};

View File

@ -0,0 +1,168 @@
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,
},
subject: {
type: DataTypes.TEXT,
},
body: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"unread",
"read",
"archived",
"blocked"
],
},
sent_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.private_mailboxes, {
as: 'mailbox',
foreignKey: {
name: 'mailboxId',
},
constraints: false,
});
db.messages.belongsTo(db.users, {
as: 'from_user',
foreignKey: {
name: 'from_userId',
},
constraints: false,
});
db.messages.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.messages.hasMany(db.file, {
as: 'attachment_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.messages.getTableName(),
belongsToColumn: 'attachment_files',
},
});
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,
},
product_name_snapshot: {
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.product_variants, {
as: 'variant',
foreignKey: {
name: 'variantId',
},
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,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 orders = sequelize.define(
'orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
subtotal: {
type: DataTypes.DECIMAL,
},
shipping_cost: {
type: DataTypes.DECIMAL,
},
tax_total: {
type: DataTypes.DECIMAL,
},
total: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"paid",
"processing",
"shipped",
"delivered",
"canceled",
"refunded"
],
},
payment_method: {
type: DataTypes.ENUM,
values: [
"demo_wallet",
"card_placeholder"
],
},
placed_at: {
type: DataTypes.DATE,
},
paid_at: {
type: DataTypes.DATE,
},
fulfilled_at: {
type: DataTypes.DATE,
},
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,
});
//end loop
db.orders.belongsTo(db.users, {
as: 'buyer_user',
foreignKey: {
name: 'buyer_userId',
},
constraints: false,
});
db.orders.belongsTo(db.merch_stores, {
as: 'merch_store',
foreignKey: {
name: 'merch_storeId',
},
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,338 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const organizations = sequelize.define(
'organizations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
organizations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.organizations.hasMany(db.users, {
as: 'users_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.creator_profiles, {
as: 'creator_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.fan_profiles, {
as: 'fan_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.follows, {
as: 'follows_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.theme_profiles, {
as: 'theme_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.profile_styles, {
as: 'profile_styles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.discovery_items, {
as: 'discovery_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.streams, {
as: 'streams_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.videos, {
as: 'videos_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.comments, {
as: 'comments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.playlists, {
as: 'playlists_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.playlist_items, {
as: 'playlist_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.tip_pages, {
as: 'tip_pages_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.tips, {
as: 'tips_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.alert_profiles, {
as: 'alert_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.alerts, {
as: 'alerts_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.overlay_profiles, {
as: 'overlay_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.widget_catalog_items, {
as: 'widget_catalog_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.overlay_widgets, {
as: 'overlay_widgets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.merch_stores, {
as: 'merch_stores_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.products, {
as: 'products_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.product_variants, {
as: 'product_variants_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.shipping_profiles, {
as: 'shipping_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.private_mailboxes, {
as: 'private_mailboxes_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.messages, {
as: 'messages_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.reports, {
as: 'reports_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.demo_wallets, {
as: 'demo_wallets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.wallet_transactions, {
as: 'wallet_transactions_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,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 overlay_profiles = sequelize.define(
'overlay_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
overlay_type: {
type: DataTypes.ENUM,
values: [
"stream",
"afk",
"music",
"adult"
],
},
access_token: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
canvas_settings_json: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
overlay_profiles.associate = (db) => {
db.overlay_profiles.belongsToMany(db.overlay_widgets, {
as: 'overlay_widgets',
foreignKey: {
name: 'overlay_profiles_overlay_widgetsId',
},
constraints: false,
through: 'overlay_profilesOverlay_widgetsOverlay_widgets',
});
db.overlay_profiles.belongsToMany(db.overlay_widgets, {
as: 'overlay_widgets_filter',
foreignKey: {
name: 'overlay_profiles_overlay_widgetsId',
},
constraints: false,
through: 'overlay_profilesOverlay_widgetsOverlay_widgets',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.overlay_profiles.hasMany(db.streams, {
as: 'streams_overlay_profile',
foreignKey: {
name: 'overlay_profileId',
},
constraints: false,
});
db.overlay_profiles.hasMany(db.overlay_widgets, {
as: 'overlay_widgets_overlay_profile',
foreignKey: {
name: 'overlay_profileId',
},
constraints: false,
});
//end loop
db.overlay_profiles.belongsTo(db.creator_profiles, {
as: 'creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.overlay_profiles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.overlay_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.overlay_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return overlay_profiles;
};

View File

@ -0,0 +1,174 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const overlay_widgets = sequelize.define(
'overlay_widgets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
instance_name: {
type: DataTypes.TEXT,
},
config_json: {
type: DataTypes.TEXT,
},
x: {
type: DataTypes.INTEGER,
},
y: {
type: DataTypes.INTEGER,
},
width: {
type: DataTypes.INTEGER,
},
height: {
type: DataTypes.INTEGER,
},
z_index: {
type: DataTypes.INTEGER,
},
is_visible: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
overlay_widgets.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.overlay_widgets.belongsTo(db.overlay_profiles, {
as: 'overlay_profile',
foreignKey: {
name: 'overlay_profileId',
},
constraints: false,
});
db.overlay_widgets.belongsTo(db.widget_catalog_items, {
as: 'catalog_item',
foreignKey: {
name: 'catalog_itemId',
},
constraints: false,
});
db.overlay_widgets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.overlay_widgets.belongsTo(db.users, {
as: 'createdBy',
});
db.overlay_widgets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return overlay_widgets;
};

View File

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

View File

@ -0,0 +1,144 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const playlist_items = sequelize.define(
'playlist_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
item_type: {
type: DataTypes.ENUM,
values: [
"video",
"track"
],
},
item_key: {
type: DataTypes.TEXT,
},
position: {
type: DataTypes.INTEGER,
},
added_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
playlist_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.playlist_items.belongsTo(db.playlists, {
as: 'playlist',
foreignKey: {
name: 'playlistId',
},
constraints: false,
});
db.playlist_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.playlist_items.belongsTo(db.users, {
as: 'createdBy',
});
db.playlist_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return playlist_items;
};

View File

@ -0,0 +1,168 @@
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 playlists = sequelize.define(
'playlists',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
visibility: {
type: DataTypes.ENUM,
values: [
"public",
"unlisted",
"private"
],
},
collaborative: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
playlists.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.playlists.hasMany(db.playlist_items, {
as: 'playlist_items_playlist',
foreignKey: {
name: 'playlistId',
},
constraints: false,
});
//end loop
db.playlists.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.playlists.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.playlists.hasMany(db.file, {
as: 'cover_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.playlists.getTableName(),
belongsToColumn: 'cover_images',
},
});
db.playlists.belongsTo(db.users, {
as: 'createdBy',
});
db.playlists.belongsTo(db.users, {
as: 'updatedBy',
});
};
return playlists;
};

View File

@ -0,0 +1,158 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const private_mailboxes = sequelize.define(
'private_mailboxes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
public_label: {
type: DataTypes.TEXT,
},
is_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
allow_attachments: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
delivery_mode: {
type: DataTypes.ENUM,
values: [
"inbox_only",
"forward_to_email"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
private_mailboxes.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.private_mailboxes.hasMany(db.messages, {
as: 'messages_mailbox',
foreignKey: {
name: 'mailboxId',
},
constraints: false,
});
//end loop
db.private_mailboxes.belongsTo(db.creator_profiles, {
as: 'owner_creator',
foreignKey: {
name: 'owner_creatorId',
},
constraints: false,
});
db.private_mailboxes.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.private_mailboxes.belongsTo(db.users, {
as: 'createdBy',
});
db.private_mailboxes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return private_mailboxes;
};

View File

@ -0,0 +1,160 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const product_variants = sequelize.define(
'product_variants',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
variant_name: {
type: DataTypes.TEXT,
},
sku: {
type: DataTypes.TEXT,
},
price_override: {
type: DataTypes.DECIMAL,
},
stock_quantity: {
type: DataTypes.INTEGER,
},
attributes_json: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
product_variants.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_variants.hasMany(db.order_items, {
as: 'order_items_variant',
foreignKey: {
name: 'variantId',
},
constraints: false,
});
//end loop
db.product_variants.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.product_variants.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.product_variants.belongsTo(db.users, {
as: 'createdBy',
});
db.product_variants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return product_variants;
};

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 products = sequelize.define(
'products',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
product_type: {
type: DataTypes.ENUM,
values: [
"physical",
"digital"
],
},
price: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
stock_quantity: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_adult: {
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.product_variants, {
as: 'product_variants_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.order_items, {
as: 'order_items_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
//end loop
db.products.belongsTo(db.merch_stores, {
as: 'merch_store',
foreignKey: {
name: 'merch_storeId',
},
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,212 @@
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 profile_styles = sequelize.define(
'profile_styles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
style_name: {
type: DataTypes.TEXT,
},
username_color_hex: {
type: DataTypes.TEXT,
},
bio_font_family: {
type: DataTypes.TEXT,
},
panel_order_json: {
type: DataTypes.TEXT,
},
profile_layout: {
type: DataTypes.ENUM,
values: [
"classic",
"modern",
"minimal",
"streamer",
"storefront"
],
},
show_pronouns_badge: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
pronouns_text: {
type: DataTypes.TEXT,
},
custom_css: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
profile_styles.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.profile_styles.hasMany(db.creator_profiles, {
as: 'creator_profiles_profile_style',
foreignKey: {
name: 'profile_styleId',
},
constraints: false,
});
//end loop
db.profile_styles.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.profile_styles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.profile_styles.hasMany(db.file, {
as: 'avatar_frame_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.profile_styles.getTableName(),
belongsToColumn: 'avatar_frame_images',
},
});
db.profile_styles.hasMany(db.file, {
as: 'banner_background_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.profile_styles.getTableName(),
belongsToColumn: 'banner_background_images',
},
});
db.profile_styles.belongsTo(db.users, {
as: 'createdBy',
});
db.profile_styles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return profile_styles;
};

View File

@ -0,0 +1,219 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const reports = sequelize.define(
'reports',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
target_type: {
type: DataTypes.ENUM,
values: [
"creator",
"video",
"stream",
"comment",
"message",
"product"
],
},
target_key: {
type: DataTypes.TEXT,
},
reason: {
type: DataTypes.ENUM,
values: [
"spam",
"harassment",
"impersonation",
"nudity",
"hate",
"illegal",
"copyright",
"other"
],
},
details: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"in_review",
"actioned",
"dismissed"
],
},
reported_at: {
type: DataTypes.DATE,
},
resolved_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
reports.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.reports.belongsTo(db.users, {
as: 'reporter_user',
foreignKey: {
name: 'reporter_userId',
},
constraints: false,
});
db.reports.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.reports.belongsTo(db.users, {
as: 'createdBy',
});
db.reports.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reports;
};

View File

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

View File

@ -0,0 +1,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 shipping_profiles = sequelize.define(
'shipping_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
profile_name: {
type: DataTypes.TEXT,
},
origin_country: {
type: DataTypes.TEXT,
},
origin_region: {
type: DataTypes.TEXT,
},
origin_postal_code: {
type: DataTypes.TEXT,
},
rules_json: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
shipping_profiles.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.shipping_profiles.belongsTo(db.merch_stores, {
as: 'merch_store',
foreignKey: {
name: 'merch_storeId',
},
constraints: false,
});
db.shipping_profiles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.shipping_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.shipping_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return shipping_profiles;
};

View File

@ -0,0 +1,228 @@
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 streams = sequelize.define(
'streams',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
category: {
type: DataTypes.ENUM,
values: [
"gaming",
"just_chatting",
"music",
"art",
"dev",
"watch_party",
"adult",
"other"
],
},
is_live: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_adult: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
scheduled_start_at: {
type: DataTypes.DATE,
},
started_at: {
type: DataTypes.DATE,
},
ended_at: {
type: DataTypes.DATE,
},
viewer_count: {
type: DataTypes.INTEGER,
},
stream_key_hint: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
streams.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.streams.belongsTo(db.creator_profiles, {
as: 'creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.streams.belongsTo(db.overlay_profiles, {
as: 'overlay_profile',
foreignKey: {
name: 'overlay_profileId',
},
constraints: false,
});
db.streams.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.streams.hasMany(db.file, {
as: 'thumbnail_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.streams.getTableName(),
belongsToColumn: 'thumbnail_images',
},
});
db.streams.belongsTo(db.users, {
as: 'createdBy',
});
db.streams.belongsTo(db.users, {
as: 'updatedBy',
});
};
return streams;
};

View File

@ -0,0 +1,250 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const theme_profiles = sequelize.define(
'theme_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
mode: {
type: DataTypes.ENUM,
values: [
"auto_time",
"manual",
"holiday"
],
},
theme_name: {
type: DataTypes.TEXT,
},
primary_color_hex: {
type: DataTypes.TEXT,
},
accent_color_hex: {
type: DataTypes.TEXT,
},
neon_glow_color_hex: {
type: DataTypes.TEXT,
},
rgb_cycle_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
rgb_cycle_speed: {
type: DataTypes.INTEGER,
},
holiday_palette: {
type: DataTypes.ENUM,
values: [
"none",
"new_year",
"valentines",
"st_patricks",
"easter",
"ramadan",
"eid",
"pride",
"halloween",
"thanksgiving",
"hanukkah",
"christmas",
"lunar_new_year",
"diwali",
"other"
],
},
adult_palette_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
adult_primary_color_hex: {
type: DataTypes.TEXT,
},
adult_accent_color_hex: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
theme_profiles.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.theme_profiles.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.theme_profiles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.theme_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.theme_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return theme_profiles;
};

View File

@ -0,0 +1,245 @@
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 tip_pages = sequelize.define(
'tip_pages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
slug: {
type: DataTypes.TEXT,
},
headline: {
type: DataTypes.TEXT,
},
thank_you_message: {
type: DataTypes.TEXT,
},
background_type: {
type: DataTypes.ENUM,
values: [
"color",
"gradient",
"image",
"video"
],
},
background_value: {
type: DataTypes.TEXT,
},
accent_color_hex: {
type: DataTypes.TEXT,
},
preset_amount_1: {
type: DataTypes.INTEGER,
},
preset_amount_2: {
type: DataTypes.INTEGER,
},
preset_amount_3: {
type: DataTypes.INTEGER,
},
allow_custom_amount: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
minimum_amount: {
type: DataTypes.INTEGER,
},
tts_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
tts_voice: {
type: DataTypes.TEXT,
},
show_supporter_feed: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tip_pages.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.tip_pages.hasMany(db.creator_profiles, {
as: 'creator_profiles_tip_page',
foreignKey: {
name: 'tip_pageId',
},
constraints: false,
});
db.tip_pages.hasMany(db.tips, {
as: 'tips_tip_page',
foreignKey: {
name: 'tip_pageId',
},
constraints: false,
});
//end loop
db.tip_pages.belongsTo(db.creator_profiles, {
as: 'creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.tip_pages.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.tip_pages.belongsTo(db.users, {
as: 'createdBy',
});
db.tip_pages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tip_pages;
};

View File

@ -0,0 +1,175 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const tips = sequelize.define(
'tips',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
message: {
type: DataTypes.TEXT,
},
is_anonymous: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"completed",
"refunded",
"failed"
],
},
sent_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tips.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.tips.belongsTo(db.tip_pages, {
as: 'tip_page',
foreignKey: {
name: 'tip_pageId',
},
constraints: false,
});
db.tips.belongsTo(db.users, {
as: 'from_user',
foreignKey: {
name: 'from_userId',
},
constraints: false,
});
db.tips.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.tips.belongsTo(db.users, {
as: 'createdBy',
});
db.tips.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tips;
};

View File

@ -0,0 +1,368 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const users = sequelize.define(
'users',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
firstName: {
type: DataTypes.TEXT,
},
lastName: {
type: DataTypes.TEXT,
},
phoneNumber: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
disabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
password: {
type: DataTypes.TEXT,
},
emailVerified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
emailVerificationToken: {
type: DataTypes.TEXT,
},
emailVerificationTokenExpiresAt: {
type: DataTypes.DATE,
},
passwordResetToken: {
type: DataTypes.TEXT,
},
passwordResetTokenExpiresAt: {
type: DataTypes.DATE,
},
provider: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
users.associate = (db) => {
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions_filter',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.users.hasMany(db.creator_profiles, {
as: 'creator_profiles_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.fan_profiles, {
as: 'fan_profiles_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.follows, {
as: 'follows_follower_user',
foreignKey: {
name: 'follower_userId',
},
constraints: false,
});
db.users.hasMany(db.theme_profiles, {
as: 'theme_profiles_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.users.hasMany(db.profile_styles, {
as: 'profile_styles_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.users.hasMany(db.comments, {
as: 'comments_author_user',
foreignKey: {
name: 'author_userId',
},
constraints: false,
});
db.users.hasMany(db.playlists, {
as: 'playlists_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.users.hasMany(db.tips, {
as: 'tips_from_user',
foreignKey: {
name: 'from_userId',
},
constraints: false,
});
db.users.hasMany(db.alert_profiles, {
as: 'alert_profiles_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.users.hasMany(db.orders, {
as: 'orders_buyer_user',
foreignKey: {
name: 'buyer_userId',
},
constraints: false,
});
db.users.hasMany(db.messages, {
as: 'messages_from_user',
foreignKey: {
name: 'from_userId',
},
constraints: false,
});
db.users.hasMany(db.reports, {
as: 'reports_reporter_user',
foreignKey: {
name: 'reporter_userId',
},
constraints: false,
});
db.users.hasMany(db.demo_wallets, {
as: 'demo_wallets_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

View File

@ -0,0 +1,205 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const videos = sequelize.define(
'videos',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
visibility: {
type: DataTypes.ENUM,
values: [
"public",
"unlisted",
"private"
],
},
is_adult: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
published_at: {
type: DataTypes.DATE,
},
duration_seconds: {
type: DataTypes.INTEGER,
},
view_count: {
type: DataTypes.INTEGER,
},
like_count: {
type: DataTypes.INTEGER,
},
comment_count: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
videos.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.videos.belongsTo(db.creator_profiles, {
as: 'creator',
foreignKey: {
name: 'creatorId',
},
constraints: false,
});
db.videos.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.videos.hasMany(db.file, {
as: 'thumbnail_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.videos.getTableName(),
belongsToColumn: 'thumbnail_images',
},
});
db.videos.hasMany(db.file, {
as: 'video_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.videos.getTableName(),
belongsToColumn: 'video_files',
},
});
db.videos.belongsTo(db.users, {
as: 'createdBy',
});
db.videos.belongsTo(db.users, {
as: 'updatedBy',
});
};
return videos;
};

View File

@ -0,0 +1,183 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const wallet_transactions = sequelize.define(
'wallet_transactions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
direction: {
type: DataTypes.ENUM,
values: [
"credit",
"debit"
],
},
kind: {
type: DataTypes.ENUM,
values: [
"tip",
"order",
"refund",
"admin_adjustment",
"xp_coins"
],
},
amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
reference_key: {
type: DataTypes.TEXT,
},
note: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
wallet_transactions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.wallet_transactions.belongsTo(db.demo_wallets, {
as: 'wallet',
foreignKey: {
name: 'walletId',
},
constraints: false,
});
db.wallet_transactions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.wallet_transactions.belongsTo(db.users, {
as: 'createdBy',
});
db.wallet_transactions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return wallet_transactions;
};

View File

@ -0,0 +1,203 @@
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 widget_catalog_items = sequelize.define(
'widget_catalog_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
icon_name: {
type: DataTypes.TEXT,
},
author_name: {
type: DataTypes.TEXT,
},
widget_type: {
type: DataTypes.ENUM,
values: [
"chat_box",
"goal_meter",
"sub_bar",
"now_playing",
"poll",
"alert_box",
"custom"
],
},
description: {
type: DataTypes.TEXT,
},
is_public: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_adult_only: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
schema_json: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
widget_catalog_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.widget_catalog_items.hasMany(db.overlay_widgets, {
as: 'overlay_widgets_catalog_item',
foreignKey: {
name: 'catalog_itemId',
},
constraints: false,
});
//end loop
db.widget_catalog_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.widget_catalog_items.hasMany(db.file, {
as: 'bundle_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.widget_catalog_items.getTableName(),
belongsToColumn: 'bundle_files',
},
});
db.widget_catalog_items.belongsTo(db.users, {
as: 'createdBy',
});
db.widget_catalog_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return widget_catalog_items;
};

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

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

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

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

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

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

@ -0,0 +1,265 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const organizationForAuthRoutes = require('./routes/organizationLogin');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const organizationsRoutes = require('./routes/organizations');
const creator_profilesRoutes = require('./routes/creator_profiles');
const fan_profilesRoutes = require('./routes/fan_profiles');
const followsRoutes = require('./routes/follows');
const theme_profilesRoutes = require('./routes/theme_profiles');
const profile_stylesRoutes = require('./routes/profile_styles');
const discovery_itemsRoutes = require('./routes/discovery_items');
const streamsRoutes = require('./routes/streams');
const videosRoutes = require('./routes/videos');
const commentsRoutes = require('./routes/comments');
const playlistsRoutes = require('./routes/playlists');
const playlist_itemsRoutes = require('./routes/playlist_items');
const tip_pagesRoutes = require('./routes/tip_pages');
const tipsRoutes = require('./routes/tips');
const alert_profilesRoutes = require('./routes/alert_profiles');
const alertsRoutes = require('./routes/alerts');
const overlay_profilesRoutes = require('./routes/overlay_profiles');
const widget_catalog_itemsRoutes = require('./routes/widget_catalog_items');
const overlay_widgetsRoutes = require('./routes/overlay_widgets');
const merch_storesRoutes = require('./routes/merch_stores');
const productsRoutes = require('./routes/products');
const product_variantsRoutes = require('./routes/product_variants');
const ordersRoutes = require('./routes/orders');
const order_itemsRoutes = require('./routes/order_items');
const shipping_profilesRoutes = require('./routes/shipping_profiles');
const private_mailboxesRoutes = require('./routes/private_mailboxes');
const messagesRoutes = require('./routes/messages');
const reportsRoutes = require('./routes/reports');
const demo_walletsRoutes = require('./routes/demo_wallets');
const wallet_transactionsRoutes = require('./routes/wallet_transactions');
const getBaseUrl = (url) => {
if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url;
};
const options = {
definition: {
openapi: "3.0.0",
info: {
version: "1.0.0",
title: "Xpansion Creator Platform",
description: "Xpansion Creator Platform Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
},
servers: [
{
url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
description: "Development server",
}
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
},
responses: {
UnauthorizedError: {
description: "Access token is missing or invalid"
}
}
},
security: [{
bearerAuth: []
}]
},
apis: ["./src/routes/*.js"],
};
const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
next()
}, swaggerUI.serve, swaggerUI.setup(specs))
app.use(cors({origin: true}));
require('./auth/auth');
app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');
app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);
app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);
app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);
app.use('/api/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);
app.use('/api/creator_profiles', passport.authenticate('jwt', {session: false}), creator_profilesRoutes);
app.use('/api/fan_profiles', passport.authenticate('jwt', {session: false}), fan_profilesRoutes);
app.use('/api/follows', passport.authenticate('jwt', {session: false}), followsRoutes);
app.use('/api/theme_profiles', passport.authenticate('jwt', {session: false}), theme_profilesRoutes);
app.use('/api/profile_styles', passport.authenticate('jwt', {session: false}), profile_stylesRoutes);
app.use('/api/discovery_items', passport.authenticate('jwt', {session: false}), discovery_itemsRoutes);
app.use('/api/streams', passport.authenticate('jwt', {session: false}), streamsRoutes);
app.use('/api/videos', passport.authenticate('jwt', {session: false}), videosRoutes);
app.use('/api/comments', passport.authenticate('jwt', {session: false}), commentsRoutes);
app.use('/api/playlists', passport.authenticate('jwt', {session: false}), playlistsRoutes);
app.use('/api/playlist_items', passport.authenticate('jwt', {session: false}), playlist_itemsRoutes);
app.use('/api/tip_pages', passport.authenticate('jwt', {session: false}), tip_pagesRoutes);
app.use('/api/tips', passport.authenticate('jwt', {session: false}), tipsRoutes);
app.use('/api/alert_profiles', passport.authenticate('jwt', {session: false}), alert_profilesRoutes);
app.use('/api/alerts', passport.authenticate('jwt', {session: false}), alertsRoutes);
app.use('/api/overlay_profiles', passport.authenticate('jwt', {session: false}), overlay_profilesRoutes);
app.use('/api/widget_catalog_items', passport.authenticate('jwt', {session: false}), widget_catalog_itemsRoutes);
app.use('/api/overlay_widgets', passport.authenticate('jwt', {session: false}), overlay_widgetsRoutes);
app.use('/api/merch_stores', passport.authenticate('jwt', {session: false}), merch_storesRoutes);
app.use('/api/products', passport.authenticate('jwt', {session: false}), productsRoutes);
app.use('/api/product_variants', passport.authenticate('jwt', {session: false}), product_variantsRoutes);
app.use('/api/orders', passport.authenticate('jwt', {session: false}), ordersRoutes);
app.use('/api/order_items', passport.authenticate('jwt', {session: false}), order_itemsRoutes);
app.use('/api/shipping_profiles', passport.authenticate('jwt', {session: false}), shipping_profilesRoutes);
app.use('/api/private_mailboxes', passport.authenticate('jwt', {session: false}), private_mailboxesRoutes);
app.use('/api/messages', passport.authenticate('jwt', {session: false}), messagesRoutes);
app.use('/api/reports', passport.authenticate('jwt', {session: false}), reportsRoutes);
app.use('/api/demo_wallets', passport.authenticate('jwt', {session: false}), demo_walletsRoutes);
app.use('/api/wallet_transactions', passport.authenticate('jwt', {session: false}), wallet_transactionsRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
app.use(
'/api/org-for-auth',
organizationForAuthRoutes,
);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
db.sequelize.sync().then(function () {
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
});
module.exports = app;

View File

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

View File

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

View File

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

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