Initial version

This commit is contained in:
Flatlogic Bot 2026-02-18 06:59:51 +00:00
commit 75053eda90
839 changed files with 313438 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>СВЕМА — дистрибуция музыки</h2>
<p>Платформа бесплатной дистрибуции музыки с кабинетом артиста, релизами, роялти, аналитикой и смарт-ссылками.</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 @@
# СВЕМА — дистрибуция музыки
## 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_38553
DB_USER=app_38553
DB_PASS=b69060f4-750b-4314-b054-fbc0fceaa28a
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 @@
#СВЕМА — дистрибуция музыки - 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___________________________;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db___________________________ 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": "generated_app",
"description": "СВЕМА — дистрибуция музыки - 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: "b69060f4",
user_pass: "fbc0fceaa28a",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'b69060f4-750b-4314-b054-fbc0fceaa28a',
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: 'СВЕМА — дистрибуция музыки <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: 'Artist Manager',
},
project_uuid: 'b69060f4-750b-4314-b054-fbc0fceaa28a',
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 = 'ocean waves abstract pattern';
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,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 Activity_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const activity_events = await db.activity_events.create(
{
id: data.id || undefined,
event_kind: data.event_kind
||
null
,
headline: data.headline
||
null
,
details: data.details
||
null
,
occurred_at: data.occurred_at
||
null
,
entity_name: data.entity_name
||
null
,
entity_key: data.entity_key
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await activity_events.setUser( data.user || null, {
transaction,
});
await activity_events.setOrganizations( data.organizations || null, {
transaction,
});
return activity_events;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const activity_eventsData = data.map((item, index) => ({
id: item.id || undefined,
event_kind: item.event_kind
||
null
,
headline: item.headline
||
null
,
details: item.details
||
null
,
occurred_at: item.occurred_at
||
null
,
entity_name: item.entity_name
||
null
,
entity_key: item.entity_key
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const activity_events = await db.activity_events.bulkCreate(activity_eventsData, { transaction });
// For each item created, replace relation files
return activity_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const activity_events = await db.activity_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.event_kind !== undefined) updatePayload.event_kind = data.event_kind;
if (data.headline !== undefined) updatePayload.headline = data.headline;
if (data.details !== undefined) updatePayload.details = data.details;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
if (data.entity_name !== undefined) updatePayload.entity_name = data.entity_name;
if (data.entity_key !== undefined) updatePayload.entity_key = data.entity_key;
updatePayload.updatedById = currentUser.id;
await activity_events.update(updatePayload, {transaction});
if (data.user !== undefined) {
await activity_events.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await activity_events.setOrganizations(
data.organizations,
{ transaction }
);
}
return activity_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const activity_events = await db.activity_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of activity_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of activity_events) {
await record.destroy({transaction});
}
});
return activity_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const activity_events = await db.activity_events.findByPk(id, options);
await activity_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await activity_events.destroy({
transaction
});
return activity_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const activity_events = await db.activity_events.findOne(
{ where },
{ transaction },
);
if (!activity_events) {
return activity_events;
}
const output = activity_events.get({plain: true});
output.user = await activity_events.getUser({
transaction
});
output.organizations = await activity_events.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: '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.headline) {
where = {
...where,
[Op.and]: Utils.ilike(
'activity_events',
'headline',
filter.headline,
),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'activity_events',
'details',
filter.details,
),
};
}
if (filter.entity_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'activity_events',
'entity_name',
filter.entity_name,
),
};
}
if (filter.entity_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'activity_events',
'entity_key',
filter.entity_key,
),
};
}
if (filter.occurred_atRange) {
const [start, end] = filter.occurred_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.event_kind) {
where = {
...where,
event_kind: filter.event_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.activity_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'activity_events',
'headline',
query,
),
],
};
}
const records = await db.activity_events.findAll({
attributes: [ 'id', 'headline' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['headline', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.headline,
}));
}
};

View File

@ -0,0 +1,857 @@
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 Analytics_dailyDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analytics_daily = await db.analytics_daily.create(
{
id: data.id || undefined,
metric_date: data.metric_date
||
null
,
streams: data.streams
||
null
,
unique_listeners: data.unique_listeners
||
null
,
saves: data.saves
||
null
,
likes: data.likes
||
null
,
shares: data.shares
||
null
,
country: data.country
||
null
,
city: data.city
||
null
,
traffic_source: data.traffic_source
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await analytics_daily.setArtist_profile( data.artist_profile || null, {
transaction,
});
await analytics_daily.setPlatform( data.platform || null, {
transaction,
});
await analytics_daily.setRelease( data.release || null, {
transaction,
});
await analytics_daily.setTrack( data.track || null, {
transaction,
});
await analytics_daily.setOrganizations( data.organizations || null, {
transaction,
});
return analytics_daily;
}
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 analytics_dailyData = data.map((item, index) => ({
id: item.id || undefined,
metric_date: item.metric_date
||
null
,
streams: item.streams
||
null
,
unique_listeners: item.unique_listeners
||
null
,
saves: item.saves
||
null
,
likes: item.likes
||
null
,
shares: item.shares
||
null
,
country: item.country
||
null
,
city: item.city
||
null
,
traffic_source: item.traffic_source
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const analytics_daily = await db.analytics_daily.bulkCreate(analytics_dailyData, { transaction });
// For each item created, replace relation files
return analytics_daily;
}
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 analytics_daily = await db.analytics_daily.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.metric_date !== undefined) updatePayload.metric_date = data.metric_date;
if (data.streams !== undefined) updatePayload.streams = data.streams;
if (data.unique_listeners !== undefined) updatePayload.unique_listeners = data.unique_listeners;
if (data.saves !== undefined) updatePayload.saves = data.saves;
if (data.likes !== undefined) updatePayload.likes = data.likes;
if (data.shares !== undefined) updatePayload.shares = data.shares;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.traffic_source !== undefined) updatePayload.traffic_source = data.traffic_source;
updatePayload.updatedById = currentUser.id;
await analytics_daily.update(updatePayload, {transaction});
if (data.artist_profile !== undefined) {
await analytics_daily.setArtist_profile(
data.artist_profile,
{ transaction }
);
}
if (data.platform !== undefined) {
await analytics_daily.setPlatform(
data.platform,
{ transaction }
);
}
if (data.release !== undefined) {
await analytics_daily.setRelease(
data.release,
{ transaction }
);
}
if (data.track !== undefined) {
await analytics_daily.setTrack(
data.track,
{ transaction }
);
}
if (data.organizations !== undefined) {
await analytics_daily.setOrganizations(
data.organizations,
{ transaction }
);
}
return analytics_daily;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analytics_daily = await db.analytics_daily.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of analytics_daily) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of analytics_daily) {
await record.destroy({transaction});
}
});
return analytics_daily;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const analytics_daily = await db.analytics_daily.findByPk(id, options);
await analytics_daily.update({
deletedBy: currentUser.id
}, {
transaction,
});
await analytics_daily.destroy({
transaction
});
return analytics_daily;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const analytics_daily = await db.analytics_daily.findOne(
{ where },
{ transaction },
);
if (!analytics_daily) {
return analytics_daily;
}
const output = analytics_daily.get({plain: true});
output.artist_profile = await analytics_daily.getArtist_profile({
transaction
});
output.platform = await analytics_daily.getPlatform({
transaction
});
output.release = await analytics_daily.getRelease({
transaction
});
output.track = await analytics_daily.getTrack({
transaction
});
output.organizations = await analytics_daily.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.artist_profiles,
as: 'artist_profile',
where: filter.artist_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.artist_profile.split('|').map(term => Utils.uuid(term)) } },
{
artist_name: {
[Op.or]: filter.artist_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.distribution_platforms,
as: 'platform',
where: filter.platform ? {
[Op.or]: [
{ id: { [Op.in]: filter.platform.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.platform.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.releases,
as: 'release',
where: filter.release ? {
[Op.or]: [
{ id: { [Op.in]: filter.release.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.release.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.tracks,
as: 'track',
where: filter.track ? {
[Op.or]: [
{ id: { [Op.in]: filter.track.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.track.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.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'analytics_daily',
'country',
filter.country,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'analytics_daily',
'city',
filter.city,
),
};
}
if (filter.traffic_source) {
where = {
...where,
[Op.and]: Utils.ilike(
'analytics_daily',
'traffic_source',
filter.traffic_source,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
metric_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
metric_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.metric_dateRange) {
const [start, end] = filter.metric_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
metric_date: {
...where.metric_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
metric_date: {
...where.metric_date,
[Op.lte]: end,
},
};
}
}
if (filter.streamsRange) {
const [start, end] = filter.streamsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
streams: {
...where.streams,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
streams: {
...where.streams,
[Op.lte]: end,
},
};
}
}
if (filter.unique_listenersRange) {
const [start, end] = filter.unique_listenersRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unique_listeners: {
...where.unique_listeners,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unique_listeners: {
...where.unique_listeners,
[Op.lte]: end,
},
};
}
}
if (filter.savesRange) {
const [start, end] = filter.savesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
saves: {
...where.saves,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
saves: {
...where.saves,
[Op.lte]: end,
},
};
}
}
if (filter.likesRange) {
const [start, end] = filter.likesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
likes: {
...where.likes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
likes: {
...where.likes,
[Op.lte]: end,
},
};
}
}
if (filter.sharesRange) {
const [start, end] = filter.sharesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
shares: {
...where.shares,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
shares: {
...where.shares,
[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.analytics_daily.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(
'analytics_daily',
'traffic_source',
query,
),
],
};
}
const records = await db.analytics_daily.findAll({
attributes: [ 'id', 'traffic_source' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['traffic_source', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.traffic_source,
}));
}
};

View File

@ -0,0 +1,624 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Api_keysDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const api_keys = await db.api_keys.create(
{
id: data.id || undefined,
name: data.name
||
null
,
key_prefix: data.key_prefix
||
null
,
key_hash: data.key_hash
||
null
,
scopes: data.scopes
||
null
,
last_used_at: data.last_used_at
||
null
,
expires_at: data.expires_at
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await api_keys.setUser( data.user || null, {
transaction,
});
await api_keys.setOrganizations( data.organizations || null, {
transaction,
});
return api_keys;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const api_keysData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
key_prefix: item.key_prefix
||
null
,
key_hash: item.key_hash
||
null
,
scopes: item.scopes
||
null
,
last_used_at: item.last_used_at
||
null
,
expires_at: item.expires_at
||
null
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const api_keys = await db.api_keys.bulkCreate(api_keysData, { transaction });
// For each item created, replace relation files
return api_keys;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const api_keys = await db.api_keys.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.key_prefix !== undefined) updatePayload.key_prefix = data.key_prefix;
if (data.key_hash !== undefined) updatePayload.key_hash = data.key_hash;
if (data.scopes !== undefined) updatePayload.scopes = data.scopes;
if (data.last_used_at !== undefined) updatePayload.last_used_at = data.last_used_at;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await api_keys.update(updatePayload, {transaction});
if (data.user !== undefined) {
await api_keys.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await api_keys.setOrganizations(
data.organizations,
{ transaction }
);
}
return api_keys;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const api_keys = await db.api_keys.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of api_keys) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of api_keys) {
await record.destroy({transaction});
}
});
return api_keys;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const api_keys = await db.api_keys.findByPk(id, options);
await api_keys.update({
deletedBy: currentUser.id
}, {
transaction,
});
await api_keys.destroy({
transaction
});
return api_keys;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const api_keys = await db.api_keys.findOne(
{ where },
{ transaction },
);
if (!api_keys) {
return api_keys;
}
const output = api_keys.get({plain: true});
output.user = await api_keys.getUser({
transaction
});
output.organizations = await api_keys.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.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_keys',
'name',
filter.name,
),
};
}
if (filter.key_prefix) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_keys',
'key_prefix',
filter.key_prefix,
),
};
}
if (filter.key_hash) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_keys',
'key_hash',
filter.key_hash,
),
};
}
if (filter.scopes) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_keys',
'scopes',
filter.scopes,
),
};
}
if (filter.last_used_atRange) {
const [start, end] = filter.last_used_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_used_at: {
...where.last_used_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_used_at: {
...where.last_used_at,
[Op.lte]: end,
},
};
}
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.api_keys.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'api_keys',
'name',
query,
),
],
};
}
const records = await db.api_keys.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,800 @@
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 Artist_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const artist_profiles = await db.artist_profiles.create(
{
id: data.id || undefined,
artist_name: data.artist_name
||
null
,
profile_type: data.profile_type
||
null
,
legal_name: data.legal_name
||
null
,
country: data.country
||
null
,
city: data.city
||
null
,
tax_residency: data.tax_residency
||
null
,
payout_currency: data.payout_currency
||
null
,
bio: data.bio
||
null
,
website_url: data.website_url
||
null
,
vk_url: data.vk_url
||
null
,
youtube_url: data.youtube_url
||
null
,
tiktok_url: data.tiktok_url
||
null
,
instagram_url: data.instagram_url
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await artist_profiles.setUser( data.user || null, {
transaction,
});
await artist_profiles.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.artist_profiles.getTableName(),
belongsToColumn: 'press_photos',
belongsToId: artist_profiles.id,
},
data.press_photos,
options,
);
return artist_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 artist_profilesData = data.map((item, index) => ({
id: item.id || undefined,
artist_name: item.artist_name
||
null
,
profile_type: item.profile_type
||
null
,
legal_name: item.legal_name
||
null
,
country: item.country
||
null
,
city: item.city
||
null
,
tax_residency: item.tax_residency
||
null
,
payout_currency: item.payout_currency
||
null
,
bio: item.bio
||
null
,
website_url: item.website_url
||
null
,
vk_url: item.vk_url
||
null
,
youtube_url: item.youtube_url
||
null
,
tiktok_url: item.tiktok_url
||
null
,
instagram_url: item.instagram_url
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const artist_profiles = await db.artist_profiles.bulkCreate(artist_profilesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < artist_profiles.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.artist_profiles.getTableName(),
belongsToColumn: 'press_photos',
belongsToId: artist_profiles[i].id,
},
data[i].press_photos,
options,
);
}
return artist_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 artist_profiles = await db.artist_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.artist_name !== undefined) updatePayload.artist_name = data.artist_name;
if (data.profile_type !== undefined) updatePayload.profile_type = data.profile_type;
if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.tax_residency !== undefined) updatePayload.tax_residency = data.tax_residency;
if (data.payout_currency !== undefined) updatePayload.payout_currency = data.payout_currency;
if (data.bio !== undefined) updatePayload.bio = data.bio;
if (data.website_url !== undefined) updatePayload.website_url = data.website_url;
if (data.vk_url !== undefined) updatePayload.vk_url = data.vk_url;
if (data.youtube_url !== undefined) updatePayload.youtube_url = data.youtube_url;
if (data.tiktok_url !== undefined) updatePayload.tiktok_url = data.tiktok_url;
if (data.instagram_url !== undefined) updatePayload.instagram_url = data.instagram_url;
updatePayload.updatedById = currentUser.id;
await artist_profiles.update(updatePayload, {transaction});
if (data.user !== undefined) {
await artist_profiles.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await artist_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.artist_profiles.getTableName(),
belongsToColumn: 'press_photos',
belongsToId: artist_profiles.id,
},
data.press_photos,
options,
);
return artist_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const artist_profiles = await db.artist_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of artist_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of artist_profiles) {
await record.destroy({transaction});
}
});
return artist_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const artist_profiles = await db.artist_profiles.findByPk(id, options);
await artist_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await artist_profiles.destroy({
transaction
});
return artist_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const artist_profiles = await db.artist_profiles.findOne(
{ where },
{ transaction },
);
if (!artist_profiles) {
return artist_profiles;
}
const output = artist_profiles.get({plain: true});
output.releases_artist_profile = await artist_profiles.getReleases_artist_profile({
transaction
});
output.pitch_requests_artist_profile = await artist_profiles.getPitch_requests_artist_profile({
transaction
});
output.royalty_reports_artist_profile = await artist_profiles.getRoyalty_reports_artist_profile({
transaction
});
output.analytics_daily_artist_profile = await artist_profiles.getAnalytics_daily_artist_profile({
transaction
});
output.user = await artist_profiles.getUser({
transaction
});
output.press_photos = await artist_profiles.getPress_photos({
transaction
});
output.organizations = await artist_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',
},
{
model: db.file,
as: 'press_photos',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.artist_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'artist_name',
filter.artist_name,
),
};
}
if (filter.legal_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'legal_name',
filter.legal_name,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'country',
filter.country,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'city',
filter.city,
),
};
}
if (filter.tax_residency) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'tax_residency',
filter.tax_residency,
),
};
}
if (filter.payout_currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'payout_currency',
filter.payout_currency,
),
};
}
if (filter.bio) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'bio',
filter.bio,
),
};
}
if (filter.website_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'website_url',
filter.website_url,
),
};
}
if (filter.vk_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'vk_url',
filter.vk_url,
),
};
}
if (filter.youtube_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'youtube_url',
filter.youtube_url,
),
};
}
if (filter.tiktok_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'tiktok_url',
filter.tiktok_url,
),
};
}
if (filter.instagram_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'artist_profiles',
'instagram_url',
filter.instagram_url,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.profile_type) {
where = {
...where,
profile_type: filter.profile_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.artist_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(
'artist_profiles',
'artist_name',
query,
),
],
};
}
const records = await db.artist_profiles.findAll({
attributes: [ 'id', 'artist_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['artist_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.artist_name,
}));
}
};

View File

@ -0,0 +1,662 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Blog_postsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const blog_posts = await db.blog_posts.create(
{
id: data.id || undefined,
title: data.title
||
null
,
slug: data.slug
||
null
,
category: data.category
||
null
,
excerpt: data.excerpt
||
null
,
content: data.content
||
null
,
is_published: data.is_published
||
false
,
published_at: data.published_at
||
null
,
seo_title: data.seo_title
||
null
,
seo_description: data.seo_description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await blog_posts.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: blog_posts.id,
},
data.cover_image,
options,
);
return blog_posts;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const blog_postsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
slug: item.slug
||
null
,
category: item.category
||
null
,
excerpt: item.excerpt
||
null
,
content: item.content
||
null
,
is_published: item.is_published
||
false
,
published_at: item.published_at
||
null
,
seo_title: item.seo_title
||
null
,
seo_description: item.seo_description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const blog_posts = await db.blog_posts.bulkCreate(blog_postsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < blog_posts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: blog_posts[i].id,
},
data[i].cover_image,
options,
);
}
return blog_posts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const blog_posts = await db.blog_posts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.excerpt !== undefined) updatePayload.excerpt = data.excerpt;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
if (data.seo_title !== undefined) updatePayload.seo_title = data.seo_title;
if (data.seo_description !== undefined) updatePayload.seo_description = data.seo_description;
updatePayload.updatedById = currentUser.id;
await blog_posts.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await blog_posts.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: blog_posts.id,
},
data.cover_image,
options,
);
return blog_posts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const blog_posts = await db.blog_posts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of blog_posts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of blog_posts) {
await record.destroy({transaction});
}
});
return blog_posts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const blog_posts = await db.blog_posts.findByPk(id, options);
await blog_posts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await blog_posts.destroy({
transaction
});
return blog_posts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const blog_posts = await db.blog_posts.findOne(
{ where },
{ transaction },
);
if (!blog_posts) {
return blog_posts;
}
const output = blog_posts.get({plain: true});
output.cover_image = await blog_posts.getCover_image({
transaction
});
output.organizations = await blog_posts.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'cover_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_posts',
'title',
filter.title,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_posts',
'slug',
filter.slug,
),
};
}
if (filter.excerpt) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_posts',
'excerpt',
filter.excerpt,
),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_posts',
'content',
filter.content,
),
};
}
if (filter.seo_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_posts',
'seo_title',
filter.seo_title,
),
};
}
if (filter.seo_description) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_posts',
'seo_description',
filter.seo_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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.is_published) {
where = {
...where,
is_published: filter.is_published,
};
}
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.blog_posts.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'blog_posts',
'title',
query,
),
],
};
}
const records = await db.blog_posts.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,550 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Contact_messagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const contact_messages = await db.contact_messages.create(
{
id: data.id || undefined,
name: data.name
||
null
,
email: data.email
||
null
,
subject: data.subject
||
null
,
message: data.message
||
null
,
status: data.status
||
null
,
submitted_at: data.submitted_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await contact_messages.setOrganizations( data.organizations || null, {
transaction,
});
return contact_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 contact_messagesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
email: item.email
||
null
,
subject: item.subject
||
null
,
message: item.message
||
null
,
status: item.status
||
null
,
submitted_at: item.submitted_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const contact_messages = await db.contact_messages.bulkCreate(contact_messagesData, { transaction });
// For each item created, replace relation files
return contact_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 contact_messages = await db.contact_messages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.subject !== undefined) updatePayload.subject = data.subject;
if (data.message !== undefined) updatePayload.message = data.message;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
updatePayload.updatedById = currentUser.id;
await contact_messages.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await contact_messages.setOrganizations(
data.organizations,
{ transaction }
);
}
return contact_messages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const contact_messages = await db.contact_messages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of contact_messages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of contact_messages) {
await record.destroy({transaction});
}
});
return contact_messages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const contact_messages = await db.contact_messages.findByPk(id, options);
await contact_messages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await contact_messages.destroy({
transaction
});
return contact_messages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const contact_messages = await db.contact_messages.findOne(
{ where },
{ transaction },
);
if (!contact_messages) {
return contact_messages;
}
const output = contact_messages.get({plain: true});
output.organizations = await contact_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.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'contact_messages',
'name',
filter.name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'contact_messages',
'email',
filter.email,
),
};
}
if (filter.subject) {
where = {
...where,
[Op.and]: Utils.ilike(
'contact_messages',
'subject',
filter.subject,
),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'contact_messages',
'message',
filter.message,
),
};
}
if (filter.submitted_atRange) {
const [start, end] = filter.submitted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.contact_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(
'contact_messages',
'subject',
query,
),
],
};
}
const records = await db.contact_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,537 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Dashboard_widgetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const dashboard_widgets = await db.dashboard_widgets.create(
{
id: data.id || undefined,
widget_type: data.widget_type
||
null
,
sort_order: data.sort_order
||
null
,
is_visible: data.is_visible
||
false
,
settings_json: data.settings_json
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await dashboard_widgets.setUser( data.user || null, {
transaction,
});
await dashboard_widgets.setOrganizations( data.organizations || null, {
transaction,
});
return dashboard_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 dashboard_widgetsData = data.map((item, index) => ({
id: item.id || undefined,
widget_type: item.widget_type
||
null
,
sort_order: item.sort_order
||
null
,
is_visible: item.is_visible
||
false
,
settings_json: item.settings_json
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const dashboard_widgets = await db.dashboard_widgets.bulkCreate(dashboard_widgetsData, { transaction });
// For each item created, replace relation files
return dashboard_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 dashboard_widgets = await db.dashboard_widgets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.widget_type !== undefined) updatePayload.widget_type = data.widget_type;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_visible !== undefined) updatePayload.is_visible = data.is_visible;
if (data.settings_json !== undefined) updatePayload.settings_json = data.settings_json;
updatePayload.updatedById = currentUser.id;
await dashboard_widgets.update(updatePayload, {transaction});
if (data.user !== undefined) {
await dashboard_widgets.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await dashboard_widgets.setOrganizations(
data.organizations,
{ transaction }
);
}
return dashboard_widgets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const dashboard_widgets = await db.dashboard_widgets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of dashboard_widgets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of dashboard_widgets) {
await record.destroy({transaction});
}
});
return dashboard_widgets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const dashboard_widgets = await db.dashboard_widgets.findByPk(id, options);
await dashboard_widgets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await dashboard_widgets.destroy({
transaction
});
return dashboard_widgets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const dashboard_widgets = await db.dashboard_widgets.findOne(
{ where },
{ transaction },
);
if (!dashboard_widgets) {
return dashboard_widgets;
}
const output = dashboard_widgets.get({plain: true});
output.user = await dashboard_widgets.getUser({
transaction
});
output.organizations = await dashboard_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.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.settings_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'dashboard_widgets',
'settings_json',
filter.settings_json,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
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_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.dashboard_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(
'dashboard_widgets',
'widget_type',
query,
),
],
};
}
const records = await db.dashboard_widgets.findAll({
attributes: [ 'id', 'widget_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['widget_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.widget_type,
}));
}
};

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 Distribution_platformsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const distribution_platforms = await db.distribution_platforms.create(
{
id: data.id || undefined,
name: data.name
||
null
,
category: data.category
||
null
,
website_url: data.website_url
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await distribution_platforms.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.distribution_platforms.getTableName(),
belongsToColumn: 'logo',
belongsToId: distribution_platforms.id,
},
data.logo,
options,
);
return distribution_platforms;
}
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 distribution_platformsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
category: item.category
||
null
,
website_url: item.website_url
||
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 distribution_platforms = await db.distribution_platforms.bulkCreate(distribution_platformsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < distribution_platforms.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.distribution_platforms.getTableName(),
belongsToColumn: 'logo',
belongsToId: distribution_platforms[i].id,
},
data[i].logo,
options,
);
}
return distribution_platforms;
}
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 distribution_platforms = await db.distribution_platforms.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.website_url !== undefined) updatePayload.website_url = data.website_url;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await distribution_platforms.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await distribution_platforms.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.distribution_platforms.getTableName(),
belongsToColumn: 'logo',
belongsToId: distribution_platforms.id,
},
data.logo,
options,
);
return distribution_platforms;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const distribution_platforms = await db.distribution_platforms.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of distribution_platforms) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of distribution_platforms) {
await record.destroy({transaction});
}
});
return distribution_platforms;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const distribution_platforms = await db.distribution_platforms.findByPk(id, options);
await distribution_platforms.update({
deletedBy: currentUser.id
}, {
transaction,
});
await distribution_platforms.destroy({
transaction
});
return distribution_platforms;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const distribution_platforms = await db.distribution_platforms.findOne(
{ where },
{ transaction },
);
if (!distribution_platforms) {
return distribution_platforms;
}
const output = distribution_platforms.get({plain: true});
output.release_deliveries_platform = await distribution_platforms.getRelease_deliveries_platform({
transaction
});
output.smart_link_destinations_platform = await distribution_platforms.getSmart_link_destinations_platform({
transaction
});
output.smart_link_clicks_platform = await distribution_platforms.getSmart_link_clicks_platform({
transaction
});
output.playlists_platform = await distribution_platforms.getPlaylists_platform({
transaction
});
output.royalty_reports_platform = await distribution_platforms.getRoyalty_reports_platform({
transaction
});
output.analytics_daily_platform = await distribution_platforms.getAnalytics_daily_platform({
transaction
});
output.logo = await distribution_platforms.getLogo({
transaction
});
output.organizations = await distribution_platforms.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'logo',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'distribution_platforms',
'name',
filter.name,
),
};
}
if (filter.website_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'distribution_platforms',
'website_url',
filter.website_url,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
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.distribution_platforms.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(
'distribution_platforms',
'name',
query,
),
],
};
}
const records = await db.distribution_platforms.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,524 @@
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 Faq_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const faq_items = await db.faq_items.create(
{
id: data.id || undefined,
category: data.category
||
null
,
question: data.question
||
null
,
answer: data.answer
||
null
,
sort_order: data.sort_order
||
null
,
is_published: data.is_published
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await faq_items.setOrganizations( data.organizations || null, {
transaction,
});
return faq_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 faq_itemsData = data.map((item, index) => ({
id: item.id || undefined,
category: item.category
||
null
,
question: item.question
||
null
,
answer: item.answer
||
null
,
sort_order: item.sort_order
||
null
,
is_published: item.is_published
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const faq_items = await db.faq_items.bulkCreate(faq_itemsData, { transaction });
// For each item created, replace relation files
return faq_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 faq_items = await db.faq_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.category !== undefined) updatePayload.category = data.category;
if (data.question !== undefined) updatePayload.question = data.question;
if (data.answer !== undefined) updatePayload.answer = data.answer;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
updatePayload.updatedById = currentUser.id;
await faq_items.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await faq_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return faq_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const faq_items = await db.faq_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of faq_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of faq_items) {
await record.destroy({transaction});
}
});
return faq_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const faq_items = await db.faq_items.findByPk(id, options);
await faq_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await faq_items.destroy({
transaction
});
return faq_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const faq_items = await db.faq_items.findOne(
{ where },
{ transaction },
);
if (!faq_items) {
return faq_items;
}
const output = faq_items.get({plain: true});
output.organizations = await faq_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',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.question) {
where = {
...where,
[Op.and]: Utils.ilike(
'faq_items',
'question',
filter.question,
),
};
}
if (filter.answer) {
where = {
...where,
[Op.and]: Utils.ilike(
'faq_items',
'answer',
filter.answer,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[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_published) {
where = {
...where,
is_published: filter.is_published,
};
}
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.faq_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(
'faq_items',
'question',
query,
),
],
};
}
const records = await db.faq_items.findAll({
attributes: [ 'id', 'question' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['question', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.question,
}));
}
};

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,492 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class GenresDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const genres = await db.genres.create(
{
id: data.id || undefined,
name: data.name
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await genres.setParent_genre( data.parent_genre || null, {
transaction,
});
await genres.setOrganizations( data.organizations || null, {
transaction,
});
return genres;
}
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 genresData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const genres = await db.genres.bulkCreate(genresData, { transaction });
// For each item created, replace relation files
return genres;
}
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 genres = await db.genres.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await genres.update(updatePayload, {transaction});
if (data.parent_genre !== undefined) {
await genres.setParent_genre(
data.parent_genre,
{ transaction }
);
}
if (data.organizations !== undefined) {
await genres.setOrganizations(
data.organizations,
{ transaction }
);
}
return genres;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const genres = await db.genres.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of genres) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of genres) {
await record.destroy({transaction});
}
});
return genres;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const genres = await db.genres.findByPk(id, options);
await genres.update({
deletedBy: currentUser.id
}, {
transaction,
});
await genres.destroy({
transaction
});
return genres;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const genres = await db.genres.findOne(
{ where },
{ transaction },
);
if (!genres) {
return genres;
}
const output = genres.get({plain: true});
output.releases_primary_genre = await genres.getReleases_primary_genre({
transaction
});
output.releases_secondary_genre = await genres.getReleases_secondary_genre({
transaction
});
output.tracks_genre = await genres.getTracks_genre({
transaction
});
output.parent_genre = await genres.getParent_genre({
transaction
});
output.organizations = await genres.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.genres,
as: 'parent_genre',
where: filter.parent_genre ? {
[Op.or]: [
{ id: { [Op.in]: filter.parent_genre.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.parent_genre.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'genres',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.genres.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(
'genres',
'name',
query,
),
],
};
}
const records = await db.genres.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,656 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Notification_preferencesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notification_preferences = await db.notification_preferences.create(
{
id: data.id || undefined,
email_enabled: data.email_enabled
||
false
,
push_enabled: data.push_enabled
||
false
,
telegram_enabled: data.telegram_enabled
||
false
,
sms_enabled: data.sms_enabled
||
false
,
in_app_enabled: data.in_app_enabled
||
false
,
release_updates_enabled: data.release_updates_enabled
||
false
,
finance_updates_enabled: data.finance_updates_enabled
||
false
,
playlist_updates_enabled: data.playlist_updates_enabled
||
false
,
marketing_updates_enabled: data.marketing_updates_enabled
||
false
,
quiet_hours: data.quiet_hours
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notification_preferences.setUser( data.user || null, {
transaction,
});
await notification_preferences.setOrganizations( data.organizations || null, {
transaction,
});
return notification_preferences;
}
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 notification_preferencesData = data.map((item, index) => ({
id: item.id || undefined,
email_enabled: item.email_enabled
||
false
,
push_enabled: item.push_enabled
||
false
,
telegram_enabled: item.telegram_enabled
||
false
,
sms_enabled: item.sms_enabled
||
false
,
in_app_enabled: item.in_app_enabled
||
false
,
release_updates_enabled: item.release_updates_enabled
||
false
,
finance_updates_enabled: item.finance_updates_enabled
||
false
,
playlist_updates_enabled: item.playlist_updates_enabled
||
false
,
marketing_updates_enabled: item.marketing_updates_enabled
||
false
,
quiet_hours: item.quiet_hours
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const notification_preferences = await db.notification_preferences.bulkCreate(notification_preferencesData, { transaction });
// For each item created, replace relation files
return notification_preferences;
}
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 notification_preferences = await db.notification_preferences.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.email_enabled !== undefined) updatePayload.email_enabled = data.email_enabled;
if (data.push_enabled !== undefined) updatePayload.push_enabled = data.push_enabled;
if (data.telegram_enabled !== undefined) updatePayload.telegram_enabled = data.telegram_enabled;
if (data.sms_enabled !== undefined) updatePayload.sms_enabled = data.sms_enabled;
if (data.in_app_enabled !== undefined) updatePayload.in_app_enabled = data.in_app_enabled;
if (data.release_updates_enabled !== undefined) updatePayload.release_updates_enabled = data.release_updates_enabled;
if (data.finance_updates_enabled !== undefined) updatePayload.finance_updates_enabled = data.finance_updates_enabled;
if (data.playlist_updates_enabled !== undefined) updatePayload.playlist_updates_enabled = data.playlist_updates_enabled;
if (data.marketing_updates_enabled !== undefined) updatePayload.marketing_updates_enabled = data.marketing_updates_enabled;
if (data.quiet_hours !== undefined) updatePayload.quiet_hours = data.quiet_hours;
updatePayload.updatedById = currentUser.id;
await notification_preferences.update(updatePayload, {transaction});
if (data.user !== undefined) {
await notification_preferences.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await notification_preferences.setOrganizations(
data.organizations,
{ transaction }
);
}
return notification_preferences;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notification_preferences = await db.notification_preferences.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notification_preferences) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notification_preferences) {
await record.destroy({transaction});
}
});
return notification_preferences;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notification_preferences = await db.notification_preferences.findByPk(id, options);
await notification_preferences.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notification_preferences.destroy({
transaction
});
return notification_preferences;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notification_preferences = await db.notification_preferences.findOne(
{ where },
{ transaction },
);
if (!notification_preferences) {
return notification_preferences;
}
const output = notification_preferences.get({plain: true});
output.user = await notification_preferences.getUser({
transaction
});
output.organizations = await notification_preferences.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.quiet_hours) {
where = {
...where,
[Op.and]: Utils.ilike(
'notification_preferences',
'quiet_hours',
filter.quiet_hours,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.email_enabled) {
where = {
...where,
email_enabled: filter.email_enabled,
};
}
if (filter.push_enabled) {
where = {
...where,
push_enabled: filter.push_enabled,
};
}
if (filter.telegram_enabled) {
where = {
...where,
telegram_enabled: filter.telegram_enabled,
};
}
if (filter.sms_enabled) {
where = {
...where,
sms_enabled: filter.sms_enabled,
};
}
if (filter.in_app_enabled) {
where = {
...where,
in_app_enabled: filter.in_app_enabled,
};
}
if (filter.release_updates_enabled) {
where = {
...where,
release_updates_enabled: filter.release_updates_enabled,
};
}
if (filter.finance_updates_enabled) {
where = {
...where,
finance_updates_enabled: filter.finance_updates_enabled,
};
}
if (filter.playlist_updates_enabled) {
where = {
...where,
playlist_updates_enabled: filter.playlist_updates_enabled,
};
}
if (filter.marketing_updates_enabled) {
where = {
...where,
marketing_updates_enabled: filter.marketing_updates_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.notification_preferences.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(
'notification_preferences',
'quiet_hours',
query,
),
],
};
}
const records = await db.notification_preferences.findAll({
attributes: [ 'id', 'quiet_hours' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['quiet_hours', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.quiet_hours,
}));
}
};

View File

@ -0,0 +1,640 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class NotificationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.create(
{
id: data.id || undefined,
channel: data.channel
||
null
,
event_type: data.event_type
||
null
,
title: data.title
||
null
,
message: data.message
||
null
,
scheduled_at: data.scheduled_at
||
null
,
sent_at: data.sent_at
||
null
,
status: data.status
||
null
,
provider_reference: data.provider_reference
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notifications.setUser( data.user || null, {
transaction,
});
await notifications.setOrganizations( data.organizations || null, {
transaction,
});
return notifications;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const notificationsData = data.map((item, index) => ({
id: item.id || undefined,
channel: item.channel
||
null
,
event_type: item.event_type
||
null
,
title: item.title
||
null
,
message: item.message
||
null
,
scheduled_at: item.scheduled_at
||
null
,
sent_at: item.sent_at
||
null
,
status: item.status
||
null
,
provider_reference: item.provider_reference
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const notifications = await db.notifications.bulkCreate(notificationsData, { transaction });
// For each item created, replace relation files
return notifications;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const notifications = await db.notifications.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.message !== undefined) updatePayload.message = data.message;
if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.provider_reference !== undefined) updatePayload.provider_reference = data.provider_reference;
updatePayload.updatedById = currentUser.id;
await notifications.update(updatePayload, {transaction});
if (data.user !== undefined) {
await notifications.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await notifications.setOrganizations(
data.organizations,
{ transaction }
);
}
return notifications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notifications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notifications) {
await record.destroy({transaction});
}
});
return notifications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findByPk(id, options);
await notifications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notifications.destroy({
transaction
});
return notifications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findOne(
{ where },
{ transaction },
);
if (!notifications) {
return notifications;
}
const output = notifications.get({plain: true});
output.user = await notifications.getUser({
transaction
});
output.organizations = await notifications.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.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.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'title',
filter.title,
),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'message',
filter.message,
),
};
}
if (filter.provider_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'provider_reference',
filter.provider_reference,
),
};
}
if (filter.scheduled_atRange) {
const [start, end] = filter.scheduled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.channel) {
where = {
...where,
channel: filter.channel,
};
}
if (filter.event_type) {
where = {
...where,
event_type: filter.event_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.notifications.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'notifications',
'title',
query,
),
],
};
}
const records = await db.notifications.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,563 @@
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 Oauth_accountsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const oauth_accounts = await db.oauth_accounts.create(
{
id: data.id || undefined,
provider: data.provider
||
null
,
provider_user_key: data.provider_user_key
||
null
,
access_token: data.access_token
||
null
,
refresh_token: data.refresh_token
||
null
,
token_expires_at: data.token_expires_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await oauth_accounts.setUser( data.user || null, {
transaction,
});
await oauth_accounts.setOrganizations( data.organizations || null, {
transaction,
});
return oauth_accounts;
}
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 oauth_accountsData = data.map((item, index) => ({
id: item.id || undefined,
provider: item.provider
||
null
,
provider_user_key: item.provider_user_key
||
null
,
access_token: item.access_token
||
null
,
refresh_token: item.refresh_token
||
null
,
token_expires_at: item.token_expires_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const oauth_accounts = await db.oauth_accounts.bulkCreate(oauth_accountsData, { transaction });
// For each item created, replace relation files
return oauth_accounts;
}
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 oauth_accounts = await db.oauth_accounts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.provider !== undefined) updatePayload.provider = data.provider;
if (data.provider_user_key !== undefined) updatePayload.provider_user_key = data.provider_user_key;
if (data.access_token !== undefined) updatePayload.access_token = data.access_token;
if (data.refresh_token !== undefined) updatePayload.refresh_token = data.refresh_token;
if (data.token_expires_at !== undefined) updatePayload.token_expires_at = data.token_expires_at;
updatePayload.updatedById = currentUser.id;
await oauth_accounts.update(updatePayload, {transaction});
if (data.user !== undefined) {
await oauth_accounts.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await oauth_accounts.setOrganizations(
data.organizations,
{ transaction }
);
}
return oauth_accounts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const oauth_accounts = await db.oauth_accounts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of oauth_accounts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of oauth_accounts) {
await record.destroy({transaction});
}
});
return oauth_accounts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const oauth_accounts = await db.oauth_accounts.findByPk(id, options);
await oauth_accounts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await oauth_accounts.destroy({
transaction
});
return oauth_accounts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const oauth_accounts = await db.oauth_accounts.findOne(
{ where },
{ transaction },
);
if (!oauth_accounts) {
return oauth_accounts;
}
const output = oauth_accounts.get({plain: true});
output.user = await oauth_accounts.getUser({
transaction
});
output.organizations = await oauth_accounts.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.provider_user_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'oauth_accounts',
'provider_user_key',
filter.provider_user_key,
),
};
}
if (filter.access_token) {
where = {
...where,
[Op.and]: Utils.ilike(
'oauth_accounts',
'access_token',
filter.access_token,
),
};
}
if (filter.refresh_token) {
where = {
...where,
[Op.and]: Utils.ilike(
'oauth_accounts',
'refresh_token',
filter.refresh_token,
),
};
}
if (filter.token_expires_atRange) {
const [start, end] = filter.token_expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
token_expires_at: {
...where.token_expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
token_expires_at: {
...where.token_expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.provider) {
where = {
...where,
provider: filter.provider,
};
}
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.oauth_accounts.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(
'oauth_accounts',
'provider_user_key',
query,
),
],
};
}
const records = await db.oauth_accounts.findAll({
attributes: [ 'id', 'provider_user_key' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['provider_user_key', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.provider_user_key,
}));
}
};

View File

@ -0,0 +1,536 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class OrganizationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return organizations;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const organizationsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const organizations = await db.organizations.bulkCreate(organizationsData, { transaction });
// For each item created, replace relation files
return organizations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const organizations = await db.organizations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await organizations.update(updatePayload, {transaction});
return organizations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of organizations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of organizations) {
await record.destroy({transaction});
}
});
return organizations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findByPk(id, options);
await organizations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await organizations.destroy({
transaction
});
return organizations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findOne(
{ where },
{ transaction },
);
if (!organizations) {
return organizations;
}
const output = organizations.get({plain: true});
output.users_organizations = await organizations.getUsers_organizations({
transaction
});
output.oauth_accounts_organizations = await organizations.getOauth_accounts_organizations({
transaction
});
output.artist_profiles_organizations = await organizations.getArtist_profiles_organizations({
transaction
});
output.teams_organizations = await organizations.getTeams_organizations({
transaction
});
output.team_memberships_organizations = await organizations.getTeam_memberships_organizations({
transaction
});
output.plans_organizations = await organizations.getPlans_organizations({
transaction
});
output.subscriptions_organizations = await organizations.getSubscriptions_organizations({
transaction
});
output.distribution_platforms_organizations = await organizations.getDistribution_platforms_organizations({
transaction
});
output.genres_organizations = await organizations.getGenres_organizations({
transaction
});
output.releases_organizations = await organizations.getReleases_organizations({
transaction
});
output.tracks_organizations = await organizations.getTracks_organizations({
transaction
});
output.track_contributors_organizations = await organizations.getTrack_contributors_organizations({
transaction
});
output.release_deliveries_organizations = await organizations.getRelease_deliveries_organizations({
transaction
});
output.smart_links_organizations = await organizations.getSmart_links_organizations({
transaction
});
output.smart_link_destinations_organizations = await organizations.getSmart_link_destinations_organizations({
transaction
});
output.smart_link_clicks_organizations = await organizations.getSmart_link_clicks_organizations({
transaction
});
output.playlists_organizations = await organizations.getPlaylists_organizations({
transaction
});
output.pitch_requests_organizations = await organizations.getPitch_requests_organizations({
transaction
});
output.playlist_placements_organizations = await organizations.getPlaylist_placements_organizations({
transaction
});
output.royalty_reports_organizations = await organizations.getRoyalty_reports_organizations({
transaction
});
output.royalty_lines_organizations = await organizations.getRoyalty_lines_organizations({
transaction
});
output.wallets_organizations = await organizations.getWallets_organizations({
transaction
});
output.wallet_transactions_organizations = await organizations.getWallet_transactions_organizations({
transaction
});
output.payout_methods_organizations = await organizations.getPayout_methods_organizations({
transaction
});
output.withdrawal_requests_organizations = await organizations.getWithdrawal_requests_organizations({
transaction
});
output.tax_documents_organizations = await organizations.getTax_documents_organizations({
transaction
});
output.analytics_daily_organizations = await organizations.getAnalytics_daily_organizations({
transaction
});
output.notifications_organizations = await organizations.getNotifications_organizations({
transaction
});
output.notification_preferences_organizations = await organizations.getNotification_preferences_organizations({
transaction
});
output.api_keys_organizations = await organizations.getApi_keys_organizations({
transaction
});
output.dashboard_widgets_organizations = await organizations.getDashboard_widgets_organizations({
transaction
});
output.activity_events_organizations = await organizations.getActivity_events_organizations({
transaction
});
output.blog_posts_organizations = await organizations.getBlog_posts_organizations({
transaction
});
output.faq_items_organizations = await organizations.getFaq_items_organizations({
transaction
});
output.contact_messages_organizations = await organizations.getContact_messages_organizations({
transaction
});
output.referral_programs_organizations = await organizations.getReferral_programs_organizations({
transaction
});
output.referral_links_organizations = await organizations.getReferral_links_organizations({
transaction
});
output.referral_conversions_organizations = await organizations.getReferral_conversions_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,596 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Payout_methodsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payout_methods = await db.payout_methods.create(
{
id: data.id || undefined,
method_type: data.method_type
||
null
,
method_label: data.method_label
||
null
,
account_identifier: data.account_identifier
||
null
,
holder_name: data.holder_name
||
null
,
country: data.country
||
null
,
is_default: data.is_default
||
false
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payout_methods.setUser( data.user || null, {
transaction,
});
await payout_methods.setOrganizations( data.organizations || null, {
transaction,
});
return payout_methods;
}
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 payout_methodsData = data.map((item, index) => ({
id: item.id || undefined,
method_type: item.method_type
||
null
,
method_label: item.method_label
||
null
,
account_identifier: item.account_identifier
||
null
,
holder_name: item.holder_name
||
null
,
country: item.country
||
null
,
is_default: item.is_default
||
false
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payout_methods = await db.payout_methods.bulkCreate(payout_methodsData, { transaction });
// For each item created, replace relation files
return payout_methods;
}
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 payout_methods = await db.payout_methods.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.method_type !== undefined) updatePayload.method_type = data.method_type;
if (data.method_label !== undefined) updatePayload.method_label = data.method_label;
if (data.account_identifier !== undefined) updatePayload.account_identifier = data.account_identifier;
if (data.holder_name !== undefined) updatePayload.holder_name = data.holder_name;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await payout_methods.update(updatePayload, {transaction});
if (data.user !== undefined) {
await payout_methods.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await payout_methods.setOrganizations(
data.organizations,
{ transaction }
);
}
return payout_methods;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payout_methods = await db.payout_methods.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payout_methods) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payout_methods) {
await record.destroy({transaction});
}
});
return payout_methods;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payout_methods = await db.payout_methods.findByPk(id, options);
await payout_methods.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payout_methods.destroy({
transaction
});
return payout_methods;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payout_methods = await db.payout_methods.findOne(
{ where },
{ transaction },
);
if (!payout_methods) {
return payout_methods;
}
const output = payout_methods.get({plain: true});
output.withdrawal_requests_payout_method = await payout_methods.getWithdrawal_requests_payout_method({
transaction
});
output.user = await payout_methods.getUser({
transaction
});
output.organizations = await payout_methods.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.method_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'payout_methods',
'method_label',
filter.method_label,
),
};
}
if (filter.account_identifier) {
where = {
...where,
[Op.and]: Utils.ilike(
'payout_methods',
'account_identifier',
filter.account_identifier,
),
};
}
if (filter.holder_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'payout_methods',
'holder_name',
filter.holder_name,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'payout_methods',
'country',
filter.country,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.method_type) {
where = {
...where,
method_type: filter.method_type,
};
}
if (filter.is_default) {
where = {
...where,
is_default: filter.is_default,
};
}
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.payout_methods.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(
'payout_methods',
'method_label',
query,
),
],
};
}
const records = await db.payout_methods.findAll({
attributes: [ 'id', 'method_label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['method_label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.method_label,
}));
}
};

View File

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

View File

@ -0,0 +1,751 @@
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 Pitch_requestsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const pitch_requests = await db.pitch_requests.create(
{
id: data.id || undefined,
pitch_title: data.pitch_title
||
null
,
pitch_text: data.pitch_text
||
null
,
mood: data.mood
||
null
,
similar_artists: data.similar_artists
||
null
,
achievements: data.achievements
||
null
,
status: data.status
||
null
,
submitted_at: data.submitted_at
||
null
,
decided_at: data.decided_at
||
null
,
decision_notes: data.decision_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await pitch_requests.setTrack( data.track || null, {
transaction,
});
await pitch_requests.setArtist_profile( data.artist_profile || null, {
transaction,
});
await pitch_requests.setOrganizations( data.organizations || null, {
transaction,
});
await pitch_requests.setTarget_playlists(data.target_playlists || [], {
transaction,
});
return pitch_requests;
}
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 pitch_requestsData = data.map((item, index) => ({
id: item.id || undefined,
pitch_title: item.pitch_title
||
null
,
pitch_text: item.pitch_text
||
null
,
mood: item.mood
||
null
,
similar_artists: item.similar_artists
||
null
,
achievements: item.achievements
||
null
,
status: item.status
||
null
,
submitted_at: item.submitted_at
||
null
,
decided_at: item.decided_at
||
null
,
decision_notes: item.decision_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const pitch_requests = await db.pitch_requests.bulkCreate(pitch_requestsData, { transaction });
// For each item created, replace relation files
return pitch_requests;
}
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 pitch_requests = await db.pitch_requests.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.pitch_title !== undefined) updatePayload.pitch_title = data.pitch_title;
if (data.pitch_text !== undefined) updatePayload.pitch_text = data.pitch_text;
if (data.mood !== undefined) updatePayload.mood = data.mood;
if (data.similar_artists !== undefined) updatePayload.similar_artists = data.similar_artists;
if (data.achievements !== undefined) updatePayload.achievements = data.achievements;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
if (data.decided_at !== undefined) updatePayload.decided_at = data.decided_at;
if (data.decision_notes !== undefined) updatePayload.decision_notes = data.decision_notes;
updatePayload.updatedById = currentUser.id;
await pitch_requests.update(updatePayload, {transaction});
if (data.track !== undefined) {
await pitch_requests.setTrack(
data.track,
{ transaction }
);
}
if (data.artist_profile !== undefined) {
await pitch_requests.setArtist_profile(
data.artist_profile,
{ transaction }
);
}
if (data.organizations !== undefined) {
await pitch_requests.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.target_playlists !== undefined) {
await pitch_requests.setTarget_playlists(data.target_playlists, { transaction });
}
return pitch_requests;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const pitch_requests = await db.pitch_requests.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of pitch_requests) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of pitch_requests) {
await record.destroy({transaction});
}
});
return pitch_requests;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const pitch_requests = await db.pitch_requests.findByPk(id, options);
await pitch_requests.update({
deletedBy: currentUser.id
}, {
transaction,
});
await pitch_requests.destroy({
transaction
});
return pitch_requests;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const pitch_requests = await db.pitch_requests.findOne(
{ where },
{ transaction },
);
if (!pitch_requests) {
return pitch_requests;
}
const output = pitch_requests.get({plain: true});
output.track = await pitch_requests.getTrack({
transaction
});
output.artist_profile = await pitch_requests.getArtist_profile({
transaction
});
output.target_playlists = await pitch_requests.getTarget_playlists({
transaction
});
output.organizations = await pitch_requests.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.tracks,
as: 'track',
where: filter.track ? {
[Op.or]: [
{ id: { [Op.in]: filter.track.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.track.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.artist_profiles,
as: 'artist_profile',
where: filter.artist_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.artist_profile.split('|').map(term => Utils.uuid(term)) } },
{
artist_name: {
[Op.or]: filter.artist_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.playlists,
as: 'target_playlists',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.pitch_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'pitch_requests',
'pitch_title',
filter.pitch_title,
),
};
}
if (filter.pitch_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'pitch_requests',
'pitch_text',
filter.pitch_text,
),
};
}
if (filter.mood) {
where = {
...where,
[Op.and]: Utils.ilike(
'pitch_requests',
'mood',
filter.mood,
),
};
}
if (filter.similar_artists) {
where = {
...where,
[Op.and]: Utils.ilike(
'pitch_requests',
'similar_artists',
filter.similar_artists,
),
};
}
if (filter.achievements) {
where = {
...where,
[Op.and]: Utils.ilike(
'pitch_requests',
'achievements',
filter.achievements,
),
};
}
if (filter.decision_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'pitch_requests',
'decision_notes',
filter.decision_notes,
),
};
}
if (filter.submitted_atRange) {
const [start, end] = filter.submitted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.lte]: end,
},
};
}
}
if (filter.decided_atRange) {
const [start, end] = filter.decided_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
decided_at: {
...where.decided_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
decided_at: {
...where.decided_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.target_playlists) {
const searchTerms = filter.target_playlists.split('|');
include = [
{
model: db.playlists,
as: 'target_playlists_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) {
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.pitch_requests.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(
'pitch_requests',
'pitch_title',
query,
),
],
};
}
const records = await db.pitch_requests.findAll({
attributes: [ 'id', 'pitch_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['pitch_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.pitch_title,
}));
}
};

576
backend/src/db/api/plans.js Normal file
View File

@ -0,0 +1,576 @@
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 PlansDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const plans = await db.plans.create(
{
id: data.id || undefined,
name: data.name
||
null
,
plan_code: data.plan_code
||
null
,
price_amount: data.price_amount
||
null
,
price_currency: data.price_currency
||
null
,
billing_period: data.billing_period
||
null
,
is_active: data.is_active
||
false
,
features: data.features
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await plans.setOrganizations( data.organizations || null, {
transaction,
});
return plans;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const plansData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
plan_code: item.plan_code
||
null
,
price_amount: item.price_amount
||
null
,
price_currency: item.price_currency
||
null
,
billing_period: item.billing_period
||
null
,
is_active: item.is_active
||
false
,
features: item.features
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const plans = await db.plans.bulkCreate(plansData, { transaction });
// For each item created, replace relation files
return plans;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const plans = await db.plans.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.plan_code !== undefined) updatePayload.plan_code = data.plan_code;
if (data.price_amount !== undefined) updatePayload.price_amount = data.price_amount;
if (data.price_currency !== undefined) updatePayload.price_currency = data.price_currency;
if (data.billing_period !== undefined) updatePayload.billing_period = data.billing_period;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.features !== undefined) updatePayload.features = data.features;
updatePayload.updatedById = currentUser.id;
await plans.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await plans.setOrganizations(
data.organizations,
{ transaction }
);
}
return plans;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const plans = await db.plans.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of plans) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of plans) {
await record.destroy({transaction});
}
});
return plans;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const plans = await db.plans.findByPk(id, options);
await plans.update({
deletedBy: currentUser.id
}, {
transaction,
});
await plans.destroy({
transaction
});
return plans;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const plans = await db.plans.findOne(
{ where },
{ transaction },
);
if (!plans) {
return plans;
}
const output = plans.get({plain: true});
output.subscriptions_plan = await plans.getSubscriptions_plan({
transaction
});
output.organizations = await plans.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'plans',
'name',
filter.name,
),
};
}
if (filter.price_currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'plans',
'price_currency',
filter.price_currency,
),
};
}
if (filter.billing_period) {
where = {
...where,
[Op.and]: Utils.ilike(
'plans',
'billing_period',
filter.billing_period,
),
};
}
if (filter.features) {
where = {
...where,
[Op.and]: Utils.ilike(
'plans',
'features',
filter.features,
),
};
}
if (filter.price_amountRange) {
const [start, end] = filter.price_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_amount: {
...where.price_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_amount: {
...where.price_amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.plan_code) {
where = {
...where,
plan_code: filter.plan_code,
};
}
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.plans.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'plans',
'name',
query,
),
],
};
}
const records = await db.plans.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,624 @@
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_placementsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const playlist_placements = await db.playlist_placements.create(
{
id: data.id || undefined,
placed_at: data.placed_at
||
null
,
removed_at: data.removed_at
||
null
,
position: data.position
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await playlist_placements.setTrack( data.track || null, {
transaction,
});
await playlist_placements.setPlaylist( data.playlist || null, {
transaction,
});
await playlist_placements.setOrganizations( data.organizations || null, {
transaction,
});
return playlist_placements;
}
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_placementsData = data.map((item, index) => ({
id: item.id || undefined,
placed_at: item.placed_at
||
null
,
removed_at: item.removed_at
||
null
,
position: item.position
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const playlist_placements = await db.playlist_placements.bulkCreate(playlist_placementsData, { transaction });
// For each item created, replace relation files
return playlist_placements;
}
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_placements = await db.playlist_placements.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.placed_at !== undefined) updatePayload.placed_at = data.placed_at;
if (data.removed_at !== undefined) updatePayload.removed_at = data.removed_at;
if (data.position !== undefined) updatePayload.position = data.position;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await playlist_placements.update(updatePayload, {transaction});
if (data.track !== undefined) {
await playlist_placements.setTrack(
data.track,
{ transaction }
);
}
if (data.playlist !== undefined) {
await playlist_placements.setPlaylist(
data.playlist,
{ transaction }
);
}
if (data.organizations !== undefined) {
await playlist_placements.setOrganizations(
data.organizations,
{ transaction }
);
}
return playlist_placements;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const playlist_placements = await db.playlist_placements.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of playlist_placements) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of playlist_placements) {
await record.destroy({transaction});
}
});
return playlist_placements;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const playlist_placements = await db.playlist_placements.findByPk(id, options);
await playlist_placements.update({
deletedBy: currentUser.id
}, {
transaction,
});
await playlist_placements.destroy({
transaction
});
return playlist_placements;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const playlist_placements = await db.playlist_placements.findOne(
{ where },
{ transaction },
);
if (!playlist_placements) {
return playlist_placements;
}
const output = playlist_placements.get({plain: true});
output.track = await playlist_placements.getTrack({
transaction
});
output.playlist = await playlist_placements.getPlaylist({
transaction
});
output.organizations = await playlist_placements.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.tracks,
as: 'track',
where: filter.track ? {
[Op.or]: [
{ id: { [Op.in]: filter.track.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.track.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
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.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'playlist_placements',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
placed_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
removed_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
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.removed_atRange) {
const [start, end] = filter.removed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
removed_at: {
...where.removed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
removed_at: {
...where.removed_at,
[Op.lte]: end,
},
};
}
}
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.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.playlist_placements.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_placements',
'notes',
query,
),
],
};
}
const records = await db.playlist_placements.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};

View File

@ -0,0 +1,600 @@
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
,
playlist_type: data.playlist_type
||
null
,
curator_name: data.curator_name
||
null
,
playlist_url: data.playlist_url
||
null
,
genre_focus: data.genre_focus
||
null
,
mood_tags: data.mood_tags
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await playlists.setPlatform( data.platform || null, {
transaction,
});
await playlists.setOrganizations( data.organizations || null, {
transaction,
});
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
,
playlist_type: item.playlist_type
||
null
,
curator_name: item.curator_name
||
null
,
playlist_url: item.playlist_url
||
null
,
genre_focus: item.genre_focus
||
null
,
mood_tags: item.mood_tags
||
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 playlists = await db.playlists.bulkCreate(playlistsData, { transaction });
// For each item created, replace relation files
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.playlist_type !== undefined) updatePayload.playlist_type = data.playlist_type;
if (data.curator_name !== undefined) updatePayload.curator_name = data.curator_name;
if (data.playlist_url !== undefined) updatePayload.playlist_url = data.playlist_url;
if (data.genre_focus !== undefined) updatePayload.genre_focus = data.genre_focus;
if (data.mood_tags !== undefined) updatePayload.mood_tags = data.mood_tags;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await playlists.update(updatePayload, {transaction});
if (data.platform !== undefined) {
await playlists.setPlatform(
data.platform,
{ transaction }
);
}
if (data.organizations !== undefined) {
await playlists.setOrganizations(
data.organizations,
{ transaction }
);
}
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_placements_playlist = await playlists.getPlaylist_placements_playlist({
transaction
});
output.platform = await playlists.getPlatform({
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.distribution_platforms,
as: 'platform',
where: filter.platform ? {
[Op.or]: [
{ id: { [Op.in]: filter.platform.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.platform.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'playlists',
'name',
filter.name,
),
};
}
if (filter.curator_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'playlists',
'curator_name',
filter.curator_name,
),
};
}
if (filter.playlist_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'playlists',
'playlist_url',
filter.playlist_url,
),
};
}
if (filter.genre_focus) {
where = {
...where,
[Op.and]: Utils.ilike(
'playlists',
'genre_focus',
filter.genre_focus,
),
};
}
if (filter.mood_tags) {
where = {
...where,
[Op.and]: Utils.ilike(
'playlists',
'mood_tags',
filter.mood_tags,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.playlist_type) {
where = {
...where,
playlist_type: filter.playlist_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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,589 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Referral_conversionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral_conversions = await db.referral_conversions.create(
{
id: data.id || undefined,
converted_at: data.converted_at
||
null
,
status: data.status
||
null
,
commission_amount: data.commission_amount
||
null
,
currency: data.currency
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await referral_conversions.setReferral_link( data.referral_link || null, {
transaction,
});
await referral_conversions.setReferred_user( data.referred_user || null, {
transaction,
});
await referral_conversions.setOrganizations( data.organizations || null, {
transaction,
});
return referral_conversions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const referral_conversionsData = data.map((item, index) => ({
id: item.id || undefined,
converted_at: item.converted_at
||
null
,
status: item.status
||
null
,
commission_amount: item.commission_amount
||
null
,
currency: item.currency
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const referral_conversions = await db.referral_conversions.bulkCreate(referral_conversionsData, { transaction });
// For each item created, replace relation files
return referral_conversions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const referral_conversions = await db.referral_conversions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.converted_at !== undefined) updatePayload.converted_at = data.converted_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.commission_amount !== undefined) updatePayload.commission_amount = data.commission_amount;
if (data.currency !== undefined) updatePayload.currency = data.currency;
updatePayload.updatedById = currentUser.id;
await referral_conversions.update(updatePayload, {transaction});
if (data.referral_link !== undefined) {
await referral_conversions.setReferral_link(
data.referral_link,
{ transaction }
);
}
if (data.referred_user !== undefined) {
await referral_conversions.setReferred_user(
data.referred_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await referral_conversions.setOrganizations(
data.organizations,
{ transaction }
);
}
return referral_conversions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral_conversions = await db.referral_conversions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of referral_conversions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of referral_conversions) {
await record.destroy({transaction});
}
});
return referral_conversions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const referral_conversions = await db.referral_conversions.findByPk(id, options);
await referral_conversions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await referral_conversions.destroy({
transaction
});
return referral_conversions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const referral_conversions = await db.referral_conversions.findOne(
{ where },
{ transaction },
);
if (!referral_conversions) {
return referral_conversions;
}
const output = referral_conversions.get({plain: true});
output.referral_link = await referral_conversions.getReferral_link({
transaction
});
output.referred_user = await referral_conversions.getReferred_user({
transaction
});
output.organizations = await referral_conversions.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.referral_links,
as: 'referral_link',
where: filter.referral_link ? {
[Op.or]: [
{ id: { [Op.in]: filter.referral_link.split('|').map(term => Utils.uuid(term)) } },
{
code: {
[Op.or]: filter.referral_link.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'referred_user',
where: filter.referred_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.referred_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.referred_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(
'referral_conversions',
'currency',
filter.currency,
),
};
}
if (filter.converted_atRange) {
const [start, end] = filter.converted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
converted_at: {
...where.converted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
converted_at: {
...where.converted_at,
[Op.lte]: end,
},
};
}
}
if (filter.commission_amountRange) {
const [start, end] = filter.commission_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commission_amount: {
...where.commission_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commission_amount: {
...where.commission_amount,
[Op.lte]: end,
},
};
}
}
if (filter.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.referral_conversions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'referral_conversions',
'status',
query,
),
],
};
}
const records = await db.referral_conversions.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,582 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Referral_linksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral_links = await db.referral_links.create(
{
id: data.id || undefined,
code: data.code
||
null
,
landing_url: data.landing_url
||
null
,
is_active: data.is_active
||
false
,
created_on: data.created_on
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await referral_links.setReferrer_user( data.referrer_user || null, {
transaction,
});
await referral_links.setProgram( data.program || null, {
transaction,
});
await referral_links.setOrganizations( data.organizations || null, {
transaction,
});
return referral_links;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const referral_linksData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
landing_url: item.landing_url
||
null
,
is_active: item.is_active
||
false
,
created_on: item.created_on
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const referral_links = await db.referral_links.bulkCreate(referral_linksData, { transaction });
// For each item created, replace relation files
return referral_links;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const referral_links = await db.referral_links.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.landing_url !== undefined) updatePayload.landing_url = data.landing_url;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
updatePayload.updatedById = currentUser.id;
await referral_links.update(updatePayload, {transaction});
if (data.referrer_user !== undefined) {
await referral_links.setReferrer_user(
data.referrer_user,
{ transaction }
);
}
if (data.program !== undefined) {
await referral_links.setProgram(
data.program,
{ transaction }
);
}
if (data.organizations !== undefined) {
await referral_links.setOrganizations(
data.organizations,
{ transaction }
);
}
return referral_links;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral_links = await db.referral_links.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of referral_links) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of referral_links) {
await record.destroy({transaction});
}
});
return referral_links;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const referral_links = await db.referral_links.findByPk(id, options);
await referral_links.update({
deletedBy: currentUser.id
}, {
transaction,
});
await referral_links.destroy({
transaction
});
return referral_links;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const referral_links = await db.referral_links.findOne(
{ where },
{ transaction },
);
if (!referral_links) {
return referral_links;
}
const output = referral_links.get({plain: true});
output.referral_conversions_referral_link = await referral_links.getReferral_conversions_referral_link({
transaction
});
output.referrer_user = await referral_links.getReferrer_user({
transaction
});
output.program = await referral_links.getProgram({
transaction
});
output.organizations = await referral_links.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'referrer_user',
where: filter.referrer_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.referrer_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.referrer_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.referral_programs,
as: 'program',
where: filter.program ? {
[Op.or]: [
{ id: { [Op.in]: filter.program.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.program.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'referral_links',
'code',
filter.code,
),
};
}
if (filter.landing_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'referral_links',
'landing_url',
filter.landing_url,
),
};
}
if (filter.created_onRange) {
const [start, end] = filter.created_onRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_on: {
...where.created_on,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_on: {
...where.created_on,
[Op.lte]: end,
},
};
}
}
if (filter.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.referral_links.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'referral_links',
'code',
query,
),
],
};
}
const records = await db.referral_links.findAll({
attributes: [ 'id', 'code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.code,
}));
}
};

View File

@ -0,0 +1,613 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Referral_programsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral_programs = await db.referral_programs.create(
{
id: data.id || undefined,
name: data.name
||
null
,
commission_percent: data.commission_percent
||
null
,
validity_days: data.validity_days
||
null
,
starts_at: data.starts_at
||
null
,
ends_at: data.ends_at
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await referral_programs.setOrganizations( data.organizations || null, {
transaction,
});
return referral_programs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const referral_programsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
commission_percent: item.commission_percent
||
null
,
validity_days: item.validity_days
||
null
,
starts_at: item.starts_at
||
null
,
ends_at: item.ends_at
||
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 referral_programs = await db.referral_programs.bulkCreate(referral_programsData, { transaction });
// For each item created, replace relation files
return referral_programs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const referral_programs = await db.referral_programs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.commission_percent !== undefined) updatePayload.commission_percent = data.commission_percent;
if (data.validity_days !== undefined) updatePayload.validity_days = data.validity_days;
if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await referral_programs.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await referral_programs.setOrganizations(
data.organizations,
{ transaction }
);
}
return referral_programs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referral_programs = await db.referral_programs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of referral_programs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of referral_programs) {
await record.destroy({transaction});
}
});
return referral_programs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const referral_programs = await db.referral_programs.findByPk(id, options);
await referral_programs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await referral_programs.destroy({
transaction
});
return referral_programs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const referral_programs = await db.referral_programs.findOne(
{ where },
{ transaction },
);
if (!referral_programs) {
return referral_programs;
}
const output = referral_programs.get({plain: true});
output.referral_links_program = await referral_programs.getReferral_links_program({
transaction
});
output.organizations = await referral_programs.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'referral_programs',
'name',
filter.name,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
starts_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ends_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.commission_percentRange) {
const [start, end] = filter.commission_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commission_percent: {
...where.commission_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commission_percent: {
...where.commission_percent,
[Op.lte]: end,
},
};
}
}
if (filter.validity_daysRange) {
const [start, end] = filter.validity_daysRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
validity_days: {
...where.validity_days,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
validity_days: {
...where.validity_days,
[Op.lte]: end,
},
};
}
}
if (filter.starts_atRange) {
const [start, end] = filter.starts_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.lte]: end,
},
};
}
}
if (filter.ends_atRange) {
const [start, end] = filter.ends_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.referral_programs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'referral_programs',
'name',
query,
),
],
};
}
const records = await db.referral_programs.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,674 @@
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 Release_deliveriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const release_deliveries = await db.release_deliveries.create(
{
id: data.id || undefined,
delivery_status: data.delivery_status
||
null
,
requested_at: data.requested_at
||
null
,
sent_at: data.sent_at
||
null
,
delivered_at: data.delivered_at
||
null
,
platform_release_url: data.platform_release_url
||
null
,
external_reference: data.external_reference
||
null
,
error_message: data.error_message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await release_deliveries.setRelease( data.release || null, {
transaction,
});
await release_deliveries.setPlatform( data.platform || null, {
transaction,
});
await release_deliveries.setOrganizations( data.organizations || null, {
transaction,
});
return release_deliveries;
}
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 release_deliveriesData = data.map((item, index) => ({
id: item.id || undefined,
delivery_status: item.delivery_status
||
null
,
requested_at: item.requested_at
||
null
,
sent_at: item.sent_at
||
null
,
delivered_at: item.delivered_at
||
null
,
platform_release_url: item.platform_release_url
||
null
,
external_reference: item.external_reference
||
null
,
error_message: item.error_message
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const release_deliveries = await db.release_deliveries.bulkCreate(release_deliveriesData, { transaction });
// For each item created, replace relation files
return release_deliveries;
}
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 release_deliveries = await db.release_deliveries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.delivery_status !== undefined) updatePayload.delivery_status = data.delivery_status;
if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.delivered_at !== undefined) updatePayload.delivered_at = data.delivered_at;
if (data.platform_release_url !== undefined) updatePayload.platform_release_url = data.platform_release_url;
if (data.external_reference !== undefined) updatePayload.external_reference = data.external_reference;
if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
updatePayload.updatedById = currentUser.id;
await release_deliveries.update(updatePayload, {transaction});
if (data.release !== undefined) {
await release_deliveries.setRelease(
data.release,
{ transaction }
);
}
if (data.platform !== undefined) {
await release_deliveries.setPlatform(
data.platform,
{ transaction }
);
}
if (data.organizations !== undefined) {
await release_deliveries.setOrganizations(
data.organizations,
{ transaction }
);
}
return release_deliveries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const release_deliveries = await db.release_deliveries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of release_deliveries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of release_deliveries) {
await record.destroy({transaction});
}
});
return release_deliveries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const release_deliveries = await db.release_deliveries.findByPk(id, options);
await release_deliveries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await release_deliveries.destroy({
transaction
});
return release_deliveries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const release_deliveries = await db.release_deliveries.findOne(
{ where },
{ transaction },
);
if (!release_deliveries) {
return release_deliveries;
}
const output = release_deliveries.get({plain: true});
output.release = await release_deliveries.getRelease({
transaction
});
output.platform = await release_deliveries.getPlatform({
transaction
});
output.organizations = await release_deliveries.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.releases,
as: 'release',
where: filter.release ? {
[Op.or]: [
{ id: { [Op.in]: filter.release.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.release.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.distribution_platforms,
as: 'platform',
where: filter.platform ? {
[Op.or]: [
{ id: { [Op.in]: filter.platform.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.platform.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.platform_release_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'release_deliveries',
'platform_release_url',
filter.platform_release_url,
),
};
}
if (filter.external_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'release_deliveries',
'external_reference',
filter.external_reference,
),
};
}
if (filter.error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'release_deliveries',
'error_message',
filter.error_message,
),
};
}
if (filter.requested_atRange) {
const [start, end] = filter.requested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.delivered_atRange) {
const [start, end] = filter.delivered_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
delivered_at: {
...where.delivered_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
delivered_at: {
...where.delivered_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.delivery_status) {
where = {
...where,
delivery_status: filter.delivery_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.release_deliveries.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(
'release_deliveries',
'delivery_status',
query,
),
],
};
}
const records = await db.release_deliveries.findAll({
attributes: [ 'id', 'delivery_status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['delivery_status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.delivery_status,
}));
}
};

File diff suppressed because it is too large Load Diff

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

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

View File

@ -0,0 +1,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 Royalty_linesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const royalty_lines = await db.royalty_lines.create(
{
id: data.id || undefined,
territory: data.territory
||
null
,
store_name: data.store_name
||
null
,
quantity: data.quantity
||
null
,
unit_rate: data.unit_rate
||
null
,
gross_amount: data.gross_amount
||
null
,
net_amount: data.net_amount
||
null
,
currency: data.currency
||
null
,
event_at: data.event_at
||
null
,
usage_type: data.usage_type
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await royalty_lines.setRoyalty_report( data.royalty_report || null, {
transaction,
});
await royalty_lines.setRelease( data.release || null, {
transaction,
});
await royalty_lines.setTrack( data.track || null, {
transaction,
});
await royalty_lines.setOrganizations( data.organizations || null, {
transaction,
});
return royalty_lines;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const royalty_linesData = data.map((item, index) => ({
id: item.id || undefined,
territory: item.territory
||
null
,
store_name: item.store_name
||
null
,
quantity: item.quantity
||
null
,
unit_rate: item.unit_rate
||
null
,
gross_amount: item.gross_amount
||
null
,
net_amount: item.net_amount
||
null
,
currency: item.currency
||
null
,
event_at: item.event_at
||
null
,
usage_type: item.usage_type
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const royalty_lines = await db.royalty_lines.bulkCreate(royalty_linesData, { transaction });
// For each item created, replace relation files
return royalty_lines;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const royalty_lines = await db.royalty_lines.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.territory !== undefined) updatePayload.territory = data.territory;
if (data.store_name !== undefined) updatePayload.store_name = data.store_name;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.unit_rate !== undefined) updatePayload.unit_rate = data.unit_rate;
if (data.gross_amount !== undefined) updatePayload.gross_amount = data.gross_amount;
if (data.net_amount !== undefined) updatePayload.net_amount = data.net_amount;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.event_at !== undefined) updatePayload.event_at = data.event_at;
if (data.usage_type !== undefined) updatePayload.usage_type = data.usage_type;
updatePayload.updatedById = currentUser.id;
await royalty_lines.update(updatePayload, {transaction});
if (data.royalty_report !== undefined) {
await royalty_lines.setRoyalty_report(
data.royalty_report,
{ transaction }
);
}
if (data.release !== undefined) {
await royalty_lines.setRelease(
data.release,
{ transaction }
);
}
if (data.track !== undefined) {
await royalty_lines.setTrack(
data.track,
{ transaction }
);
}
if (data.organizations !== undefined) {
await royalty_lines.setOrganizations(
data.organizations,
{ transaction }
);
}
return royalty_lines;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const royalty_lines = await db.royalty_lines.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of royalty_lines) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of royalty_lines) {
await record.destroy({transaction});
}
});
return royalty_lines;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const royalty_lines = await db.royalty_lines.findByPk(id, options);
await royalty_lines.update({
deletedBy: currentUser.id
}, {
transaction,
});
await royalty_lines.destroy({
transaction
});
return royalty_lines;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const royalty_lines = await db.royalty_lines.findOne(
{ where },
{ transaction },
);
if (!royalty_lines) {
return royalty_lines;
}
const output = royalty_lines.get({plain: true});
output.royalty_report = await royalty_lines.getRoyalty_report({
transaction
});
output.release = await royalty_lines.getRelease({
transaction
});
output.track = await royalty_lines.getTrack({
transaction
});
output.organizations = await royalty_lines.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.royalty_reports,
as: 'royalty_report',
where: filter.royalty_report ? {
[Op.or]: [
{ id: { [Op.in]: filter.royalty_report.split('|').map(term => Utils.uuid(term)) } },
{
source_reference: {
[Op.or]: filter.royalty_report.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.releases,
as: 'release',
where: filter.release ? {
[Op.or]: [
{ id: { [Op.in]: filter.release.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.release.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.tracks,
as: 'track',
where: filter.track ? {
[Op.or]: [
{ id: { [Op.in]: filter.track.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.track.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.territory) {
where = {
...where,
[Op.and]: Utils.ilike(
'royalty_lines',
'territory',
filter.territory,
),
};
}
if (filter.store_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'royalty_lines',
'store_name',
filter.store_name,
),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'royalty_lines',
'currency',
filter.currency,
),
};
}
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_rateRange) {
const [start, end] = filter.unit_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unit_rate: {
...where.unit_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unit_rate: {
...where.unit_rate,
[Op.lte]: end,
},
};
}
}
if (filter.gross_amountRange) {
const [start, end] = filter.gross_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
gross_amount: {
...where.gross_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
gross_amount: {
...where.gross_amount,
[Op.lte]: end,
},
};
}
}
if (filter.net_amountRange) {
const [start, end] = filter.net_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
net_amount: {
...where.net_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
net_amount: {
...where.net_amount,
[Op.lte]: end,
},
};
}
}
if (filter.event_atRange) {
const [start, end] = filter.event_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
event_at: {
...where.event_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
event_at: {
...where.event_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.usage_type) {
where = {
...where,
usage_type: filter.usage_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.royalty_lines.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'royalty_lines',
'store_name',
query,
),
],
};
}
const records = await db.royalty_lines.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,697 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Royalty_reportsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const royalty_reports = await db.royalty_reports.create(
{
id: data.id || undefined,
period_start_at: data.period_start_at
||
null
,
period_end_at: data.period_end_at
||
null
,
source_type: data.source_type
||
null
,
source_reference: data.source_reference
||
null
,
status: data.status
||
null
,
error_details: data.error_details
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await royalty_reports.setArtist_profile( data.artist_profile || null, {
transaction,
});
await royalty_reports.setPlatform( data.platform || null, {
transaction,
});
await royalty_reports.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.royalty_reports.getTableName(),
belongsToColumn: 'source_file',
belongsToId: royalty_reports.id,
},
data.source_file,
options,
);
return royalty_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 royalty_reportsData = data.map((item, index) => ({
id: item.id || undefined,
period_start_at: item.period_start_at
||
null
,
period_end_at: item.period_end_at
||
null
,
source_type: item.source_type
||
null
,
source_reference: item.source_reference
||
null
,
status: item.status
||
null
,
error_details: item.error_details
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const royalty_reports = await db.royalty_reports.bulkCreate(royalty_reportsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < royalty_reports.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.royalty_reports.getTableName(),
belongsToColumn: 'source_file',
belongsToId: royalty_reports[i].id,
},
data[i].source_file,
options,
);
}
return royalty_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 royalty_reports = await db.royalty_reports.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.period_start_at !== undefined) updatePayload.period_start_at = data.period_start_at;
if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
if (data.source_type !== undefined) updatePayload.source_type = data.source_type;
if (data.source_reference !== undefined) updatePayload.source_reference = data.source_reference;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.error_details !== undefined) updatePayload.error_details = data.error_details;
updatePayload.updatedById = currentUser.id;
await royalty_reports.update(updatePayload, {transaction});
if (data.artist_profile !== undefined) {
await royalty_reports.setArtist_profile(
data.artist_profile,
{ transaction }
);
}
if (data.platform !== undefined) {
await royalty_reports.setPlatform(
data.platform,
{ transaction }
);
}
if (data.organizations !== undefined) {
await royalty_reports.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.royalty_reports.getTableName(),
belongsToColumn: 'source_file',
belongsToId: royalty_reports.id,
},
data.source_file,
options,
);
return royalty_reports;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const royalty_reports = await db.royalty_reports.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of royalty_reports) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of royalty_reports) {
await record.destroy({transaction});
}
});
return royalty_reports;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const royalty_reports = await db.royalty_reports.findByPk(id, options);
await royalty_reports.update({
deletedBy: currentUser.id
}, {
transaction,
});
await royalty_reports.destroy({
transaction
});
return royalty_reports;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const royalty_reports = await db.royalty_reports.findOne(
{ where },
{ transaction },
);
if (!royalty_reports) {
return royalty_reports;
}
const output = royalty_reports.get({plain: true});
output.royalty_lines_royalty_report = await royalty_reports.getRoyalty_lines_royalty_report({
transaction
});
output.artist_profile = await royalty_reports.getArtist_profile({
transaction
});
output.platform = await royalty_reports.getPlatform({
transaction
});
output.source_file = await royalty_reports.getSource_file({
transaction
});
output.organizations = await royalty_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.artist_profiles,
as: 'artist_profile',
where: filter.artist_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.artist_profile.split('|').map(term => Utils.uuid(term)) } },
{
artist_name: {
[Op.or]: filter.artist_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.distribution_platforms,
as: 'platform',
where: filter.platform ? {
[Op.or]: [
{ id: { [Op.in]: filter.platform.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.platform.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'source_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.source_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'royalty_reports',
'source_reference',
filter.source_reference,
),
};
}
if (filter.error_details) {
where = {
...where,
[Op.and]: Utils.ilike(
'royalty_reports',
'error_details',
filter.error_details,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
period_start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
period_end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.period_start_atRange) {
const [start, end] = filter.period_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_start_at: {
...where.period_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_start_at: {
...where.period_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.period_end_atRange) {
const [start, end] = filter.period_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_end_at: {
...where.period_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_end_at: {
...where.period_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.source_type) {
where = {
...where,
source_type: filter.source_type,
};
}
if (filter.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.royalty_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(
'royalty_reports',
'source_reference',
query,
),
],
};
}
const records = await db.royalty_reports.findAll({
attributes: [ 'id', 'source_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['source_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.source_reference,
}));
}
};

View File

@ -0,0 +1,628 @@
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 Smart_link_clicksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const smart_link_clicks = await db.smart_link_clicks.create(
{
id: data.id || undefined,
clicked_at: data.clicked_at
||
null
,
country: data.country
||
null
,
city: data.city
||
null
,
referrer: data.referrer
||
null
,
utm_source: data.utm_source
||
null
,
utm_campaign: data.utm_campaign
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await smart_link_clicks.setSmart_link( data.smart_link || null, {
transaction,
});
await smart_link_clicks.setPlatform( data.platform || null, {
transaction,
});
await smart_link_clicks.setOrganizations( data.organizations || null, {
transaction,
});
return smart_link_clicks;
}
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 smart_link_clicksData = data.map((item, index) => ({
id: item.id || undefined,
clicked_at: item.clicked_at
||
null
,
country: item.country
||
null
,
city: item.city
||
null
,
referrer: item.referrer
||
null
,
utm_source: item.utm_source
||
null
,
utm_campaign: item.utm_campaign
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const smart_link_clicks = await db.smart_link_clicks.bulkCreate(smart_link_clicksData, { transaction });
// For each item created, replace relation files
return smart_link_clicks;
}
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 smart_link_clicks = await db.smart_link_clicks.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.clicked_at !== undefined) updatePayload.clicked_at = data.clicked_at;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.referrer !== undefined) updatePayload.referrer = data.referrer;
if (data.utm_source !== undefined) updatePayload.utm_source = data.utm_source;
if (data.utm_campaign !== undefined) updatePayload.utm_campaign = data.utm_campaign;
updatePayload.updatedById = currentUser.id;
await smart_link_clicks.update(updatePayload, {transaction});
if (data.smart_link !== undefined) {
await smart_link_clicks.setSmart_link(
data.smart_link,
{ transaction }
);
}
if (data.platform !== undefined) {
await smart_link_clicks.setPlatform(
data.platform,
{ transaction }
);
}
if (data.organizations !== undefined) {
await smart_link_clicks.setOrganizations(
data.organizations,
{ transaction }
);
}
return smart_link_clicks;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const smart_link_clicks = await db.smart_link_clicks.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of smart_link_clicks) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of smart_link_clicks) {
await record.destroy({transaction});
}
});
return smart_link_clicks;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const smart_link_clicks = await db.smart_link_clicks.findByPk(id, options);
await smart_link_clicks.update({
deletedBy: currentUser.id
}, {
transaction,
});
await smart_link_clicks.destroy({
transaction
});
return smart_link_clicks;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const smart_link_clicks = await db.smart_link_clicks.findOne(
{ where },
{ transaction },
);
if (!smart_link_clicks) {
return smart_link_clicks;
}
const output = smart_link_clicks.get({plain: true});
output.smart_link = await smart_link_clicks.getSmart_link({
transaction
});
output.platform = await smart_link_clicks.getPlatform({
transaction
});
output.organizations = await smart_link_clicks.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.smart_links,
as: 'smart_link',
where: filter.smart_link ? {
[Op.or]: [
{ id: { [Op.in]: filter.smart_link.split('|').map(term => Utils.uuid(term)) } },
{
slug: {
[Op.or]: filter.smart_link.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.distribution_platforms,
as: 'platform',
where: filter.platform ? {
[Op.or]: [
{ id: { [Op.in]: filter.platform.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.platform.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.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'smart_link_clicks',
'country',
filter.country,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'smart_link_clicks',
'city',
filter.city,
),
};
}
if (filter.referrer) {
where = {
...where,
[Op.and]: Utils.ilike(
'smart_link_clicks',
'referrer',
filter.referrer,
),
};
}
if (filter.utm_source) {
where = {
...where,
[Op.and]: Utils.ilike(
'smart_link_clicks',
'utm_source',
filter.utm_source,
),
};
}
if (filter.utm_campaign) {
where = {
...where,
[Op.and]: Utils.ilike(
'smart_link_clicks',
'utm_campaign',
filter.utm_campaign,
),
};
}
if (filter.clicked_atRange) {
const [start, end] = filter.clicked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
clicked_at: {
...where.clicked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
clicked_at: {
...where.clicked_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.smart_link_clicks.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(
'smart_link_clicks',
'referrer',
query,
),
],
};
}
const records = await db.smart_link_clicks.findAll({
attributes: [ 'id', 'referrer' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['referrer', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.referrer,
}));
}
};

View File

@ -0,0 +1,554 @@
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 Smart_link_destinationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const smart_link_destinations = await db.smart_link_destinations.create(
{
id: data.id || undefined,
destination_url: data.destination_url
||
null
,
sort_order: data.sort_order
||
null
,
is_primary: data.is_primary
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await smart_link_destinations.setSmart_link( data.smart_link || null, {
transaction,
});
await smart_link_destinations.setPlatform( data.platform || null, {
transaction,
});
await smart_link_destinations.setOrganizations( data.organizations || null, {
transaction,
});
return smart_link_destinations;
}
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 smart_link_destinationsData = data.map((item, index) => ({
id: item.id || undefined,
destination_url: item.destination_url
||
null
,
sort_order: item.sort_order
||
null
,
is_primary: item.is_primary
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const smart_link_destinations = await db.smart_link_destinations.bulkCreate(smart_link_destinationsData, { transaction });
// For each item created, replace relation files
return smart_link_destinations;
}
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 smart_link_destinations = await db.smart_link_destinations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.destination_url !== undefined) updatePayload.destination_url = data.destination_url;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_primary !== undefined) updatePayload.is_primary = data.is_primary;
updatePayload.updatedById = currentUser.id;
await smart_link_destinations.update(updatePayload, {transaction});
if (data.smart_link !== undefined) {
await smart_link_destinations.setSmart_link(
data.smart_link,
{ transaction }
);
}
if (data.platform !== undefined) {
await smart_link_destinations.setPlatform(
data.platform,
{ transaction }
);
}
if (data.organizations !== undefined) {
await smart_link_destinations.setOrganizations(
data.organizations,
{ transaction }
);
}
return smart_link_destinations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const smart_link_destinations = await db.smart_link_destinations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of smart_link_destinations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of smart_link_destinations) {
await record.destroy({transaction});
}
});
return smart_link_destinations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const smart_link_destinations = await db.smart_link_destinations.findByPk(id, options);
await smart_link_destinations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await smart_link_destinations.destroy({
transaction
});
return smart_link_destinations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const smart_link_destinations = await db.smart_link_destinations.findOne(
{ where },
{ transaction },
);
if (!smart_link_destinations) {
return smart_link_destinations;
}
const output = smart_link_destinations.get({plain: true});
output.smart_link = await smart_link_destinations.getSmart_link({
transaction
});
output.platform = await smart_link_destinations.getPlatform({
transaction
});
output.organizations = await smart_link_destinations.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.smart_links,
as: 'smart_link',
where: filter.smart_link ? {
[Op.or]: [
{ id: { [Op.in]: filter.smart_link.split('|').map(term => Utils.uuid(term)) } },
{
slug: {
[Op.or]: filter.smart_link.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.distribution_platforms,
as: 'platform',
where: filter.platform ? {
[Op.or]: [
{ id: { [Op.in]: filter.platform.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.platform.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.destination_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'smart_link_destinations',
'destination_url',
filter.destination_url,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_primary) {
where = {
...where,
is_primary: filter.is_primary,
};
}
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.smart_link_destinations.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(
'smart_link_destinations',
'destination_url',
query,
),
],
};
}
const records = await db.smart_link_destinations.findAll({
attributes: [ 'id', 'destination_url' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['destination_url', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.destination_url,
}));
}
};

View File

@ -0,0 +1,681 @@
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 Smart_linksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const smart_links = await db.smart_links.create(
{
id: data.id || undefined,
slug: data.slug
||
null
,
page_title: data.page_title
||
null
,
custom_text: data.custom_text
||
null
,
theme_color: data.theme_color
||
null
,
is_public: data.is_public
||
false
,
published_at: data.published_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await smart_links.setRelease( data.release || null, {
transaction,
});
await smart_links.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.smart_links.getTableName(),
belongsToColumn: 'background_image',
belongsToId: smart_links.id,
},
data.background_image,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.smart_links.getTableName(),
belongsToColumn: 'artist_photo',
belongsToId: smart_links.id,
},
data.artist_photo,
options,
);
return smart_links;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const smart_linksData = data.map((item, index) => ({
id: item.id || undefined,
slug: item.slug
||
null
,
page_title: item.page_title
||
null
,
custom_text: item.custom_text
||
null
,
theme_color: item.theme_color
||
null
,
is_public: item.is_public
||
false
,
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 smart_links = await db.smart_links.bulkCreate(smart_linksData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < smart_links.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.smart_links.getTableName(),
belongsToColumn: 'background_image',
belongsToId: smart_links[i].id,
},
data[i].background_image,
options,
);
}
for (let i = 0; i < smart_links.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.smart_links.getTableName(),
belongsToColumn: 'artist_photo',
belongsToId: smart_links[i].id,
},
data[i].artist_photo,
options,
);
}
return smart_links;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const smart_links = await db.smart_links.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.page_title !== undefined) updatePayload.page_title = data.page_title;
if (data.custom_text !== undefined) updatePayload.custom_text = data.custom_text;
if (data.theme_color !== undefined) updatePayload.theme_color = data.theme_color;
if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
updatePayload.updatedById = currentUser.id;
await smart_links.update(updatePayload, {transaction});
if (data.release !== undefined) {
await smart_links.setRelease(
data.release,
{ transaction }
);
}
if (data.organizations !== undefined) {
await smart_links.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.smart_links.getTableName(),
belongsToColumn: 'background_image',
belongsToId: smart_links.id,
},
data.background_image,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.smart_links.getTableName(),
belongsToColumn: 'artist_photo',
belongsToId: smart_links.id,
},
data.artist_photo,
options,
);
return smart_links;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const smart_links = await db.smart_links.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of smart_links) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of smart_links) {
await record.destroy({transaction});
}
});
return smart_links;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const smart_links = await db.smart_links.findByPk(id, options);
await smart_links.update({
deletedBy: currentUser.id
}, {
transaction,
});
await smart_links.destroy({
transaction
});
return smart_links;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const smart_links = await db.smart_links.findOne(
{ where },
{ transaction },
);
if (!smart_links) {
return smart_links;
}
const output = smart_links.get({plain: true});
output.smart_link_destinations_smart_link = await smart_links.getSmart_link_destinations_smart_link({
transaction
});
output.smart_link_clicks_smart_link = await smart_links.getSmart_link_clicks_smart_link({
transaction
});
output.release = await smart_links.getRelease({
transaction
});
output.background_image = await smart_links.getBackground_image({
transaction
});
output.artist_photo = await smart_links.getArtist_photo({
transaction
});
output.organizations = await smart_links.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.releases,
as: 'release',
where: filter.release ? {
[Op.or]: [
{ id: { [Op.in]: filter.release.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.release.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'background_image',
},
{
model: db.file,
as: 'artist_photo',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'smart_links',
'slug',
filter.slug,
),
};
}
if (filter.page_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'smart_links',
'page_title',
filter.page_title,
),
};
}
if (filter.custom_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'smart_links',
'custom_text',
filter.custom_text,
),
};
}
if (filter.theme_color) {
where = {
...where,
[Op.and]: Utils.ilike(
'smart_links',
'theme_color',
filter.theme_color,
),
};
}
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.is_public) {
where = {
...where,
is_public: filter.is_public,
};
}
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.smart_links.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'smart_links',
'slug',
query,
),
],
};
}
const records = await db.smart_links.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,
}));
}
};

View File

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

View File

@ -0,0 +1,632 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Tax_documentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tax_documents = await db.tax_documents.create(
{
id: data.id || undefined,
document_type: data.document_type
||
null
,
status: data.status
||
null
,
issued_at: data.issued_at
||
null
,
expires_at: data.expires_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tax_documents.setUser( data.user || null, {
transaction,
});
await tax_documents.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tax_documents.getTableName(),
belongsToColumn: 'document_file',
belongsToId: tax_documents.id,
},
data.document_file,
options,
);
return tax_documents;
}
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 tax_documentsData = data.map((item, index) => ({
id: item.id || undefined,
document_type: item.document_type
||
null
,
status: item.status
||
null
,
issued_at: item.issued_at
||
null
,
expires_at: item.expires_at
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tax_documents = await db.tax_documents.bulkCreate(tax_documentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < tax_documents.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tax_documents.getTableName(),
belongsToColumn: 'document_file',
belongsToId: tax_documents[i].id,
},
data[i].document_file,
options,
);
}
return tax_documents;
}
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 tax_documents = await db.tax_documents.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await tax_documents.update(updatePayload, {transaction});
if (data.user !== undefined) {
await tax_documents.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await tax_documents.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tax_documents.getTableName(),
belongsToColumn: 'document_file',
belongsToId: tax_documents.id,
},
data.document_file,
options,
);
return tax_documents;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tax_documents = await db.tax_documents.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tax_documents) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tax_documents) {
await record.destroy({transaction});
}
});
return tax_documents;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tax_documents = await db.tax_documents.findByPk(id, options);
await tax_documents.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tax_documents.destroy({
transaction
});
return tax_documents;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tax_documents = await db.tax_documents.findOne(
{ where },
{ transaction },
);
if (!tax_documents) {
return tax_documents;
}
const output = tax_documents.get({plain: true});
output.user = await tax_documents.getUser({
transaction
});
output.document_file = await tax_documents.getDocument_file({
transaction
});
output.organizations = await tax_documents.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'document_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'tax_documents',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
issued_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
expires_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.lte]: end,
},
};
}
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.document_type) {
where = {
...where,
document_type: filter.document_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.tax_documents.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(
'tax_documents',
'document_type',
query,
),
],
};
}
const records = await db.tax_documents.findAll({
attributes: [ 'id', 'document_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['document_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.document_type,
}));
}
};

View File

@ -0,0 +1,585 @@
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 Team_membershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const team_memberships = await db.team_memberships.create(
{
id: data.id || undefined,
role: data.role
||
null
,
status: data.status
||
null
,
invited_at: data.invited_at
||
null
,
accepted_at: data.accepted_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await team_memberships.setTeam( data.team || null, {
transaction,
});
await team_memberships.setMember_user( data.member_user || null, {
transaction,
});
await team_memberships.setOrganizations( data.organizations || null, {
transaction,
});
return team_memberships;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const team_membershipsData = data.map((item, index) => ({
id: item.id || undefined,
role: item.role
||
null
,
status: item.status
||
null
,
invited_at: item.invited_at
||
null
,
accepted_at: item.accepted_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const team_memberships = await db.team_memberships.bulkCreate(team_membershipsData, { transaction });
// For each item created, replace relation files
return team_memberships;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const team_memberships = await db.team_memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.role !== undefined) updatePayload.role = data.role;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.invited_at !== undefined) updatePayload.invited_at = data.invited_at;
if (data.accepted_at !== undefined) updatePayload.accepted_at = data.accepted_at;
updatePayload.updatedById = currentUser.id;
await team_memberships.update(updatePayload, {transaction});
if (data.team !== undefined) {
await team_memberships.setTeam(
data.team,
{ transaction }
);
}
if (data.member_user !== undefined) {
await team_memberships.setMember_user(
data.member_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await team_memberships.setOrganizations(
data.organizations,
{ transaction }
);
}
return team_memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const team_memberships = await db.team_memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of team_memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of team_memberships) {
await record.destroy({transaction});
}
});
return team_memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const team_memberships = await db.team_memberships.findByPk(id, options);
await team_memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await team_memberships.destroy({
transaction
});
return team_memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const team_memberships = await db.team_memberships.findOne(
{ where },
{ transaction },
);
if (!team_memberships) {
return team_memberships;
}
const output = team_memberships.get({plain: true});
output.team = await team_memberships.getTeam({
transaction
});
output.member_user = await team_memberships.getMember_user({
transaction
});
output.organizations = await team_memberships.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.teams,
as: 'team',
where: filter.team ? {
[Op.or]: [
{ id: { [Op.in]: filter.team.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.team.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'member_user',
where: filter.member_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.member_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.member_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.invited_atRange) {
const [start, end] = filter.invited_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
invited_at: {
...where.invited_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
invited_at: {
...where.invited_at,
[Op.lte]: end,
},
};
}
}
if (filter.accepted_atRange) {
const [start, end] = filter.accepted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
accepted_at: {
...where.accepted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
accepted_at: {
...where.accepted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.role) {
where = {
...where,
role: filter.role,
};
}
if (filter.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.team_memberships.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'team_memberships',
'status',
query,
),
],
};
}
const records = await db.team_memberships.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

486
backend/src/db/api/teams.js Normal file
View File

@ -0,0 +1,486 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class TeamsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const teams = await db.teams.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await teams.setOwner( data.owner || null, {
transaction,
});
await teams.setOrganizations( data.organizations || null, {
transaction,
});
return teams;
}
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 teamsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const teams = await db.teams.bulkCreate(teamsData, { transaction });
// For each item created, replace relation files
return teams;
}
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 teams = await db.teams.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await teams.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await teams.setOwner(
data.owner,
{ transaction }
);
}
if (data.organizations !== undefined) {
await teams.setOrganizations(
data.organizations,
{ transaction }
);
}
return teams;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const teams = await db.teams.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of teams) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of teams) {
await record.destroy({transaction});
}
});
return teams;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const teams = await db.teams.findByPk(id, options);
await teams.update({
deletedBy: currentUser.id
}, {
transaction,
});
await teams.destroy({
transaction
});
return teams;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const teams = await db.teams.findOne(
{ where },
{ transaction },
);
if (!teams) {
return teams;
}
const output = teams.get({plain: true});
output.team_memberships_team = await teams.getTeam_memberships_team({
transaction
});
output.owner = await teams.getOwner({
transaction
});
output.organizations = await teams.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'teams',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'teams',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.teams.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(
'teams',
'name',
query,
),
],
};
}
const records = await db.teams.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,550 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Track_contributorsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const track_contributors = await db.track_contributors.create(
{
id: data.id || undefined,
name: data.name
||
null
,
role: data.role
||
null
,
spotify_artist_url: data.spotify_artist_url
||
null
,
apple_artist_url: data.apple_artist_url
||
null
,
society_identifier: data.society_identifier
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await track_contributors.setTrack( data.track || null, {
transaction,
});
await track_contributors.setOrganizations( data.organizations || null, {
transaction,
});
return track_contributors;
}
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 track_contributorsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
role: item.role
||
null
,
spotify_artist_url: item.spotify_artist_url
||
null
,
apple_artist_url: item.apple_artist_url
||
null
,
society_identifier: item.society_identifier
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const track_contributors = await db.track_contributors.bulkCreate(track_contributorsData, { transaction });
// For each item created, replace relation files
return track_contributors;
}
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 track_contributors = await db.track_contributors.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.role !== undefined) updatePayload.role = data.role;
if (data.spotify_artist_url !== undefined) updatePayload.spotify_artist_url = data.spotify_artist_url;
if (data.apple_artist_url !== undefined) updatePayload.apple_artist_url = data.apple_artist_url;
if (data.society_identifier !== undefined) updatePayload.society_identifier = data.society_identifier;
updatePayload.updatedById = currentUser.id;
await track_contributors.update(updatePayload, {transaction});
if (data.track !== undefined) {
await track_contributors.setTrack(
data.track,
{ transaction }
);
}
if (data.organizations !== undefined) {
await track_contributors.setOrganizations(
data.organizations,
{ transaction }
);
}
return track_contributors;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const track_contributors = await db.track_contributors.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of track_contributors) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of track_contributors) {
await record.destroy({transaction});
}
});
return track_contributors;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const track_contributors = await db.track_contributors.findByPk(id, options);
await track_contributors.update({
deletedBy: currentUser.id
}, {
transaction,
});
await track_contributors.destroy({
transaction
});
return track_contributors;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const track_contributors = await db.track_contributors.findOne(
{ where },
{ transaction },
);
if (!track_contributors) {
return track_contributors;
}
const output = track_contributors.get({plain: true});
output.track = await track_contributors.getTrack({
transaction
});
output.organizations = await track_contributors.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.tracks,
as: 'track',
where: filter.track ? {
[Op.or]: [
{ id: { [Op.in]: filter.track.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.track.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'track_contributors',
'name',
filter.name,
),
};
}
if (filter.spotify_artist_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'track_contributors',
'spotify_artist_url',
filter.spotify_artist_url,
),
};
}
if (filter.apple_artist_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'track_contributors',
'apple_artist_url',
filter.apple_artist_url,
),
};
}
if (filter.society_identifier) {
where = {
...where,
[Op.and]: Utils.ilike(
'track_contributors',
'society_identifier',
filter.society_identifier,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.role) {
where = {
...where,
role: filter.role,
};
}
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.track_contributors.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(
'track_contributors',
'name',
query,
),
],
};
}
const records = await db.track_contributors.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,907 @@
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 TracksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tracks = await db.tracks.create(
{
id: data.id || undefined,
title: data.title
||
null
,
track_number: data.track_number
||
null
,
version: data.version
||
null
,
isrc_code: data.isrc_code
||
null
,
isrc_source: data.isrc_source
||
null
,
duration_seconds: data.duration_seconds
||
null
,
sample_rate_hz: data.sample_rate_hz
||
null
,
bitrate_kbps: data.bitrate_kbps
||
null
,
audio_format: data.audio_format
||
null
,
explicit_content: data.explicit_content
||
false
,
lyrics: data.lyrics
||
null
,
audio_fingerprint: data.audio_fingerprint
||
null
,
quality_status: data.quality_status
||
null
,
quality_notes: data.quality_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tracks.setRelease( data.release || null, {
transaction,
});
await tracks.setGenre( data.genre || null, {
transaction,
});
await tracks.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tracks.getTableName(),
belongsToColumn: 'audio_file',
belongsToId: tracks.id,
},
data.audio_file,
options,
);
return tracks;
}
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 tracksData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
track_number: item.track_number
||
null
,
version: item.version
||
null
,
isrc_code: item.isrc_code
||
null
,
isrc_source: item.isrc_source
||
null
,
duration_seconds: item.duration_seconds
||
null
,
sample_rate_hz: item.sample_rate_hz
||
null
,
bitrate_kbps: item.bitrate_kbps
||
null
,
audio_format: item.audio_format
||
null
,
explicit_content: item.explicit_content
||
false
,
lyrics: item.lyrics
||
null
,
audio_fingerprint: item.audio_fingerprint
||
null
,
quality_status: item.quality_status
||
null
,
quality_notes: item.quality_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tracks = await db.tracks.bulkCreate(tracksData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < tracks.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tracks.getTableName(),
belongsToColumn: 'audio_file',
belongsToId: tracks[i].id,
},
data[i].audio_file,
options,
);
}
return tracks;
}
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 tracks = await db.tracks.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.track_number !== undefined) updatePayload.track_number = data.track_number;
if (data.version !== undefined) updatePayload.version = data.version;
if (data.isrc_code !== undefined) updatePayload.isrc_code = data.isrc_code;
if (data.isrc_source !== undefined) updatePayload.isrc_source = data.isrc_source;
if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
if (data.sample_rate_hz !== undefined) updatePayload.sample_rate_hz = data.sample_rate_hz;
if (data.bitrate_kbps !== undefined) updatePayload.bitrate_kbps = data.bitrate_kbps;
if (data.audio_format !== undefined) updatePayload.audio_format = data.audio_format;
if (data.explicit_content !== undefined) updatePayload.explicit_content = data.explicit_content;
if (data.lyrics !== undefined) updatePayload.lyrics = data.lyrics;
if (data.audio_fingerprint !== undefined) updatePayload.audio_fingerprint = data.audio_fingerprint;
if (data.quality_status !== undefined) updatePayload.quality_status = data.quality_status;
if (data.quality_notes !== undefined) updatePayload.quality_notes = data.quality_notes;
updatePayload.updatedById = currentUser.id;
await tracks.update(updatePayload, {transaction});
if (data.release !== undefined) {
await tracks.setRelease(
data.release,
{ transaction }
);
}
if (data.genre !== undefined) {
await tracks.setGenre(
data.genre,
{ transaction }
);
}
if (data.organizations !== undefined) {
await tracks.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tracks.getTableName(),
belongsToColumn: 'audio_file',
belongsToId: tracks.id,
},
data.audio_file,
options,
);
return tracks;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tracks = await db.tracks.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tracks) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tracks) {
await record.destroy({transaction});
}
});
return tracks;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tracks = await db.tracks.findByPk(id, options);
await tracks.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tracks.destroy({
transaction
});
return tracks;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tracks = await db.tracks.findOne(
{ where },
{ transaction },
);
if (!tracks) {
return tracks;
}
const output = tracks.get({plain: true});
output.track_contributors_track = await tracks.getTrack_contributors_track({
transaction
});
output.pitch_requests_track = await tracks.getPitch_requests_track({
transaction
});
output.playlist_placements_track = await tracks.getPlaylist_placements_track({
transaction
});
output.royalty_lines_track = await tracks.getRoyalty_lines_track({
transaction
});
output.analytics_daily_track = await tracks.getAnalytics_daily_track({
transaction
});
output.release = await tracks.getRelease({
transaction
});
output.genre = await tracks.getGenre({
transaction
});
output.audio_file = await tracks.getAudio_file({
transaction
});
output.organizations = await tracks.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.releases,
as: 'release',
where: filter.release ? {
[Op.or]: [
{ id: { [Op.in]: filter.release.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.release.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.genres,
as: 'genre',
where: filter.genre ? {
[Op.or]: [
{ id: { [Op.in]: filter.genre.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.genre.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'audio_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'tracks',
'title',
filter.title,
),
};
}
if (filter.version) {
where = {
...where,
[Op.and]: Utils.ilike(
'tracks',
'version',
filter.version,
),
};
}
if (filter.isrc_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'tracks',
'isrc_code',
filter.isrc_code,
),
};
}
if (filter.lyrics) {
where = {
...where,
[Op.and]: Utils.ilike(
'tracks',
'lyrics',
filter.lyrics,
),
};
}
if (filter.audio_fingerprint) {
where = {
...where,
[Op.and]: Utils.ilike(
'tracks',
'audio_fingerprint',
filter.audio_fingerprint,
),
};
}
if (filter.quality_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'tracks',
'quality_notes',
filter.quality_notes,
),
};
}
if (filter.track_numberRange) {
const [start, end] = filter.track_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
track_number: {
...where.track_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
track_number: {
...where.track_number,
[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.sample_rate_hzRange) {
const [start, end] = filter.sample_rate_hzRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sample_rate_hz: {
...where.sample_rate_hz,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sample_rate_hz: {
...where.sample_rate_hz,
[Op.lte]: end,
},
};
}
}
if (filter.bitrate_kbpsRange) {
const [start, end] = filter.bitrate_kbpsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bitrate_kbps: {
...where.bitrate_kbps,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bitrate_kbps: {
...where.bitrate_kbps,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.isrc_source) {
where = {
...where,
isrc_source: filter.isrc_source,
};
}
if (filter.audio_format) {
where = {
...where,
audio_format: filter.audio_format,
};
}
if (filter.explicit_content) {
where = {
...where,
explicit_content: filter.explicit_content,
};
}
if (filter.quality_status) {
where = {
...where,
quality_status: filter.quality_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.tracks.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(
'tracks',
'title',
query,
),
],
};
}
const records = await db.tracks.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,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,600 @@
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,
transaction_type: data.transaction_type
||
null
,
amount: data.amount
||
null
,
currency: data.currency
||
null
,
posted_at: data.posted_at
||
null
,
description: data.description
||
null
,
external_reference: data.external_reference
||
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,
transaction_type: item.transaction_type
||
null
,
amount: item.amount
||
null
,
currency: item.currency
||
null
,
posted_at: item.posted_at
||
null
,
description: item.description
||
null
,
external_reference: item.external_reference
||
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.transaction_type !== undefined) updatePayload.transaction_type = data.transaction_type;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.external_reference !== undefined) updatePayload.external_reference = data.external_reference;
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.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.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallet_transactions',
'description',
filter.description,
),
};
}
if (filter.external_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallet_transactions',
'external_reference',
filter.external_reference,
),
};
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.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.transaction_type) {
where = {
...where,
transaction_type: filter.transaction_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.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',
'description',
query,
),
],
};
}
const records = await db.wallet_transactions.findAll({
attributes: [ 'id', 'description' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['description', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.description,
}));
}
};

View File

@ -0,0 +1,651 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class WalletsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const wallets = await db.wallets.create(
{
id: data.id || undefined,
currency: data.currency
||
null
,
available_balance: data.available_balance
||
null
,
pending_balance: data.pending_balance
||
null
,
lifetime_earned: data.lifetime_earned
||
null
,
lifetime_paid_out: data.lifetime_paid_out
||
null
,
minimum_withdrawal_amount: data.minimum_withdrawal_amount
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await wallets.setUser( data.user || null, {
transaction,
});
await wallets.setOrganizations( data.organizations || null, {
transaction,
});
return wallets;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const walletsData = data.map((item, index) => ({
id: item.id || undefined,
currency: item.currency
||
null
,
available_balance: item.available_balance
||
null
,
pending_balance: item.pending_balance
||
null
,
lifetime_earned: item.lifetime_earned
||
null
,
lifetime_paid_out: item.lifetime_paid_out
||
null
,
minimum_withdrawal_amount: item.minimum_withdrawal_amount
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const wallets = await db.wallets.bulkCreate(walletsData, { transaction });
// For each item created, replace relation files
return wallets;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const wallets = await db.wallets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.available_balance !== undefined) updatePayload.available_balance = data.available_balance;
if (data.pending_balance !== undefined) updatePayload.pending_balance = data.pending_balance;
if (data.lifetime_earned !== undefined) updatePayload.lifetime_earned = data.lifetime_earned;
if (data.lifetime_paid_out !== undefined) updatePayload.lifetime_paid_out = data.lifetime_paid_out;
if (data.minimum_withdrawal_amount !== undefined) updatePayload.minimum_withdrawal_amount = data.minimum_withdrawal_amount;
updatePayload.updatedById = currentUser.id;
await wallets.update(updatePayload, {transaction});
if (data.user !== undefined) {
await wallets.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await wallets.setOrganizations(
data.organizations,
{ transaction }
);
}
return wallets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const wallets = await db.wallets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of wallets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of wallets) {
await record.destroy({transaction});
}
});
return wallets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const wallets = await db.wallets.findByPk(id, options);
await wallets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await wallets.destroy({
transaction
});
return wallets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const wallets = await db.wallets.findOne(
{ where },
{ transaction },
);
if (!wallets) {
return wallets;
}
const output = wallets.get({plain: true});
output.wallet_transactions_wallet = await wallets.getWallet_transactions_wallet({
transaction
});
output.withdrawal_requests_wallet = await wallets.getWithdrawal_requests_wallet({
transaction
});
output.user = await wallets.getUser({
transaction
});
output.organizations = await wallets.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: '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.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'wallets',
'currency',
filter.currency,
),
};
}
if (filter.available_balanceRange) {
const [start, end] = filter.available_balanceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
available_balance: {
...where.available_balance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
available_balance: {
...where.available_balance,
[Op.lte]: end,
},
};
}
}
if (filter.pending_balanceRange) {
const [start, end] = filter.pending_balanceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pending_balance: {
...where.pending_balance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pending_balance: {
...where.pending_balance,
[Op.lte]: end,
},
};
}
}
if (filter.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_paid_outRange) {
const [start, end] = filter.lifetime_paid_outRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lifetime_paid_out: {
...where.lifetime_paid_out,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lifetime_paid_out: {
...where.lifetime_paid_out,
[Op.lte]: end,
},
};
}
}
if (filter.minimum_withdrawal_amountRange) {
const [start, end] = filter.minimum_withdrawal_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
minimum_withdrawal_amount: {
...where.minimum_withdrawal_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
minimum_withdrawal_amount: {
...where.minimum_withdrawal_amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.wallets.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'wallets',
'currency',
query,
),
],
};
}
const records = await db.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,674 @@
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 Withdrawal_requestsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const withdrawal_requests = await db.withdrawal_requests.create(
{
id: data.id || undefined,
amount: data.amount
||
null
,
currency: data.currency
||
null
,
status: data.status
||
null
,
requested_at: data.requested_at
||
null
,
processed_at: data.processed_at
||
null
,
processor_reference: data.processor_reference
||
null
,
failure_reason: data.failure_reason
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await withdrawal_requests.setWallet( data.wallet || null, {
transaction,
});
await withdrawal_requests.setPayout_method( data.payout_method || null, {
transaction,
});
await withdrawal_requests.setOrganizations( data.organizations || null, {
transaction,
});
return withdrawal_requests;
}
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 withdrawal_requestsData = data.map((item, index) => ({
id: item.id || undefined,
amount: item.amount
||
null
,
currency: item.currency
||
null
,
status: item.status
||
null
,
requested_at: item.requested_at
||
null
,
processed_at: item.processed_at
||
null
,
processor_reference: item.processor_reference
||
null
,
failure_reason: item.failure_reason
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const withdrawal_requests = await db.withdrawal_requests.bulkCreate(withdrawal_requestsData, { transaction });
// For each item created, replace relation files
return withdrawal_requests;
}
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 withdrawal_requests = await db.withdrawal_requests.findByPk(id, {}, {transaction});
const updatePayload = {};
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.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
if (data.processed_at !== undefined) updatePayload.processed_at = data.processed_at;
if (data.processor_reference !== undefined) updatePayload.processor_reference = data.processor_reference;
if (data.failure_reason !== undefined) updatePayload.failure_reason = data.failure_reason;
updatePayload.updatedById = currentUser.id;
await withdrawal_requests.update(updatePayload, {transaction});
if (data.wallet !== undefined) {
await withdrawal_requests.setWallet(
data.wallet,
{ transaction }
);
}
if (data.payout_method !== undefined) {
await withdrawal_requests.setPayout_method(
data.payout_method,
{ transaction }
);
}
if (data.organizations !== undefined) {
await withdrawal_requests.setOrganizations(
data.organizations,
{ transaction }
);
}
return withdrawal_requests;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const withdrawal_requests = await db.withdrawal_requests.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of withdrawal_requests) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of withdrawal_requests) {
await record.destroy({transaction});
}
});
return withdrawal_requests;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const withdrawal_requests = await db.withdrawal_requests.findByPk(id, options);
await withdrawal_requests.update({
deletedBy: currentUser.id
}, {
transaction,
});
await withdrawal_requests.destroy({
transaction
});
return withdrawal_requests;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const withdrawal_requests = await db.withdrawal_requests.findOne(
{ where },
{ transaction },
);
if (!withdrawal_requests) {
return withdrawal_requests;
}
const output = withdrawal_requests.get({plain: true});
output.wallet = await withdrawal_requests.getWallet({
transaction
});
output.payout_method = await withdrawal_requests.getPayout_method({
transaction
});
output.organizations = await withdrawal_requests.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.wallets,
as: 'wallet',
where: filter.wallet ? {
[Op.or]: [
{ id: { [Op.in]: filter.wallet.split('|').map(term => Utils.uuid(term)) } },
{
currency: {
[Op.or]: filter.wallet.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.payout_methods,
as: 'payout_method',
where: filter.payout_method ? {
[Op.or]: [
{ id: { [Op.in]: filter.payout_method.split('|').map(term => Utils.uuid(term)) } },
{
method_label: {
[Op.or]: filter.payout_method.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(
'withdrawal_requests',
'currency',
filter.currency,
),
};
}
if (filter.processor_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'withdrawal_requests',
'processor_reference',
filter.processor_reference,
),
};
}
if (filter.failure_reason) {
where = {
...where,
[Op.and]: Utils.ilike(
'withdrawal_requests',
'failure_reason',
filter.failure_reason,
),
};
}
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.requested_atRange) {
const [start, end] = filter.requested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.lte]: end,
},
};
}
}
if (filter.processed_atRange) {
const [start, end] = filter.processed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
processed_at: {
...where.processed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
processed_at: {
...where.processed_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.withdrawal_requests.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(
'withdrawal_requests',
'status',
query,
),
],
};
}
const records = await db.withdrawal_requests.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,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___________________________',
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,181 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const activity_events = sequelize.define(
'activity_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_kind: {
type: DataTypes.ENUM,
values: [
"playlist",
"finance",
"moderation",
"milestone",
"notification",
"warning",
"security"
],
},
headline: {
type: DataTypes.TEXT,
},
details: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
entity_name: {
type: DataTypes.TEXT,
},
entity_key: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
activity_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.activity_events.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.activity_events.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.activity_events.belongsTo(db.users, {
as: 'createdBy',
});
db.activity_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return activity_events;
};

View File

@ -0,0 +1,202 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const analytics_daily = sequelize.define(
'analytics_daily',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
metric_date: {
type: DataTypes.DATE,
},
streams: {
type: DataTypes.INTEGER,
},
unique_listeners: {
type: DataTypes.INTEGER,
},
saves: {
type: DataTypes.INTEGER,
},
likes: {
type: DataTypes.INTEGER,
},
shares: {
type: DataTypes.INTEGER,
},
country: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
traffic_source: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
analytics_daily.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.analytics_daily.belongsTo(db.artist_profiles, {
as: 'artist_profile',
foreignKey: {
name: 'artist_profileId',
},
constraints: false,
});
db.analytics_daily.belongsTo(db.distribution_platforms, {
as: 'platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.analytics_daily.belongsTo(db.releases, {
as: 'release',
foreignKey: {
name: 'releaseId',
},
constraints: false,
});
db.analytics_daily.belongsTo(db.tracks, {
as: 'track',
foreignKey: {
name: 'trackId',
},
constraints: false,
});
db.analytics_daily.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.analytics_daily.belongsTo(db.users, {
as: 'createdBy',
});
db.analytics_daily.belongsTo(db.users, {
as: 'updatedBy',
});
};
return analytics_daily;
};

View File

@ -0,0 +1,173 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const api_keys = sequelize.define(
'api_keys',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
key_prefix: {
type: DataTypes.TEXT,
},
key_hash: {
type: DataTypes.TEXT,
},
scopes: {
type: DataTypes.TEXT,
},
last_used_at: {
type: DataTypes.DATE,
},
expires_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"revoked"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
api_keys.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.api_keys.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.api_keys.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.api_keys.belongsTo(db.users, {
as: 'createdBy',
});
db.api_keys.belongsTo(db.users, {
as: 'updatedBy',
});
};
return api_keys;
};

View File

@ -0,0 +1,260 @@
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 artist_profiles = sequelize.define(
'artist_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
artist_name: {
type: DataTypes.TEXT,
},
profile_type: {
type: DataTypes.ENUM,
values: [
"solo_artist",
"group",
"label"
],
},
legal_name: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
tax_residency: {
type: DataTypes.TEXT,
},
payout_currency: {
type: DataTypes.TEXT,
},
bio: {
type: DataTypes.TEXT,
},
website_url: {
type: DataTypes.TEXT,
},
vk_url: {
type: DataTypes.TEXT,
},
youtube_url: {
type: DataTypes.TEXT,
},
tiktok_url: {
type: DataTypes.TEXT,
},
instagram_url: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
artist_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.artist_profiles.hasMany(db.releases, {
as: 'releases_artist_profile',
foreignKey: {
name: 'artist_profileId',
},
constraints: false,
});
db.artist_profiles.hasMany(db.pitch_requests, {
as: 'pitch_requests_artist_profile',
foreignKey: {
name: 'artist_profileId',
},
constraints: false,
});
db.artist_profiles.hasMany(db.royalty_reports, {
as: 'royalty_reports_artist_profile',
foreignKey: {
name: 'artist_profileId',
},
constraints: false,
});
db.artist_profiles.hasMany(db.analytics_daily, {
as: 'analytics_daily_artist_profile',
foreignKey: {
name: 'artist_profileId',
},
constraints: false,
});
//end loop
db.artist_profiles.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.artist_profiles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.artist_profiles.hasMany(db.file, {
as: 'press_photos',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.artist_profiles.getTableName(),
belongsToColumn: 'press_photos',
},
});
db.artist_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.artist_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return artist_profiles;
};

View File

@ -0,0 +1,201 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const blog_posts = sequelize.define(
'blog_posts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
category: {
type: DataTypes.ENUM,
values: [
"platform_updates",
"industry_news",
"guides",
"success_stories",
"webinars"
],
},
excerpt: {
type: DataTypes.TEXT,
},
content: {
type: DataTypes.TEXT,
},
is_published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
published_at: {
type: DataTypes.DATE,
},
seo_title: {
type: DataTypes.TEXT,
},
seo_description: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
blog_posts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.blog_posts.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.blog_posts.hasMany(db.file, {
as: 'cover_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'cover_image',
},
});
db.blog_posts.belongsTo(db.users, {
as: 'createdBy',
});
db.blog_posts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return blog_posts;
};

View File

@ -0,0 +1,164 @@
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 contact_messages = sequelize.define(
'contact_messages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
subject: {
type: DataTypes.TEXT,
},
message: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"new",
"in_progress",
"resolved",
"spam"
],
},
submitted_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
contact_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.contact_messages.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.contact_messages.belongsTo(db.users, {
as: 'createdBy',
});
db.contact_messages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return contact_messages;
};

View File

@ -0,0 +1,170 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const dashboard_widgets = sequelize.define(
'dashboard_widgets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
widget_type: {
type: DataTypes.ENUM,
values: [
"kpi_cards",
"streams_chart",
"revenue_by_platform",
"listener_geography",
"quick_actions",
"activity_feed",
"latest_releases"
],
},
sort_order: {
type: DataTypes.INTEGER,
},
is_visible: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
settings_json: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
dashboard_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.dashboard_widgets.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.dashboard_widgets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.dashboard_widgets.belongsTo(db.users, {
as: 'createdBy',
});
db.dashboard_widgets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return dashboard_widgets;
};

View File

@ -0,0 +1,208 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const distribution_platforms = sequelize.define(
'distribution_platforms',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
category: {
type: DataTypes.ENUM,
values: [
"streaming",
"social",
"other"
],
},
website_url: {
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,
},
);
distribution_platforms.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.distribution_platforms.hasMany(db.release_deliveries, {
as: 'release_deliveries_platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.distribution_platforms.hasMany(db.smart_link_destinations, {
as: 'smart_link_destinations_platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.distribution_platforms.hasMany(db.smart_link_clicks, {
as: 'smart_link_clicks_platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.distribution_platforms.hasMany(db.playlists, {
as: 'playlists_platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.distribution_platforms.hasMany(db.royalty_reports, {
as: 'royalty_reports_platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.distribution_platforms.hasMany(db.analytics_daily, {
as: 'analytics_daily_platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
//end loop
db.distribution_platforms.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.distribution_platforms.hasMany(db.file, {
as: 'logo',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.distribution_platforms.getTableName(),
belongsToColumn: 'logo',
},
});
db.distribution_platforms.belongsTo(db.users, {
as: 'createdBy',
});
db.distribution_platforms.belongsTo(db.users, {
as: 'updatedBy',
});
};
return distribution_platforms;
};

View File

@ -0,0 +1,166 @@
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 faq_items = sequelize.define(
'faq_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
category: {
type: DataTypes.ENUM,
values: [
"general",
"uploading",
"payouts",
"platforms",
"technical",
"copyright"
],
},
question: {
type: DataTypes.TEXT,
},
answer: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
faq_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.faq_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.faq_items.belongsTo(db.users, {
as: 'createdBy',
});
db.faq_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return faq_items;
};

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,156 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const genres = sequelize.define(
'genres',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
genres.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.genres.hasMany(db.releases, {
as: 'releases_primary_genre',
foreignKey: {
name: 'primary_genreId',
},
constraints: false,
});
db.genres.hasMany(db.releases, {
as: 'releases_secondary_genre',
foreignKey: {
name: 'secondary_genreId',
},
constraints: false,
});
db.genres.hasMany(db.tracks, {
as: 'tracks_genre',
foreignKey: {
name: 'genreId',
},
constraints: false,
});
//end loop
db.genres.belongsTo(db.genres, {
as: 'parent_genre',
foreignKey: {
name: 'parent_genreId',
},
constraints: false,
});
db.genres.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.genres.belongsTo(db.users, {
as: 'createdBy',
});
db.genres.belongsTo(db.users, {
as: 'updatedBy',
});
};
return genres;
};

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,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 notification_preferences = sequelize.define(
'notification_preferences',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
email_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
push_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
telegram_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
sms_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
in_app_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
release_updates_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
finance_updates_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
playlist_updates_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
marketing_updates_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
quiet_hours: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notification_preferences.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.notification_preferences.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.notification_preferences.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.notification_preferences.belongsTo(db.users, {
as: 'createdBy',
});
db.notification_preferences.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notification_preferences;
};

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 notifications = sequelize.define(
'notifications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
channel: {
type: DataTypes.ENUM,
values: [
"email",
"push",
"telegram",
"sms",
"in_app"
],
},
event_type: {
type: DataTypes.ENUM,
values: [
"release_published",
"royalty_accrual",
"playlist_added",
"moderation_status_changed",
"withdrawal_processed",
"system_announcement",
"security_new_login"
],
},
title: {
type: DataTypes.TEXT,
},
message: {
type: DataTypes.TEXT,
},
scheduled_at: {
type: DataTypes.DATE,
},
sent_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"sent",
"failed",
"canceled"
],
},
provider_reference: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notifications.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.notifications.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.notifications.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.notifications.belongsTo(db.users, {
as: 'createdBy',
});
db.notifications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notifications;
};

View File

@ -0,0 +1,165 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const oauth_accounts = sequelize.define(
'oauth_accounts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
provider: {
type: DataTypes.ENUM,
values: [
"vk",
"yandex",
"google",
"apple"
],
},
provider_user_key: {
type: DataTypes.TEXT,
},
access_token: {
type: DataTypes.TEXT,
},
refresh_token: {
type: DataTypes.TEXT,
},
token_expires_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
oauth_accounts.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.oauth_accounts.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.oauth_accounts.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.oauth_accounts.belongsTo(db.users, {
as: 'createdBy',
});
db.oauth_accounts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return oauth_accounts;
};

View File

@ -0,0 +1,410 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const organizations = sequelize.define(
'organizations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
organizations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.organizations.hasMany(db.users, {
as: 'users_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.oauth_accounts, {
as: 'oauth_accounts_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.artist_profiles, {
as: 'artist_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.teams, {
as: 'teams_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.team_memberships, {
as: 'team_memberships_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.plans, {
as: 'plans_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.subscriptions, {
as: 'subscriptions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.distribution_platforms, {
as: 'distribution_platforms_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.genres, {
as: 'genres_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.releases, {
as: 'releases_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.tracks, {
as: 'tracks_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.track_contributors, {
as: 'track_contributors_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.release_deliveries, {
as: 'release_deliveries_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.smart_links, {
as: 'smart_links_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.smart_link_destinations, {
as: 'smart_link_destinations_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.smart_link_clicks, {
as: 'smart_link_clicks_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.playlists, {
as: 'playlists_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.pitch_requests, {
as: 'pitch_requests_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.playlist_placements, {
as: 'playlist_placements_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.royalty_reports, {
as: 'royalty_reports_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.royalty_lines, {
as: 'royalty_lines_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.wallets, {
as: 'wallets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.wallet_transactions, {
as: 'wallet_transactions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.payout_methods, {
as: 'payout_methods_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.withdrawal_requests, {
as: 'withdrawal_requests_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.tax_documents, {
as: 'tax_documents_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.analytics_daily, {
as: 'analytics_daily_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.notifications, {
as: 'notifications_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.notification_preferences, {
as: 'notification_preferences_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.api_keys, {
as: 'api_keys_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.dashboard_widgets, {
as: 'dashboard_widgets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.activity_events, {
as: 'activity_events_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.blog_posts, {
as: 'blog_posts_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.faq_items, {
as: 'faq_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.contact_messages, {
as: 'contact_messages_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.referral_programs, {
as: 'referral_programs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.referral_links, {
as: 'referral_links_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.referral_conversions, {
as: 'referral_conversions_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,211 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const payout_methods = sequelize.define(
'payout_methods',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
method_type: {
type: DataTypes.ENUM,
values: [
"bank_card",
"bank_transfer",
"paypal",
"webmoney",
"yookassa",
"robokassa",
"crypto"
],
},
method_label: {
type: DataTypes.TEXT,
},
account_identifier: {
type: DataTypes.TEXT,
},
holder_name: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
is_default: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"disabled",
"needs_verification"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payout_methods.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.payout_methods.hasMany(db.withdrawal_requests, {
as: 'withdrawal_requests_payout_method',
foreignKey: {
name: 'payout_methodId',
},
constraints: false,
});
//end loop
db.payout_methods.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.payout_methods.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.payout_methods.belongsTo(db.users, {
as: 'createdBy',
});
db.payout_methods.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payout_methods;
};

View File

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

View File

@ -0,0 +1,222 @@
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 pitch_requests = sequelize.define(
'pitch_requests',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
pitch_title: {
type: DataTypes.TEXT,
},
pitch_text: {
type: DataTypes.TEXT,
},
mood: {
type: DataTypes.TEXT,
},
similar_artists: {
type: DataTypes.TEXT,
},
achievements: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"sent",
"under_review",
"accepted",
"rejected"
],
},
submitted_at: {
type: DataTypes.DATE,
},
decided_at: {
type: DataTypes.DATE,
},
decision_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
pitch_requests.associate = (db) => {
db.pitch_requests.belongsToMany(db.playlists, {
as: 'target_playlists',
foreignKey: {
name: 'pitch_requests_target_playlistsId',
},
constraints: false,
through: 'pitch_requestsTarget_playlistsPlaylists',
});
db.pitch_requests.belongsToMany(db.playlists, {
as: 'target_playlists_filter',
foreignKey: {
name: 'pitch_requests_target_playlistsId',
},
constraints: false,
through: 'pitch_requestsTarget_playlistsPlaylists',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.pitch_requests.belongsTo(db.tracks, {
as: 'track',
foreignKey: {
name: 'trackId',
},
constraints: false,
});
db.pitch_requests.belongsTo(db.artist_profiles, {
as: 'artist_profile',
foreignKey: {
name: 'artist_profileId',
},
constraints: false,
});
db.pitch_requests.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.pitch_requests.belongsTo(db.users, {
as: 'createdBy',
});
db.pitch_requests.belongsTo(db.users, {
as: 'updatedBy',
});
};
return pitch_requests;
};

View File

@ -0,0 +1,179 @@
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 plans = sequelize.define(
'plans',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
plan_code: {
type: DataTypes.ENUM,
values: [
"basic",
"pro",
"label"
],
},
price_amount: {
type: DataTypes.DECIMAL,
},
price_currency: {
type: DataTypes.TEXT,
},
billing_period: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
features: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
plans.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.plans.hasMany(db.subscriptions, {
as: 'subscriptions_plan',
foreignKey: {
name: 'planId',
},
constraints: false,
});
//end loop
db.plans.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.plans.belongsTo(db.users, {
as: 'createdBy',
});
db.plans.belongsTo(db.users, {
as: 'updatedBy',
});
};
return plans;
};

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 playlist_placements = sequelize.define(
'playlist_placements',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
placed_at: {
type: DataTypes.DATE,
},
removed_at: {
type: DataTypes.DATE,
},
position: {
type: DataTypes.INTEGER,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
playlist_placements.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_placements.belongsTo(db.tracks, {
as: 'track',
foreignKey: {
name: 'trackId',
},
constraints: false,
});
db.playlist_placements.belongsTo(db.playlists, {
as: 'playlist',
foreignKey: {
name: 'playlistId',
},
constraints: false,
});
db.playlist_placements.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.playlist_placements.belongsTo(db.users, {
as: 'createdBy',
});
db.playlist_placements.belongsTo(db.users, {
as: 'updatedBy',
});
};
return playlist_placements;
};

View File

@ -0,0 +1,187 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const playlists = sequelize.define(
'playlists',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
playlist_type: {
type: DataTypes.ENUM,
values: [
"editorial",
"partner_curator",
"user"
],
},
curator_name: {
type: DataTypes.TEXT,
},
playlist_url: {
type: DataTypes.TEXT,
},
genre_focus: {
type: DataTypes.TEXT,
},
mood_tags: {
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,
},
);
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_placements, {
as: 'playlist_placements_playlist',
foreignKey: {
name: 'playlistId',
},
constraints: false,
});
//end loop
db.playlists.belongsTo(db.distribution_platforms, {
as: 'platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.playlists.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.playlists.belongsTo(db.users, {
as: 'createdBy',
});
db.playlists.belongsTo(db.users, {
as: 'updatedBy',
});
};
return playlists;
};

View File

@ -0,0 +1,163 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const referral_conversions = sequelize.define(
'referral_conversions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
converted_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"qualified",
"disqualified"
],
},
commission_amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
referral_conversions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.referral_conversions.belongsTo(db.referral_links, {
as: 'referral_link',
foreignKey: {
name: 'referral_linkId',
},
constraints: false,
});
db.referral_conversions.belongsTo(db.users, {
as: 'referred_user',
foreignKey: {
name: 'referred_userId',
},
constraints: false,
});
db.referral_conversions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.referral_conversions.belongsTo(db.users, {
as: 'createdBy',
});
db.referral_conversions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return referral_conversions;
};

View File

@ -0,0 +1,162 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const referral_links = sequelize.define(
'referral_links',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
landing_url: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
created_on: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
referral_links.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.referral_links.hasMany(db.referral_conversions, {
as: 'referral_conversions_referral_link',
foreignKey: {
name: 'referral_linkId',
},
constraints: false,
});
//end loop
db.referral_links.belongsTo(db.users, {
as: 'referrer_user',
foreignKey: {
name: 'referrer_userId',
},
constraints: false,
});
db.referral_links.belongsTo(db.referral_programs, {
as: 'program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
db.referral_links.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.referral_links.belongsTo(db.users, {
as: 'createdBy',
});
db.referral_links.belongsTo(db.users, {
as: 'updatedBy',
});
};
return referral_links;
};

View File

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

View File

@ -0,0 +1,199 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const release_deliveries = sequelize.define(
'release_deliveries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
delivery_status: {
type: DataTypes.ENUM,
values: [
"not_sent",
"queued",
"sent",
"processing",
"delivered",
"failed",
"takedown_sent",
"takedown_completed"
],
},
requested_at: {
type: DataTypes.DATE,
},
sent_at: {
type: DataTypes.DATE,
},
delivered_at: {
type: DataTypes.DATE,
},
platform_release_url: {
type: DataTypes.TEXT,
},
external_reference: {
type: DataTypes.TEXT,
},
error_message: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
release_deliveries.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.release_deliveries.belongsTo(db.releases, {
as: 'release',
foreignKey: {
name: 'releaseId',
},
constraints: false,
});
db.release_deliveries.belongsTo(db.distribution_platforms, {
as: 'platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.release_deliveries.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.release_deliveries.belongsTo(db.users, {
as: 'createdBy',
});
db.release_deliveries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return release_deliveries;
};

View File

@ -0,0 +1,397 @@
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 releases = sequelize.define(
'releases',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
release_type: {
type: DataTypes.ENUM,
values: [
"single",
"ep",
"album",
"compilation",
"podcast"
],
},
language: {
type: DataTypes.TEXT,
},
label_name: {
type: DataTypes.TEXT,
},
copyright_notice: {
type: DataTypes.TEXT,
},
production_notice: {
type: DataTypes.TEXT,
},
upc_code: {
type: DataTypes.TEXT,
},
upc_source: {
type: DataTypes.ENUM,
values: [
"auto",
"manual"
],
},
release_date: {
type: DataTypes.DATE,
},
original_release_date: {
type: DataTypes.DATE,
},
moderation_status: {
type: DataTypes.ENUM,
values: [
"draft",
"submitted",
"in_review",
"changes_requested",
"approved",
"published",
"rejected",
"takedown_requested",
"takedown_completed"
],
},
moderation_notes: {
type: DataTypes.TEXT,
},
explicit_content: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
license_accepted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
content_id_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
content_match_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
internal_catalog_code: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
releases.associate = (db) => {
db.releases.belongsToMany(db.distribution_platforms, {
as: 'selected_platforms',
foreignKey: {
name: 'releases_selected_platformsId',
},
constraints: false,
through: 'releasesSelected_platformsDistribution_platforms',
});
db.releases.belongsToMany(db.distribution_platforms, {
as: 'selected_platforms_filter',
foreignKey: {
name: 'releases_selected_platformsId',
},
constraints: false,
through: 'releasesSelected_platformsDistribution_platforms',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.releases.hasMany(db.tracks, {
as: 'tracks_release',
foreignKey: {
name: 'releaseId',
},
constraints: false,
});
db.releases.hasMany(db.release_deliveries, {
as: 'release_deliveries_release',
foreignKey: {
name: 'releaseId',
},
constraints: false,
});
db.releases.hasMany(db.smart_links, {
as: 'smart_links_release',
foreignKey: {
name: 'releaseId',
},
constraints: false,
});
db.releases.hasMany(db.royalty_lines, {
as: 'royalty_lines_release',
foreignKey: {
name: 'releaseId',
},
constraints: false,
});
db.releases.hasMany(db.analytics_daily, {
as: 'analytics_daily_release',
foreignKey: {
name: 'releaseId',
},
constraints: false,
});
//end loop
db.releases.belongsTo(db.artist_profiles, {
as: 'artist_profile',
foreignKey: {
name: 'artist_profileId',
},
constraints: false,
});
db.releases.belongsTo(db.genres, {
as: 'primary_genre',
foreignKey: {
name: 'primary_genreId',
},
constraints: false,
});
db.releases.belongsTo(db.genres, {
as: 'secondary_genre',
foreignKey: {
name: 'secondary_genreId',
},
constraints: false,
});
db.releases.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.releases.hasMany(db.file, {
as: 'cover_art',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.releases.getTableName(),
belongsToColumn: 'cover_art',
},
});
db.releases.hasMany(db.file, {
as: 'booklet_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.releases.getTableName(),
belongsToColumn: 'booklet_files',
},
});
db.releases.belongsTo(db.users, {
as: 'createdBy',
});
db.releases.belongsTo(db.users, {
as: 'updatedBy',
});
};
return releases;
};

View File

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

View File

@ -0,0 +1,215 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const royalty_lines = sequelize.define(
'royalty_lines',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
territory: {
type: DataTypes.TEXT,
},
store_name: {
type: DataTypes.TEXT,
},
quantity: {
type: DataTypes.INTEGER,
},
unit_rate: {
type: DataTypes.DECIMAL,
},
gross_amount: {
type: DataTypes.DECIMAL,
},
net_amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
event_at: {
type: DataTypes.DATE,
},
usage_type: {
type: DataTypes.ENUM,
values: [
"stream",
"download",
"video",
"ugc",
"content_id",
"other"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
royalty_lines.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.royalty_lines.belongsTo(db.royalty_reports, {
as: 'royalty_report',
foreignKey: {
name: 'royalty_reportId',
},
constraints: false,
});
db.royalty_lines.belongsTo(db.releases, {
as: 'release',
foreignKey: {
name: 'releaseId',
},
constraints: false,
});
db.royalty_lines.belongsTo(db.tracks, {
as: 'track',
foreignKey: {
name: 'trackId',
},
constraints: false,
});
db.royalty_lines.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.royalty_lines.belongsTo(db.users, {
as: 'createdBy',
});
db.royalty_lines.belongsTo(db.users, {
as: 'updatedBy',
});
};
return royalty_lines;
};

View File

@ -0,0 +1,213 @@
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 royalty_reports = sequelize.define(
'royalty_reports',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
period_start_at: {
type: DataTypes.DATE,
},
period_end_at: {
type: DataTypes.DATE,
},
source_type: {
type: DataTypes.ENUM,
values: [
"api",
"csv",
"xml",
"manual"
],
},
source_reference: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"imported",
"processing",
"completed",
"failed"
],
},
error_details: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
royalty_reports.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.royalty_reports.hasMany(db.royalty_lines, {
as: 'royalty_lines_royalty_report',
foreignKey: {
name: 'royalty_reportId',
},
constraints: false,
});
//end loop
db.royalty_reports.belongsTo(db.artist_profiles, {
as: 'artist_profile',
foreignKey: {
name: 'artist_profileId',
},
constraints: false,
});
db.royalty_reports.belongsTo(db.distribution_platforms, {
as: 'platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.royalty_reports.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.royalty_reports.hasMany(db.file, {
as: 'source_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.royalty_reports.getTableName(),
belongsToColumn: 'source_file',
},
});
db.royalty_reports.belongsTo(db.users, {
as: 'createdBy',
});
db.royalty_reports.belongsTo(db.users, {
as: 'updatedBy',
});
};
return royalty_reports;
};

View File

@ -0,0 +1,165 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const smart_link_clicks = sequelize.define(
'smart_link_clicks',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
clicked_at: {
type: DataTypes.DATE,
},
country: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
referrer: {
type: DataTypes.TEXT,
},
utm_source: {
type: DataTypes.TEXT,
},
utm_campaign: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
smart_link_clicks.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.smart_link_clicks.belongsTo(db.smart_links, {
as: 'smart_link',
foreignKey: {
name: 'smart_linkId',
},
constraints: false,
});
db.smart_link_clicks.belongsTo(db.distribution_platforms, {
as: 'platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.smart_link_clicks.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.smart_link_clicks.belongsTo(db.users, {
as: 'createdBy',
});
db.smart_link_clicks.belongsTo(db.users, {
as: 'updatedBy',
});
};
return smart_link_clicks;
};

View File

@ -0,0 +1,147 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const smart_link_destinations = sequelize.define(
'smart_link_destinations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
destination_url: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_primary: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
smart_link_destinations.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.smart_link_destinations.belongsTo(db.smart_links, {
as: 'smart_link',
foreignKey: {
name: 'smart_linkId',
},
constraints: false,
});
db.smart_link_destinations.belongsTo(db.distribution_platforms, {
as: 'platform',
foreignKey: {
name: 'platformId',
},
constraints: false,
});
db.smart_link_destinations.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.smart_link_destinations.belongsTo(db.users, {
as: 'createdBy',
});
db.smart_link_destinations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return smart_link_destinations;
};

View File

@ -0,0 +1,196 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const smart_links = sequelize.define(
'smart_links',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
slug: {
type: DataTypes.TEXT,
},
page_title: {
type: DataTypes.TEXT,
},
custom_text: {
type: DataTypes.TEXT,
},
theme_color: {
type: DataTypes.TEXT,
},
is_public: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
published_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
smart_links.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.smart_links.hasMany(db.smart_link_destinations, {
as: 'smart_link_destinations_smart_link',
foreignKey: {
name: 'smart_linkId',
},
constraints: false,
});
db.smart_links.hasMany(db.smart_link_clicks, {
as: 'smart_link_clicks_smart_link',
foreignKey: {
name: 'smart_linkId',
},
constraints: false,
});
//end loop
db.smart_links.belongsTo(db.releases, {
as: 'release',
foreignKey: {
name: 'releaseId',
},
constraints: false,
});
db.smart_links.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.smart_links.hasMany(db.file, {
as: 'background_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.smart_links.getTableName(),
belongsToColumn: 'background_image',
},
});
db.smart_links.hasMany(db.file, {
as: 'artist_photo',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.smart_links.getTableName(),
belongsToColumn: 'artist_photo',
},
});
db.smart_links.belongsTo(db.users, {
as: 'createdBy',
});
db.smart_links.belongsTo(db.users, {
as: 'updatedBy',
});
};
return smart_links;
};

View File

@ -0,0 +1,179 @@
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 subscriptions = sequelize.define(
'subscriptions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"trialing",
"active",
"past_due",
"canceled",
"expired"
],
},
starts_at: {
type: DataTypes.DATE,
},
ends_at: {
type: DataTypes.DATE,
},
auto_renew: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
external_billing_key: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
subscriptions.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.subscriptions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.subscriptions.belongsTo(db.plans, {
as: 'plan',
foreignKey: {
name: 'planId',
},
constraints: false,
});
db.subscriptions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.subscriptions.belongsTo(db.users, {
as: 'createdBy',
});
db.subscriptions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return subscriptions;
};

View File

@ -0,0 +1,196 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const tax_documents = sequelize.define(
'tax_documents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
document_type: {
type: DataTypes.ENUM,
values: [
"w8ben",
"ndfl_2",
"invoice",
"vat_statement",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"submitted",
"approved",
"rejected",
"expired"
],
},
issued_at: {
type: DataTypes.DATE,
},
expires_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tax_documents.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.tax_documents.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.tax_documents.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.tax_documents.hasMany(db.file, {
as: 'document_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.tax_documents.getTableName(),
belongsToColumn: 'document_file',
},
});
db.tax_documents.belongsTo(db.users, {
as: 'createdBy',
});
db.tax_documents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tax_documents;
};

View File

@ -0,0 +1,181 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const team_memberships = sequelize.define(
'team_memberships',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
role: {
type: DataTypes.ENUM,
values: [
"owner",
"admin",
"editor",
"viewer",
"finance_manager"
],
},
status: {
type: DataTypes.ENUM,
values: [
"invited",
"active",
"revoked"
],
},
invited_at: {
type: DataTypes.DATE,
},
accepted_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
team_memberships.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.team_memberships.belongsTo(db.teams, {
as: 'team',
foreignKey: {
name: 'teamId',
},
constraints: false,
});
db.team_memberships.belongsTo(db.users, {
as: 'member_user',
foreignKey: {
name: 'member_userId',
},
constraints: false,
});
db.team_memberships.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.team_memberships.belongsTo(db.users, {
as: 'createdBy',
});
db.team_memberships.belongsTo(db.users, {
as: 'updatedBy',
});
};
return team_memberships;
};

View File

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

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