Initial version

This commit is contained in:
Flatlogic Bot 2026-04-12 17:17:18 +00:00
commit fe111dfa46
616 changed files with 207207 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>SA AI Music Studio</h2>
<p>AI-powered SA-focused music studio for generating beats, processing vocals, mixing, mastering, and exporting songs.</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 @@
# SA AI Music Studio
## 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_39594
DB_USER=app_39594
DB_PASS=bf5dcaa7-2335-4163-ae45-2e0f433f5b5a
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 @@
#SA AI Music Studio - 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_sa_ai_music_studio;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_sa_ai_music_studio 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": "saaimusicstudio",
"description": "SA AI Music Studio - 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: "bf5dcaa7",
user_pass: "2e0f433f5b5a",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'bf5dcaa7-2335-4163-ae45-2e0f433f5b5a',
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: 'SA AI Music Studio <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: 'Marketplace Buyer',
},
project_uuid: 'bf5dcaa7-2335-4163-ae45-2e0f433f5b5a',
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 = 'Abstract sound waves at night';
config.host = process.env.NODE_ENV === "production" ? config.remote : "http://localhost";
config.apiUrl = `${config.host}${config.port ? `:${config.port}` : ``}/api`;
config.swaggerUrl = `${config.swaggerUI}${config.swaggerPort}`;
config.uiUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}/#`;
config.backUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}`;
module.exports = config;

View File

@ -0,0 +1,500 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Ai_modelsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_models = await db.ai_models.create(
{
id: data.id || undefined,
name: data.name
||
null
,
model_type: data.model_type
||
null
,
provider: data.provider
||
null
,
version: data.version
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_models.setOrganizations( data.organizations || null, {
transaction,
});
return ai_models;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const ai_modelsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
model_type: item.model_type
||
null
,
provider: item.provider
||
null
,
version: item.version
||
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 ai_models = await db.ai_models.bulkCreate(ai_modelsData, { transaction });
// For each item created, replace relation files
return ai_models;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const ai_models = await db.ai_models.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.model_type !== undefined) updatePayload.model_type = data.model_type;
if (data.provider !== undefined) updatePayload.provider = data.provider;
if (data.version !== undefined) updatePayload.version = data.version;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await ai_models.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await ai_models.setOrganizations(
data.organizations,
{ transaction }
);
}
return ai_models;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_models = await db.ai_models.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ai_models) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ai_models) {
await record.destroy({transaction});
}
});
return ai_models;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_models = await db.ai_models.findByPk(id, options);
await ai_models.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ai_models.destroy({
transaction
});
return ai_models;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ai_models = await db.ai_models.findOne(
{ where },
{ transaction },
);
if (!ai_models) {
return ai_models;
}
const output = ai_models.get({plain: true});
output.generation_requests_model = await ai_models.getGeneration_requests_model({
transaction
});
output.organizations = await ai_models.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(
'ai_models',
'name',
filter.name,
),
};
}
if (filter.provider) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_models',
'provider',
filter.provider,
),
};
}
if (filter.version) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_models',
'version',
filter.version,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.model_type) {
where = {
...where,
model_type: filter.model_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.ai_models.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'ai_models',
'name',
query,
),
],
};
}
const records = await db.ai_models.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,574 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Arrangement_sectionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const arrangement_sections = await db.arrangement_sections.create(
{
id: data.id || undefined,
section_type: data.section_type
||
null
,
label: data.label
||
null
,
start_bar: data.start_bar
||
null
,
bar_length: data.bar_length
||
null
,
order_index: data.order_index
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await arrangement_sections.setSong( data.song || null, {
transaction,
});
await arrangement_sections.setOrganizations( data.organizations || null, {
transaction,
});
return arrangement_sections;
}
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 arrangement_sectionsData = data.map((item, index) => ({
id: item.id || undefined,
section_type: item.section_type
||
null
,
label: item.label
||
null
,
start_bar: item.start_bar
||
null
,
bar_length: item.bar_length
||
null
,
order_index: item.order_index
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const arrangement_sections = await db.arrangement_sections.bulkCreate(arrangement_sectionsData, { transaction });
// For each item created, replace relation files
return arrangement_sections;
}
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 arrangement_sections = await db.arrangement_sections.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.section_type !== undefined) updatePayload.section_type = data.section_type;
if (data.label !== undefined) updatePayload.label = data.label;
if (data.start_bar !== undefined) updatePayload.start_bar = data.start_bar;
if (data.bar_length !== undefined) updatePayload.bar_length = data.bar_length;
if (data.order_index !== undefined) updatePayload.order_index = data.order_index;
updatePayload.updatedById = currentUser.id;
await arrangement_sections.update(updatePayload, {transaction});
if (data.song !== undefined) {
await arrangement_sections.setSong(
data.song,
{ transaction }
);
}
if (data.organizations !== undefined) {
await arrangement_sections.setOrganizations(
data.organizations,
{ transaction }
);
}
return arrangement_sections;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const arrangement_sections = await db.arrangement_sections.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of arrangement_sections) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of arrangement_sections) {
await record.destroy({transaction});
}
});
return arrangement_sections;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const arrangement_sections = await db.arrangement_sections.findByPk(id, options);
await arrangement_sections.update({
deletedBy: currentUser.id
}, {
transaction,
});
await arrangement_sections.destroy({
transaction
});
return arrangement_sections;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const arrangement_sections = await db.arrangement_sections.findOne(
{ where },
{ transaction },
);
if (!arrangement_sections) {
return arrangement_sections;
}
const output = arrangement_sections.get({plain: true});
output.song = await arrangement_sections.getSong({
transaction
});
output.organizations = await arrangement_sections.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.songs,
as: 'song',
where: filter.song ? {
[Op.or]: [
{ id: { [Op.in]: filter.song.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.song.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.label) {
where = {
...where,
[Op.and]: Utils.ilike(
'arrangement_sections',
'label',
filter.label,
),
};
}
if (filter.start_barRange) {
const [start, end] = filter.start_barRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_bar: {
...where.start_bar,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_bar: {
...where.start_bar,
[Op.lte]: end,
},
};
}
}
if (filter.bar_lengthRange) {
const [start, end] = filter.bar_lengthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bar_length: {
...where.bar_length,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bar_length: {
...where.bar_length,
[Op.lte]: end,
},
};
}
}
if (filter.order_indexRange) {
const [start, end] = filter.order_indexRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
order_index: {
...where.order_index,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
order_index: {
...where.order_index,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.section_type) {
where = {
...where,
section_type: filter.section_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.arrangement_sections.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(
'arrangement_sections',
'label',
query,
),
],
};
}
const records = await db.arrangement_sections.findAll({
attributes: [ 'id', 'label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.label,
}));
}
};

View File

@ -0,0 +1,847 @@
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 AssetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assets = await db.assets.create(
{
id: data.id || undefined,
asset_type: data.asset_type
||
null
,
audio_role: data.audio_role
||
null
,
name: data.name
||
null
,
duration_seconds: data.duration_seconds
||
null
,
sample_rate_hz: data.sample_rate_hz
||
null
,
bit_depth: data.bit_depth
||
null
,
is_stereo: data.is_stereo
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await assets.setWorkspace( data.workspace || null, {
transaction,
});
await assets.setUploaded_user( data.uploaded_user || null, {
transaction,
});
await assets.setProject( data.project || null, {
transaction,
});
await assets.setSong( data.song || null, {
transaction,
});
await assets.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'file_blobs',
belongsToId: assets.id,
},
data.file_blobs,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'image_blobs',
belongsToId: assets.id,
},
data.image_blobs,
options,
);
return assets;
}
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 assetsData = data.map((item, index) => ({
id: item.id || undefined,
asset_type: item.asset_type
||
null
,
audio_role: item.audio_role
||
null
,
name: item.name
||
null
,
duration_seconds: item.duration_seconds
||
null
,
sample_rate_hz: item.sample_rate_hz
||
null
,
bit_depth: item.bit_depth
||
null
,
is_stereo: item.is_stereo
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const assets = await db.assets.bulkCreate(assetsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < assets.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'file_blobs',
belongsToId: assets[i].id,
},
data[i].file_blobs,
options,
);
}
for (let i = 0; i < assets.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'image_blobs',
belongsToId: assets[i].id,
},
data[i].image_blobs,
options,
);
}
return assets;
}
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 assets = await db.assets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.asset_type !== undefined) updatePayload.asset_type = data.asset_type;
if (data.audio_role !== undefined) updatePayload.audio_role = data.audio_role;
if (data.name !== undefined) updatePayload.name = data.name;
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.bit_depth !== undefined) updatePayload.bit_depth = data.bit_depth;
if (data.is_stereo !== undefined) updatePayload.is_stereo = data.is_stereo;
updatePayload.updatedById = currentUser.id;
await assets.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await assets.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.uploaded_user !== undefined) {
await assets.setUploaded_user(
data.uploaded_user,
{ transaction }
);
}
if (data.project !== undefined) {
await assets.setProject(
data.project,
{ transaction }
);
}
if (data.song !== undefined) {
await assets.setSong(
data.song,
{ transaction }
);
}
if (data.organizations !== undefined) {
await assets.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'file_blobs',
belongsToId: assets.id,
},
data.file_blobs,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'image_blobs',
belongsToId: assets.id,
},
data.image_blobs,
options,
);
return assets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assets = await db.assets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of assets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of assets) {
await record.destroy({transaction});
}
});
return assets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const assets = await db.assets.findByPk(id, options);
await assets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await assets.destroy({
transaction
});
return assets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const assets = await db.assets.findOne(
{ where },
{ transaction },
);
if (!assets) {
return assets;
}
const output = assets.get({plain: true});
output.tracks_source_asset = await assets.getTracks_source_asset({
transaction
});
output.generation_requests_input_asset = await assets.getGeneration_requests_input_asset({
transaction
});
output.generation_requests_output_asset = await assets.getGeneration_requests_output_asset({
transaction
});
output.mix_sessions_result_mix_asset = await assets.getMix_sessions_result_mix_asset({
transaction
});
output.mastering_sessions_input_mix_asset = await assets.getMastering_sessions_input_mix_asset({
transaction
});
output.mastering_sessions_result_master_asset = await assets.getMastering_sessions_result_master_asset({
transaction
});
output.exports_export_asset = await assets.getExports_export_asset({
transaction
});
output.marketplace_listings_preview_asset = await assets.getMarketplace_listings_preview_asset({
transaction
});
output.marketplace_listings_deliverable_asset = await assets.getMarketplace_listings_deliverable_asset({
transaction
});
output.workspace = await assets.getWorkspace({
transaction
});
output.uploaded_user = await assets.getUploaded_user({
transaction
});
output.project = await assets.getProject({
transaction
});
output.song = await assets.getSong({
transaction
});
output.file_blobs = await assets.getFile_blobs({
transaction
});
output.image_blobs = await assets.getImage_blobs({
transaction
});
output.organizations = await assets.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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'uploaded_user',
where: filter.uploaded_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.uploaded_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.uploaded_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.projects,
as: 'project',
where: filter.project ? {
[Op.or]: [
{ id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.songs,
as: 'song',
where: filter.song ? {
[Op.or]: [
{ id: { [Op.in]: filter.song.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.song.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'file_blobs',
},
{
model: db.file,
as: 'image_blobs',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'assets',
'name',
filter.name,
),
};
}
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.bit_depthRange) {
const [start, end] = filter.bit_depthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bit_depth: {
...where.bit_depth,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bit_depth: {
...where.bit_depth,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.asset_type) {
where = {
...where,
asset_type: filter.asset_type,
};
}
if (filter.audio_role) {
where = {
...where,
audio_role: filter.audio_role,
};
}
if (filter.is_stereo) {
where = {
...where,
is_stereo: filter.is_stereo,
};
}
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.assets.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(
'assets',
'name',
query,
),
],
};
}
const records = await db.assets.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,505 @@
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 Cover_artworksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cover_artworks = await db.cover_artworks.create(
{
id: data.id || undefined,
prompt: data.prompt
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await cover_artworks.setSong( data.song || null, {
transaction,
});
await cover_artworks.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.cover_artworks.getTableName(),
belongsToColumn: 'art_images',
belongsToId: cover_artworks.id,
},
data.art_images,
options,
);
return cover_artworks;
}
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 cover_artworksData = data.map((item, index) => ({
id: item.id || undefined,
prompt: item.prompt
||
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 cover_artworks = await db.cover_artworks.bulkCreate(cover_artworksData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < cover_artworks.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.cover_artworks.getTableName(),
belongsToColumn: 'art_images',
belongsToId: cover_artworks[i].id,
},
data[i].art_images,
options,
);
}
return cover_artworks;
}
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 cover_artworks = await db.cover_artworks.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.prompt !== undefined) updatePayload.prompt = data.prompt;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await cover_artworks.update(updatePayload, {transaction});
if (data.song !== undefined) {
await cover_artworks.setSong(
data.song,
{ transaction }
);
}
if (data.organizations !== undefined) {
await cover_artworks.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.cover_artworks.getTableName(),
belongsToColumn: 'art_images',
belongsToId: cover_artworks.id,
},
data.art_images,
options,
);
return cover_artworks;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cover_artworks = await db.cover_artworks.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of cover_artworks) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of cover_artworks) {
await record.destroy({transaction});
}
});
return cover_artworks;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const cover_artworks = await db.cover_artworks.findByPk(id, options);
await cover_artworks.update({
deletedBy: currentUser.id
}, {
transaction,
});
await cover_artworks.destroy({
transaction
});
return cover_artworks;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const cover_artworks = await db.cover_artworks.findOne(
{ where },
{ transaction },
);
if (!cover_artworks) {
return cover_artworks;
}
const output = cover_artworks.get({plain: true});
output.song = await cover_artworks.getSong({
transaction
});
output.art_images = await cover_artworks.getArt_images({
transaction
});
output.organizations = await cover_artworks.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.songs,
as: 'song',
where: filter.song ? {
[Op.or]: [
{ id: { [Op.in]: filter.song.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.song.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'art_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.prompt) {
where = {
...where,
[Op.and]: Utils.ilike(
'cover_artworks',
'prompt',
filter.prompt,
),
};
}
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.cover_artworks.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(
'cover_artworks',
'prompt',
query,
),
],
};
}
const records = await db.cover_artworks.findAll({
attributes: [ 'id', 'prompt' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['prompt', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.prompt,
}));
}
};

View File

@ -0,0 +1,649 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ExportsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exports = await db.exports.create(
{
id: data.id || undefined,
format: data.format
||
null
,
quality: data.quality
||
null
,
include_stems: data.include_stems
||
false
,
status: data.status
||
null
,
requested_at: data.requested_at
||
null
,
completed_at: data.completed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await exports.setSong( data.song || null, {
transaction,
});
await exports.setRequested_user( data.requested_user || null, {
transaction,
});
await exports.setExport_asset( data.export_asset || null, {
transaction,
});
await exports.setOrganizations( data.organizations || null, {
transaction,
});
return exports;
}
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 exportsData = data.map((item, index) => ({
id: item.id || undefined,
format: item.format
||
null
,
quality: item.quality
||
null
,
include_stems: item.include_stems
||
false
,
status: item.status
||
null
,
requested_at: item.requested_at
||
null
,
completed_at: item.completed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const exports = await db.exports.bulkCreate(exportsData, { transaction });
// For each item created, replace relation files
return exports;
}
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 exports = await db.exports.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.format !== undefined) updatePayload.format = data.format;
if (data.quality !== undefined) updatePayload.quality = data.quality;
if (data.include_stems !== undefined) updatePayload.include_stems = data.include_stems;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
updatePayload.updatedById = currentUser.id;
await exports.update(updatePayload, {transaction});
if (data.song !== undefined) {
await exports.setSong(
data.song,
{ transaction }
);
}
if (data.requested_user !== undefined) {
await exports.setRequested_user(
data.requested_user,
{ transaction }
);
}
if (data.export_asset !== undefined) {
await exports.setExport_asset(
data.export_asset,
{ transaction }
);
}
if (data.organizations !== undefined) {
await exports.setOrganizations(
data.organizations,
{ transaction }
);
}
return exports;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const exports = await db.exports.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of exports) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of exports) {
await record.destroy({transaction});
}
});
return exports;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const exports = await db.exports.findByPk(id, options);
await exports.update({
deletedBy: currentUser.id
}, {
transaction,
});
await exports.destroy({
transaction
});
return exports;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const exports = await db.exports.findOne(
{ where },
{ transaction },
);
if (!exports) {
return exports;
}
const output = exports.get({plain: true});
output.song = await exports.getSong({
transaction
});
output.requested_user = await exports.getRequested_user({
transaction
});
output.export_asset = await exports.getExport_asset({
transaction
});
output.organizations = await exports.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.songs,
as: 'song',
where: filter.song ? {
[Op.or]: [
{ id: { [Op.in]: filter.song.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.song.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'requested_user',
where: filter.requested_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.assets,
as: 'export_asset',
where: filter.export_asset ? {
[Op.or]: [
{ id: { [Op.in]: filter.export_asset.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.export_asset.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.requested_atRange) {
const [start, end] = filter.requested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.format) {
where = {
...where,
format: filter.format,
};
}
if (filter.quality) {
where = {
...where,
quality: filter.quality,
};
}
if (filter.include_stems) {
where = {
...where,
include_stems: filter.include_stems,
};
}
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.exports.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(
'exports',
'format',
query,
),
],
};
}
const records = await db.exports.findAll({
attributes: [ 'id', 'format' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['format', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.format,
}));
}
};

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

File diff suppressed because it is too large Load Diff

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 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
,
origin: data.origin
||
null
,
description: data.description
||
null
,
typical_bpm_min: data.typical_bpm_min
||
null
,
typical_bpm_max: data.typical_bpm_max
||
null
,
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
,
origin: item.origin
||
null
,
description: item.description
||
null
,
typical_bpm_min: item.typical_bpm_min
||
null
,
typical_bpm_max: item.typical_bpm_max
||
null
,
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.origin !== undefined) updatePayload.origin = data.origin;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.typical_bpm_min !== undefined) updatePayload.typical_bpm_min = data.typical_bpm_min;
if (data.typical_bpm_max !== undefined) updatePayload.typical_bpm_max = data.typical_bpm_max;
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.projects_primary_genre = await genres.getProjects_primary_genre({
transaction
});
output.songs_genre = await genres.getSongs_genre({
transaction
});
output.generation_requests_target_genre = await genres.getGeneration_requests_target_genre({
transaction
});
output.vocal_processing_presets_recommended_genre = await genres.getVocal_processing_presets_recommended_genre({
transaction
});
output.mastering_presets_genre = await genres.getMastering_presets_genre({
transaction
});
output.marketplace_listings_genre = await genres.getMarketplace_listings_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.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'genres',
'description',
filter.description,
),
};
}
if (filter.typical_bpm_minRange) {
const [start, end] = filter.typical_bpm_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
typical_bpm_min: {
...where.typical_bpm_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
typical_bpm_min: {
...where.typical_bpm_min,
[Op.lte]: end,
},
};
}
}
if (filter.typical_bpm_maxRange) {
const [start, end] = filter.typical_bpm_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
typical_bpm_max: {
...where.typical_bpm_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
typical_bpm_max: {
...where.typical_bpm_max,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.origin) {
where = {
...where,
origin: filter.origin,
};
}
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,456 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class LanguagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const languages = await db.languages.create(
{
id: data.id || undefined,
name: data.name
||
null
,
iso_code: data.iso_code
||
null
,
is_supported: data.is_supported
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await languages.setOrganizations( data.organizations || null, {
transaction,
});
return languages;
}
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 languagesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
iso_code: item.iso_code
||
null
,
is_supported: item.is_supported
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const languages = await db.languages.bulkCreate(languagesData, { transaction });
// For each item created, replace relation files
return languages;
}
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 languages = await db.languages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.iso_code !== undefined) updatePayload.iso_code = data.iso_code;
if (data.is_supported !== undefined) updatePayload.is_supported = data.is_supported;
updatePayload.updatedById = currentUser.id;
await languages.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await languages.setOrganizations(
data.organizations,
{ transaction }
);
}
return languages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const languages = await db.languages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of languages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of languages) {
await record.destroy({transaction});
}
});
return languages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const languages = await db.languages.findByPk(id, options);
await languages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await languages.destroy({
transaction
});
return languages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const languages = await db.languages.findOne(
{ where },
{ transaction },
);
if (!languages) {
return languages;
}
const output = languages.get({plain: true});
output.songs_vocal_language = await languages.getSongs_vocal_language({
transaction
});
output.organizations = await languages.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(
'languages',
'name',
filter.name,
),
};
}
if (filter.iso_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'languages',
'iso_code',
filter.iso_code,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_supported) {
where = {
...where,
is_supported: filter.is_supported,
};
}
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.languages.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(
'languages',
'name',
query,
),
],
};
}
const records = await db.languages.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,753 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Marketplace_listingsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const marketplace_listings = await db.marketplace_listings.create(
{
id: data.id || undefined,
listing_type: data.listing_type
||
null
,
title: data.title
||
null
,
description: data.description
||
null
,
price: data.price
||
null
,
currency: data.currency
||
null
,
status: data.status
||
null
,
published_at: data.published_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await marketplace_listings.setSeller_user( data.seller_user || null, {
transaction,
});
await marketplace_listings.setWorkspace( data.workspace || null, {
transaction,
});
await marketplace_listings.setGenre( data.genre || null, {
transaction,
});
await marketplace_listings.setPreview_asset( data.preview_asset || null, {
transaction,
});
await marketplace_listings.setDeliverable_asset( data.deliverable_asset || null, {
transaction,
});
await marketplace_listings.setOrganizations( data.organizations || null, {
transaction,
});
return marketplace_listings;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const marketplace_listingsData = data.map((item, index) => ({
id: item.id || undefined,
listing_type: item.listing_type
||
null
,
title: item.title
||
null
,
description: item.description
||
null
,
price: item.price
||
null
,
currency: item.currency
||
null
,
status: item.status
||
null
,
published_at: item.published_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const marketplace_listings = await db.marketplace_listings.bulkCreate(marketplace_listingsData, { transaction });
// For each item created, replace relation files
return marketplace_listings;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const marketplace_listings = await db.marketplace_listings.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.listing_type !== undefined) updatePayload.listing_type = data.listing_type;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
updatePayload.updatedById = currentUser.id;
await marketplace_listings.update(updatePayload, {transaction});
if (data.seller_user !== undefined) {
await marketplace_listings.setSeller_user(
data.seller_user,
{ transaction }
);
}
if (data.workspace !== undefined) {
await marketplace_listings.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.genre !== undefined) {
await marketplace_listings.setGenre(
data.genre,
{ transaction }
);
}
if (data.preview_asset !== undefined) {
await marketplace_listings.setPreview_asset(
data.preview_asset,
{ transaction }
);
}
if (data.deliverable_asset !== undefined) {
await marketplace_listings.setDeliverable_asset(
data.deliverable_asset,
{ transaction }
);
}
if (data.organizations !== undefined) {
await marketplace_listings.setOrganizations(
data.organizations,
{ transaction }
);
}
return marketplace_listings;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const marketplace_listings = await db.marketplace_listings.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of marketplace_listings) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of marketplace_listings) {
await record.destroy({transaction});
}
});
return marketplace_listings;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const marketplace_listings = await db.marketplace_listings.findByPk(id, options);
await marketplace_listings.update({
deletedBy: currentUser.id
}, {
transaction,
});
await marketplace_listings.destroy({
transaction
});
return marketplace_listings;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const marketplace_listings = await db.marketplace_listings.findOne(
{ where },
{ transaction },
);
if (!marketplace_listings) {
return marketplace_listings;
}
const output = marketplace_listings.get({plain: true});
output.marketplace_orders_listing = await marketplace_listings.getMarketplace_orders_listing({
transaction
});
output.seller_user = await marketplace_listings.getSeller_user({
transaction
});
output.workspace = await marketplace_listings.getWorkspace({
transaction
});
output.genre = await marketplace_listings.getGenre({
transaction
});
output.preview_asset = await marketplace_listings.getPreview_asset({
transaction
});
output.deliverable_asset = await marketplace_listings.getDeliverable_asset({
transaction
});
output.organizations = await marketplace_listings.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'seller_user',
where: filter.seller_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.seller_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.seller_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.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.assets,
as: 'preview_asset',
where: filter.preview_asset ? {
[Op.or]: [
{ id: { [Op.in]: filter.preview_asset.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.preview_asset.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.assets,
as: 'deliverable_asset',
where: filter.deliverable_asset ? {
[Op.or]: [
{ id: { [Op.in]: filter.deliverable_asset.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.deliverable_asset.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(
'marketplace_listings',
'title',
filter.title,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'marketplace_listings',
'description',
filter.description,
),
};
}
if (filter.priceRange) {
const [start, end] = filter.priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price: {
...where.price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price: {
...where.price,
[Op.lte]: end,
},
};
}
}
if (filter.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.listing_type) {
where = {
...where,
listing_type: filter.listing_type,
};
}
if (filter.currency) {
where = {
...where,
currency: filter.currency,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.marketplace_listings.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'marketplace_listings',
'title',
query,
),
],
};
}
const records = await db.marketplace_listings.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,607 @@
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 Marketplace_ordersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const marketplace_orders = await db.marketplace_orders.create(
{
id: data.id || undefined,
amount: data.amount
||
null
,
currency: data.currency
||
null
,
status: data.status
||
null
,
ordered_at: data.ordered_at
||
null
,
fulfilled_at: data.fulfilled_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await marketplace_orders.setListing( data.listing || null, {
transaction,
});
await marketplace_orders.setBuyer_user( data.buyer_user || null, {
transaction,
});
await marketplace_orders.setOrganizations( data.organizations || null, {
transaction,
});
return marketplace_orders;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const marketplace_ordersData = data.map((item, index) => ({
id: item.id || undefined,
amount: item.amount
||
null
,
currency: item.currency
||
null
,
status: item.status
||
null
,
ordered_at: item.ordered_at
||
null
,
fulfilled_at: item.fulfilled_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const marketplace_orders = await db.marketplace_orders.bulkCreate(marketplace_ordersData, { transaction });
// For each item created, replace relation files
return marketplace_orders;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const marketplace_orders = await db.marketplace_orders.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.ordered_at !== undefined) updatePayload.ordered_at = data.ordered_at;
if (data.fulfilled_at !== undefined) updatePayload.fulfilled_at = data.fulfilled_at;
updatePayload.updatedById = currentUser.id;
await marketplace_orders.update(updatePayload, {transaction});
if (data.listing !== undefined) {
await marketplace_orders.setListing(
data.listing,
{ transaction }
);
}
if (data.buyer_user !== undefined) {
await marketplace_orders.setBuyer_user(
data.buyer_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await marketplace_orders.setOrganizations(
data.organizations,
{ transaction }
);
}
return marketplace_orders;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const marketplace_orders = await db.marketplace_orders.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of marketplace_orders) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of marketplace_orders) {
await record.destroy({transaction});
}
});
return marketplace_orders;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const marketplace_orders = await db.marketplace_orders.findByPk(id, options);
await marketplace_orders.update({
deletedBy: currentUser.id
}, {
transaction,
});
await marketplace_orders.destroy({
transaction
});
return marketplace_orders;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const marketplace_orders = await db.marketplace_orders.findOne(
{ where },
{ transaction },
);
if (!marketplace_orders) {
return marketplace_orders;
}
const output = marketplace_orders.get({plain: true});
output.listing = await marketplace_orders.getListing({
transaction
});
output.buyer_user = await marketplace_orders.getBuyer_user({
transaction
});
output.organizations = await marketplace_orders.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.marketplace_listings,
as: 'listing',
where: filter.listing ? {
[Op.or]: [
{ id: { [Op.in]: filter.listing.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.listing.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'buyer_user',
where: filter.buyer_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.buyer_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.buyer_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
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.ordered_atRange) {
const [start, end] = filter.ordered_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ordered_at: {
...where.ordered_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ordered_at: {
...where.ordered_at,
[Op.lte]: end,
},
};
}
}
if (filter.fulfilled_atRange) {
const [start, end] = filter.fulfilled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
fulfilled_at: {
...where.fulfilled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
fulfilled_at: {
...where.fulfilled_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.currency) {
where = {
...where,
currency: filter.currency,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.marketplace_orders.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'marketplace_orders',
'status',
query,
),
],
};
}
const records = await db.marketplace_orders.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,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 Mastering_presetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mastering_presets = await db.mastering_presets.create(
{
id: data.id || undefined,
name: data.name
||
null
,
target: data.target
||
null
,
lufs_target: data.lufs_target
||
null
,
true_peak_db: data.true_peak_db
||
null
,
is_default: data.is_default
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await mastering_presets.setGenre( data.genre || null, {
transaction,
});
await mastering_presets.setOrganizations( data.organizations || null, {
transaction,
});
return mastering_presets;
}
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 mastering_presetsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
target: item.target
||
null
,
lufs_target: item.lufs_target
||
null
,
true_peak_db: item.true_peak_db
||
null
,
is_default: item.is_default
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const mastering_presets = await db.mastering_presets.bulkCreate(mastering_presetsData, { transaction });
// For each item created, replace relation files
return mastering_presets;
}
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 mastering_presets = await db.mastering_presets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.target !== undefined) updatePayload.target = data.target;
if (data.lufs_target !== undefined) updatePayload.lufs_target = data.lufs_target;
if (data.true_peak_db !== undefined) updatePayload.true_peak_db = data.true_peak_db;
if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
updatePayload.updatedById = currentUser.id;
await mastering_presets.update(updatePayload, {transaction});
if (data.genre !== undefined) {
await mastering_presets.setGenre(
data.genre,
{ transaction }
);
}
if (data.organizations !== undefined) {
await mastering_presets.setOrganizations(
data.organizations,
{ transaction }
);
}
return mastering_presets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mastering_presets = await db.mastering_presets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of mastering_presets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of mastering_presets) {
await record.destroy({transaction});
}
});
return mastering_presets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mastering_presets = await db.mastering_presets.findByPk(id, options);
await mastering_presets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await mastering_presets.destroy({
transaction
});
return mastering_presets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const mastering_presets = await db.mastering_presets.findOne(
{ where },
{ transaction },
);
if (!mastering_presets) {
return mastering_presets;
}
const output = mastering_presets.get({plain: true});
output.mastering_sessions_preset = await mastering_presets.getMastering_sessions_preset({
transaction
});
output.genre = await mastering_presets.getGenre({
transaction
});
output.organizations = await mastering_presets.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: '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',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'mastering_presets',
'name',
filter.name,
),
};
}
if (filter.lufs_targetRange) {
const [start, end] = filter.lufs_targetRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lufs_target: {
...where.lufs_target,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lufs_target: {
...where.lufs_target,
[Op.lte]: end,
},
};
}
}
if (filter.true_peak_dbRange) {
const [start, end] = filter.true_peak_dbRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
true_peak_db: {
...where.true_peak_db,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
true_peak_db: {
...where.true_peak_db,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.target) {
where = {
...where,
target: filter.target,
};
}
if (filter.is_default) {
where = {
...where,
is_default: filter.is_default,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.mastering_presets.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(
'mastering_presets',
'name',
query,
),
],
};
}
const records = await db.mastering_presets.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,735 @@
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 Mastering_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mastering_sessions = await db.mastering_sessions.create(
{
id: data.id || undefined,
status: data.status
||
null
,
lufs_measured: data.lufs_measured
||
null
,
true_peak_measured_db: data.true_peak_measured_db
||
null
,
started_at: data.started_at
||
null
,
finished_at: data.finished_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await mastering_sessions.setSong( data.song || null, {
transaction,
});
await mastering_sessions.setRequested_user( data.requested_user || null, {
transaction,
});
await mastering_sessions.setPreset( data.preset || null, {
transaction,
});
await mastering_sessions.setInput_mix_asset( data.input_mix_asset || null, {
transaction,
});
await mastering_sessions.setResult_master_asset( data.result_master_asset || null, {
transaction,
});
await mastering_sessions.setOrganizations( data.organizations || null, {
transaction,
});
return mastering_sessions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const mastering_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
lufs_measured: item.lufs_measured
||
null
,
true_peak_measured_db: item.true_peak_measured_db
||
null
,
started_at: item.started_at
||
null
,
finished_at: item.finished_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const mastering_sessions = await db.mastering_sessions.bulkCreate(mastering_sessionsData, { transaction });
// For each item created, replace relation files
return mastering_sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const mastering_sessions = await db.mastering_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.lufs_measured !== undefined) updatePayload.lufs_measured = data.lufs_measured;
if (data.true_peak_measured_db !== undefined) updatePayload.true_peak_measured_db = data.true_peak_measured_db;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
updatePayload.updatedById = currentUser.id;
await mastering_sessions.update(updatePayload, {transaction});
if (data.song !== undefined) {
await mastering_sessions.setSong(
data.song,
{ transaction }
);
}
if (data.requested_user !== undefined) {
await mastering_sessions.setRequested_user(
data.requested_user,
{ transaction }
);
}
if (data.preset !== undefined) {
await mastering_sessions.setPreset(
data.preset,
{ transaction }
);
}
if (data.input_mix_asset !== undefined) {
await mastering_sessions.setInput_mix_asset(
data.input_mix_asset,
{ transaction }
);
}
if (data.result_master_asset !== undefined) {
await mastering_sessions.setResult_master_asset(
data.result_master_asset,
{ transaction }
);
}
if (data.organizations !== undefined) {
await mastering_sessions.setOrganizations(
data.organizations,
{ transaction }
);
}
return mastering_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mastering_sessions = await db.mastering_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of mastering_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of mastering_sessions) {
await record.destroy({transaction});
}
});
return mastering_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mastering_sessions = await db.mastering_sessions.findByPk(id, options);
await mastering_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await mastering_sessions.destroy({
transaction
});
return mastering_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const mastering_sessions = await db.mastering_sessions.findOne(
{ where },
{ transaction },
);
if (!mastering_sessions) {
return mastering_sessions;
}
const output = mastering_sessions.get({plain: true});
output.song = await mastering_sessions.getSong({
transaction
});
output.requested_user = await mastering_sessions.getRequested_user({
transaction
});
output.preset = await mastering_sessions.getPreset({
transaction
});
output.input_mix_asset = await mastering_sessions.getInput_mix_asset({
transaction
});
output.result_master_asset = await mastering_sessions.getResult_master_asset({
transaction
});
output.organizations = await mastering_sessions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.songs,
as: 'song',
where: filter.song ? {
[Op.or]: [
{ id: { [Op.in]: filter.song.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.song.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'requested_user',
where: filter.requested_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.mastering_presets,
as: 'preset',
where: filter.preset ? {
[Op.or]: [
{ id: { [Op.in]: filter.preset.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.preset.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.assets,
as: 'input_mix_asset',
where: filter.input_mix_asset ? {
[Op.or]: [
{ id: { [Op.in]: filter.input_mix_asset.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.input_mix_asset.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.assets,
as: 'result_master_asset',
where: filter.result_master_asset ? {
[Op.or]: [
{ id: { [Op.in]: filter.result_master_asset.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.result_master_asset.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.lufs_measuredRange) {
const [start, end] = filter.lufs_measuredRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lufs_measured: {
...where.lufs_measured,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lufs_measured: {
...where.lufs_measured,
[Op.lte]: end,
},
};
}
}
if (filter.true_peak_measured_dbRange) {
const [start, end] = filter.true_peak_measured_dbRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
true_peak_measured_db: {
...where.true_peak_measured_db,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
true_peak_measured_db: {
...where.true_peak_measured_db,
[Op.lte]: end,
},
};
}
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.finished_atRange) {
const [start, end] = filter.finished_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
finished_at: {
...where.finished_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.mastering_sessions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'mastering_sessions',
'status',
query,
),
],
};
}
const records = await db.mastering_sessions.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,718 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Mix_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mix_sessions = await db.mix_sessions.create(
{
id: data.id || undefined,
mix_type: data.mix_type
||
null
,
status: data.status
||
null
,
stereo_widening_amount: data.stereo_widening_amount
||
null
,
compression_amount: data.compression_amount
||
null
,
eq_amount: data.eq_amount
||
null
,
started_at: data.started_at
||
null
,
finished_at: data.finished_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await mix_sessions.setSong( data.song || null, {
transaction,
});
await mix_sessions.setRequested_user( data.requested_user || null, {
transaction,
});
await mix_sessions.setResult_mix_asset( data.result_mix_asset || null, {
transaction,
});
await mix_sessions.setOrganizations( data.organizations || null, {
transaction,
});
return mix_sessions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const mix_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
mix_type: item.mix_type
||
null
,
status: item.status
||
null
,
stereo_widening_amount: item.stereo_widening_amount
||
null
,
compression_amount: item.compression_amount
||
null
,
eq_amount: item.eq_amount
||
null
,
started_at: item.started_at
||
null
,
finished_at: item.finished_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const mix_sessions = await db.mix_sessions.bulkCreate(mix_sessionsData, { transaction });
// For each item created, replace relation files
return mix_sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const mix_sessions = await db.mix_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.mix_type !== undefined) updatePayload.mix_type = data.mix_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.stereo_widening_amount !== undefined) updatePayload.stereo_widening_amount = data.stereo_widening_amount;
if (data.compression_amount !== undefined) updatePayload.compression_amount = data.compression_amount;
if (data.eq_amount !== undefined) updatePayload.eq_amount = data.eq_amount;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
updatePayload.updatedById = currentUser.id;
await mix_sessions.update(updatePayload, {transaction});
if (data.song !== undefined) {
await mix_sessions.setSong(
data.song,
{ transaction }
);
}
if (data.requested_user !== undefined) {
await mix_sessions.setRequested_user(
data.requested_user,
{ transaction }
);
}
if (data.result_mix_asset !== undefined) {
await mix_sessions.setResult_mix_asset(
data.result_mix_asset,
{ transaction }
);
}
if (data.organizations !== undefined) {
await mix_sessions.setOrganizations(
data.organizations,
{ transaction }
);
}
return mix_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mix_sessions = await db.mix_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of mix_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of mix_sessions) {
await record.destroy({transaction});
}
});
return mix_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mix_sessions = await db.mix_sessions.findByPk(id, options);
await mix_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await mix_sessions.destroy({
transaction
});
return mix_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const mix_sessions = await db.mix_sessions.findOne(
{ where },
{ transaction },
);
if (!mix_sessions) {
return mix_sessions;
}
const output = mix_sessions.get({plain: true});
output.song = await mix_sessions.getSong({
transaction
});
output.requested_user = await mix_sessions.getRequested_user({
transaction
});
output.result_mix_asset = await mix_sessions.getResult_mix_asset({
transaction
});
output.organizations = await mix_sessions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.songs,
as: 'song',
where: filter.song ? {
[Op.or]: [
{ id: { [Op.in]: filter.song.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.song.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'requested_user',
where: filter.requested_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.assets,
as: 'result_mix_asset',
where: filter.result_mix_asset ? {
[Op.or]: [
{ id: { [Op.in]: filter.result_mix_asset.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.result_mix_asset.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.stereo_widening_amountRange) {
const [start, end] = filter.stereo_widening_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
stereo_widening_amount: {
...where.stereo_widening_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
stereo_widening_amount: {
...where.stereo_widening_amount,
[Op.lte]: end,
},
};
}
}
if (filter.compression_amountRange) {
const [start, end] = filter.compression_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
compression_amount: {
...where.compression_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
compression_amount: {
...where.compression_amount,
[Op.lte]: end,
},
};
}
}
if (filter.eq_amountRange) {
const [start, end] = filter.eq_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
eq_amount: {
...where.eq_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
eq_amount: {
...where.eq_amount,
[Op.lte]: end,
},
};
}
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.finished_atRange) {
const [start, end] = filter.finished_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.mix_type) {
where = {
...where,
mix_type: filter.mix_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.mix_sessions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'mix_sessions',
'mix_type',
query,
),
],
};
}
const records = await db.mix_sessions.findAll({
attributes: [ 'id', 'mix_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['mix_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.mix_type,
}));
}
};

View File

@ -0,0 +1,461 @@
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.workspaces_organizations = await organizations.getWorkspaces_organizations({
transaction
});
output.workspace_memberships_organizations = await organizations.getWorkspace_memberships_organizations({
transaction
});
output.genres_organizations = await organizations.getGenres_organizations({
transaction
});
output.languages_organizations = await organizations.getLanguages_organizations({
transaction
});
output.ai_models_organizations = await organizations.getAi_models_organizations({
transaction
});
output.projects_organizations = await organizations.getProjects_organizations({
transaction
});
output.project_collaborations_organizations = await organizations.getProject_collaborations_organizations({
transaction
});
output.songs_organizations = await organizations.getSongs_organizations({
transaction
});
output.song_metadata_organizations = await organizations.getSong_metadata_organizations({
transaction
});
output.assets_organizations = await organizations.getAssets_organizations({
transaction
});
output.recording_sessions_organizations = await organizations.getRecording_sessions_organizations({
transaction
});
output.tracks_organizations = await organizations.getTracks_organizations({
transaction
});
output.arrangement_sections_organizations = await organizations.getArrangement_sections_organizations({
transaction
});
output.generation_requests_organizations = await organizations.getGeneration_requests_organizations({
transaction
});
output.vocal_processing_presets_organizations = await organizations.getVocal_processing_presets_organizations({
transaction
});
output.mastering_presets_organizations = await organizations.getMastering_presets_organizations({
transaction
});
output.mix_sessions_organizations = await organizations.getMix_sessions_organizations({
transaction
});
output.mastering_sessions_organizations = await organizations.getMastering_sessions_organizations({
transaction
});
output.exports_organizations = await organizations.getExports_organizations({
transaction
});
output.cover_artworks_organizations = await organizations.getCover_artworks_organizations({
transaction
});
output.marketplace_listings_organizations = await organizations.getMarketplace_listings_organizations({
transaction
});
output.marketplace_orders_organizations = await organizations.getMarketplace_orders_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,355 @@
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,570 @@
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 Project_collaborationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const project_collaborations = await db.project_collaborations.create(
{
id: data.id || undefined,
permission_level: data.permission_level
||
null
,
invited_at: data.invited_at
||
null
,
accepted_at: data.accepted_at
||
null
,
invite_status: data.invite_status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await project_collaborations.setProject( data.project || null, {
transaction,
});
await project_collaborations.setCollaborator_user( data.collaborator_user || null, {
transaction,
});
await project_collaborations.setOrganizations( data.organizations || null, {
transaction,
});
return project_collaborations;
}
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 project_collaborationsData = data.map((item, index) => ({
id: item.id || undefined,
permission_level: item.permission_level
||
null
,
invited_at: item.invited_at
||
null
,
accepted_at: item.accepted_at
||
null
,
invite_status: item.invite_status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const project_collaborations = await db.project_collaborations.bulkCreate(project_collaborationsData, { transaction });
// For each item created, replace relation files
return project_collaborations;
}
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 project_collaborations = await db.project_collaborations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.permission_level !== undefined) updatePayload.permission_level = data.permission_level;
if (data.invited_at !== undefined) updatePayload.invited_at = data.invited_at;
if (data.accepted_at !== undefined) updatePayload.accepted_at = data.accepted_at;
if (data.invite_status !== undefined) updatePayload.invite_status = data.invite_status;
updatePayload.updatedById = currentUser.id;
await project_collaborations.update(updatePayload, {transaction});
if (data.project !== undefined) {
await project_collaborations.setProject(
data.project,
{ transaction }
);
}
if (data.collaborator_user !== undefined) {
await project_collaborations.setCollaborator_user(
data.collaborator_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await project_collaborations.setOrganizations(
data.organizations,
{ transaction }
);
}
return project_collaborations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const project_collaborations = await db.project_collaborations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of project_collaborations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of project_collaborations) {
await record.destroy({transaction});
}
});
return project_collaborations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const project_collaborations = await db.project_collaborations.findByPk(id, options);
await project_collaborations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await project_collaborations.destroy({
transaction
});
return project_collaborations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const project_collaborations = await db.project_collaborations.findOne(
{ where },
{ transaction },
);
if (!project_collaborations) {
return project_collaborations;
}
const output = project_collaborations.get({plain: true});
output.project = await project_collaborations.getProject({
transaction
});
output.collaborator_user = await project_collaborations.getCollaborator_user({
transaction
});
output.organizations = await project_collaborations.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.projects,
as: 'project',
where: filter.project ? {
[Op.or]: [
{ id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'collaborator_user',
where: filter.collaborator_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.collaborator_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.collaborator_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.permission_level) {
where = {
...where,
permission_level: filter.permission_level,
};
}
if (filter.invite_status) {
where = {
...where,
invite_status: filter.invite_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.project_collaborations.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(
'project_collaborations',
'invite_status',
query,
),
],
};
}
const records = await db.project_collaborations.findAll({
attributes: [ 'id', 'invite_status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['invite_status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.invite_status,
}));
}
};

View File

@ -0,0 +1,758 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ProjectsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
status: data.status
||
null
,
target_bpm: data.target_bpm
||
null
,
target_key: data.target_key
||
null
,
mood: data.mood
||
null
,
target_duration_seconds: data.target_duration_seconds
||
null
,
collaboration_enabled: data.collaboration_enabled
||
false
,
last_opened_at: data.last_opened_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await projects.setWorkspace( data.workspace || null, {
transaction,
});
await projects.setCreated_user( data.created_user || null, {
transaction,
});
await projects.setPrimary_genre( data.primary_genre || null, {
transaction,
});
await projects.setOrganizations( data.organizations || null, {
transaction,
});
return projects;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const projectsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
status: item.status
||
null
,
target_bpm: item.target_bpm
||
null
,
target_key: item.target_key
||
null
,
mood: item.mood
||
null
,
target_duration_seconds: item.target_duration_seconds
||
null
,
collaboration_enabled: item.collaboration_enabled
||
false
,
last_opened_at: item.last_opened_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const projects = await db.projects.bulkCreate(projectsData, { transaction });
// For each item created, replace relation files
return projects;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const projects = await db.projects.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.target_bpm !== undefined) updatePayload.target_bpm = data.target_bpm;
if (data.target_key !== undefined) updatePayload.target_key = data.target_key;
if (data.mood !== undefined) updatePayload.mood = data.mood;
if (data.target_duration_seconds !== undefined) updatePayload.target_duration_seconds = data.target_duration_seconds;
if (data.collaboration_enabled !== undefined) updatePayload.collaboration_enabled = data.collaboration_enabled;
if (data.last_opened_at !== undefined) updatePayload.last_opened_at = data.last_opened_at;
updatePayload.updatedById = currentUser.id;
await projects.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await projects.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.created_user !== undefined) {
await projects.setCreated_user(
data.created_user,
{ transaction }
);
}
if (data.primary_genre !== undefined) {
await projects.setPrimary_genre(
data.primary_genre,
{ transaction }
);
}
if (data.organizations !== undefined) {
await projects.setOrganizations(
data.organizations,
{ transaction }
);
}
return projects;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of projects) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of projects) {
await record.destroy({transaction});
}
});
return projects;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findByPk(id, options);
await projects.update({
deletedBy: currentUser.id
}, {
transaction,
});
await projects.destroy({
transaction
});
return projects;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findOne(
{ where },
{ transaction },
);
if (!projects) {
return projects;
}
const output = projects.get({plain: true});
output.project_collaborations_project = await projects.getProject_collaborations_project({
transaction
});
output.songs_project = await projects.getSongs_project({
transaction
});
output.assets_project = await projects.getAssets_project({
transaction
});
output.recording_sessions_project = await projects.getRecording_sessions_project({
transaction
});
output.generation_requests_project = await projects.getGeneration_requests_project({
transaction
});
output.workspace = await projects.getWorkspace({
transaction
});
output.created_user = await projects.getCreated_user({
transaction
});
output.primary_genre = await projects.getPrimary_genre({
transaction
});
output.organizations = await projects.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'created_user',
where: filter.created_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.genres,
as: 'primary_genre',
where: filter.primary_genre ? {
[Op.or]: [
{ id: { [Op.in]: filter.primary_genre.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.primary_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(
'projects',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'description',
filter.description,
),
};
}
if (filter.target_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'target_key',
filter.target_key,
),
};
}
if (filter.target_bpmRange) {
const [start, end] = filter.target_bpmRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
target_bpm: {
...where.target_bpm,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
target_bpm: {
...where.target_bpm,
[Op.lte]: end,
},
};
}
}
if (filter.target_duration_secondsRange) {
const [start, end] = filter.target_duration_secondsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
target_duration_seconds: {
...where.target_duration_seconds,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
target_duration_seconds: {
...where.target_duration_seconds,
[Op.lte]: end,
},
};
}
}
if (filter.last_opened_atRange) {
const [start, end] = filter.last_opened_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_opened_at: {
...where.last_opened_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_opened_at: {
...where.last_opened_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.mood) {
where = {
...where,
mood: filter.mood,
};
}
if (filter.collaboration_enabled) {
where = {
...where,
collaboration_enabled: filter.collaboration_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.projects.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'projects',
'name',
query,
),
],
};
}
const records = await db.projects.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,679 @@
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 Recording_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const recording_sessions = await db.recording_sessions.create(
{
id: data.id || undefined,
status: data.status
||
null
,
started_at: data.started_at
||
null
,
ended_at: data.ended_at
||
null
,
input_channels: data.input_channels
||
null
,
sample_rate_hz: data.sample_rate_hz
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await recording_sessions.setProject( data.project || null, {
transaction,
});
await recording_sessions.setSong( data.song || null, {
transaction,
});
await recording_sessions.setStarted_user( data.started_user || null, {
transaction,
});
await recording_sessions.setOrganizations( data.organizations || null, {
transaction,
});
return recording_sessions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const recording_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
started_at: item.started_at
||
null
,
ended_at: item.ended_at
||
null
,
input_channels: item.input_channels
||
null
,
sample_rate_hz: item.sample_rate_hz
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const recording_sessions = await db.recording_sessions.bulkCreate(recording_sessionsData, { transaction });
// For each item created, replace relation files
return recording_sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const recording_sessions = await db.recording_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.input_channels !== undefined) updatePayload.input_channels = data.input_channels;
if (data.sample_rate_hz !== undefined) updatePayload.sample_rate_hz = data.sample_rate_hz;
updatePayload.updatedById = currentUser.id;
await recording_sessions.update(updatePayload, {transaction});
if (data.project !== undefined) {
await recording_sessions.setProject(
data.project,
{ transaction }
);
}
if (data.song !== undefined) {
await recording_sessions.setSong(
data.song,
{ transaction }
);
}
if (data.started_user !== undefined) {
await recording_sessions.setStarted_user(
data.started_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await recording_sessions.setOrganizations(
data.organizations,
{ transaction }
);
}
return recording_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const recording_sessions = await db.recording_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of recording_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of recording_sessions) {
await record.destroy({transaction});
}
});
return recording_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const recording_sessions = await db.recording_sessions.findByPk(id, options);
await recording_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await recording_sessions.destroy({
transaction
});
return recording_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const recording_sessions = await db.recording_sessions.findOne(
{ where },
{ transaction },
);
if (!recording_sessions) {
return recording_sessions;
}
const output = recording_sessions.get({plain: true});
output.project = await recording_sessions.getProject({
transaction
});
output.song = await recording_sessions.getSong({
transaction
});
output.started_user = await recording_sessions.getStarted_user({
transaction
});
output.organizations = await recording_sessions.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.projects,
as: 'project',
where: filter.project ? {
[Op.or]: [
{ id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.songs,
as: 'song',
where: filter.song ? {
[Op.or]: [
{ id: { [Op.in]: filter.song.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.song.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'started_user',
where: filter.started_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.started_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.started_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.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
started_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ended_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.ended_atRange) {
const [start, end] = filter.ended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.lte]: end,
},
};
}
}
if (filter.input_channelsRange) {
const [start, end] = filter.input_channelsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
input_channels: {
...where.input_channels,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
input_channels: {
...where.input_channels,
[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.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.recording_sessions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'recording_sessions',
'status',
query,
),
],
};
}
const records = await db.recording_sessions.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,
}));
}
};

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

@ -0,0 +1,457 @@
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,620 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Song_metadataDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const song_metadata = await db.song_metadata.create(
{
id: data.id || undefined,
isrc: data.isrc
||
null
,
upc: data.upc
||
null
,
release_title: data.release_title
||
null
,
release_date: data.release_date
||
null
,
label_name: data.label_name
||
null
,
publisher: data.publisher
||
null
,
copyright_notice: data.copyright_notice
||
null
,
distribution_status: data.distribution_status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await song_metadata.setSong( data.song || null, {
transaction,
});
await song_metadata.setOrganizations( data.organizations || null, {
transaction,
});
return song_metadata;
}
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 song_metadataData = data.map((item, index) => ({
id: item.id || undefined,
isrc: item.isrc
||
null
,
upc: item.upc
||
null
,
release_title: item.release_title
||
null
,
release_date: item.release_date
||
null
,
label_name: item.label_name
||
null
,
publisher: item.publisher
||
null
,
copyright_notice: item.copyright_notice
||
null
,
distribution_status: item.distribution_status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const song_metadata = await db.song_metadata.bulkCreate(song_metadataData, { transaction });
// For each item created, replace relation files
return song_metadata;
}
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 song_metadata = await db.song_metadata.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.isrc !== undefined) updatePayload.isrc = data.isrc;
if (data.upc !== undefined) updatePayload.upc = data.upc;
if (data.release_title !== undefined) updatePayload.release_title = data.release_title;
if (data.release_date !== undefined) updatePayload.release_date = data.release_date;
if (data.label_name !== undefined) updatePayload.label_name = data.label_name;
if (data.publisher !== undefined) updatePayload.publisher = data.publisher;
if (data.copyright_notice !== undefined) updatePayload.copyright_notice = data.copyright_notice;
if (data.distribution_status !== undefined) updatePayload.distribution_status = data.distribution_status;
updatePayload.updatedById = currentUser.id;
await song_metadata.update(updatePayload, {transaction});
if (data.song !== undefined) {
await song_metadata.setSong(
data.song,
{ transaction }
);
}
if (data.organizations !== undefined) {
await song_metadata.setOrganizations(
data.organizations,
{ transaction }
);
}
return song_metadata;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const song_metadata = await db.song_metadata.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of song_metadata) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of song_metadata) {
await record.destroy({transaction});
}
});
return song_metadata;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const song_metadata = await db.song_metadata.findByPk(id, options);
await song_metadata.update({
deletedBy: currentUser.id
}, {
transaction,
});
await song_metadata.destroy({
transaction
});
return song_metadata;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const song_metadata = await db.song_metadata.findOne(
{ where },
{ transaction },
);
if (!song_metadata) {
return song_metadata;
}
const output = song_metadata.get({plain: true});
output.song = await song_metadata.getSong({
transaction
});
output.organizations = await song_metadata.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.songs,
as: 'song',
where: filter.song ? {
[Op.or]: [
{ id: { [Op.in]: filter.song.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.song.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.isrc) {
where = {
...where,
[Op.and]: Utils.ilike(
'song_metadata',
'isrc',
filter.isrc,
),
};
}
if (filter.upc) {
where = {
...where,
[Op.and]: Utils.ilike(
'song_metadata',
'upc',
filter.upc,
),
};
}
if (filter.release_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'song_metadata',
'release_title',
filter.release_title,
),
};
}
if (filter.label_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'song_metadata',
'label_name',
filter.label_name,
),
};
}
if (filter.publisher) {
where = {
...where,
[Op.and]: Utils.ilike(
'song_metadata',
'publisher',
filter.publisher,
),
};
}
if (filter.copyright_notice) {
where = {
...where,
[Op.and]: Utils.ilike(
'song_metadata',
'copyright_notice',
filter.copyright_notice,
),
};
}
if (filter.release_dateRange) {
const [start, end] = filter.release_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
release_date: {
...where.release_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
release_date: {
...where.release_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.distribution_status) {
where = {
...where,
distribution_status: filter.distribution_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.song_metadata.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(
'song_metadata',
'release_title',
query,
),
],
};
}
const records = await db.song_metadata.findAll({
attributes: [ 'id', 'release_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['release_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.release_title,
}));
}
};

745
backend/src/db/api/songs.js Normal file
View File

@ -0,0 +1,745 @@
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 SongsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const songs = await db.songs.create(
{
id: data.id || undefined,
title: data.title
||
null
,
artist_display: data.artist_display
||
null
,
bpm: data.bpm
||
null
,
key_signature: data.key_signature
||
null
,
mood: data.mood
||
null
,
duration_seconds: data.duration_seconds
||
null
,
explicit_content: data.explicit_content
||
false
,
lyrics: data.lyrics
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await songs.setProject( data.project || null, {
transaction,
});
await songs.setGenre( data.genre || null, {
transaction,
});
await songs.setVocal_language( data.vocal_language || null, {
transaction,
});
await songs.setOrganizations( data.organizations || null, {
transaction,
});
return songs;
}
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 songsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
artist_display: item.artist_display
||
null
,
bpm: item.bpm
||
null
,
key_signature: item.key_signature
||
null
,
mood: item.mood
||
null
,
duration_seconds: item.duration_seconds
||
null
,
explicit_content: item.explicit_content
||
false
,
lyrics: item.lyrics
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const songs = await db.songs.bulkCreate(songsData, { transaction });
// For each item created, replace relation files
return songs;
}
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 songs = await db.songs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.artist_display !== undefined) updatePayload.artist_display = data.artist_display;
if (data.bpm !== undefined) updatePayload.bpm = data.bpm;
if (data.key_signature !== undefined) updatePayload.key_signature = data.key_signature;
if (data.mood !== undefined) updatePayload.mood = data.mood;
if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
if (data.explicit_content !== undefined) updatePayload.explicit_content = data.explicit_content;
if (data.lyrics !== undefined) updatePayload.lyrics = data.lyrics;
updatePayload.updatedById = currentUser.id;
await songs.update(updatePayload, {transaction});
if (data.project !== undefined) {
await songs.setProject(
data.project,
{ transaction }
);
}
if (data.genre !== undefined) {
await songs.setGenre(
data.genre,
{ transaction }
);
}
if (data.vocal_language !== undefined) {
await songs.setVocal_language(
data.vocal_language,
{ transaction }
);
}
if (data.organizations !== undefined) {
await songs.setOrganizations(
data.organizations,
{ transaction }
);
}
return songs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const songs = await db.songs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of songs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of songs) {
await record.destroy({transaction});
}
});
return songs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const songs = await db.songs.findByPk(id, options);
await songs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await songs.destroy({
transaction
});
return songs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const songs = await db.songs.findOne(
{ where },
{ transaction },
);
if (!songs) {
return songs;
}
const output = songs.get({plain: true});
output.song_metadata_song = await songs.getSong_metadata_song({
transaction
});
output.assets_song = await songs.getAssets_song({
transaction
});
output.recording_sessions_song = await songs.getRecording_sessions_song({
transaction
});
output.tracks_song = await songs.getTracks_song({
transaction
});
output.arrangement_sections_song = await songs.getArrangement_sections_song({
transaction
});
output.generation_requests_song = await songs.getGeneration_requests_song({
transaction
});
output.mix_sessions_song = await songs.getMix_sessions_song({
transaction
});
output.mastering_sessions_song = await songs.getMastering_sessions_song({
transaction
});
output.exports_song = await songs.getExports_song({
transaction
});
output.cover_artworks_song = await songs.getCover_artworks_song({
transaction
});
output.project = await songs.getProject({
transaction
});
output.genre = await songs.getGenre({
transaction
});
output.vocal_language = await songs.getVocal_language({
transaction
});
output.organizations = await songs.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.projects,
as: 'project',
where: filter.project ? {
[Op.or]: [
{ id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.project.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.languages,
as: 'vocal_language',
where: filter.vocal_language ? {
[Op.or]: [
{ id: { [Op.in]: filter.vocal_language.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.vocal_language.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(
'songs',
'title',
filter.title,
),
};
}
if (filter.artist_display) {
where = {
...where,
[Op.and]: Utils.ilike(
'songs',
'artist_display',
filter.artist_display,
),
};
}
if (filter.key_signature) {
where = {
...where,
[Op.and]: Utils.ilike(
'songs',
'key_signature',
filter.key_signature,
),
};
}
if (filter.lyrics) {
where = {
...where,
[Op.and]: Utils.ilike(
'songs',
'lyrics',
filter.lyrics,
),
};
}
if (filter.bpmRange) {
const [start, end] = filter.bpmRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bpm: {
...where.bpm,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bpm: {
...where.bpm,
[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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.mood) {
where = {
...where,
mood: filter.mood,
};
}
if (filter.explicit_content) {
where = {
...where,
explicit_content: filter.explicit_content,
};
}
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.songs.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(
'songs',
'title',
query,
),
],
};
}
const records = await db.songs.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,638 @@
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,
name: data.name
||
null
,
track_type: data.track_type
||
null
,
instrument: data.instrument
||
null
,
volume_db: data.volume_db
||
null
,
pan: data.pan
||
null
,
mute: data.mute
||
false
,
solo: data.solo
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tracks.setSong( data.song || null, {
transaction,
});
await tracks.setSource_asset( data.source_asset || null, {
transaction,
});
await tracks.setOrganizations( data.organizations || null, {
transaction,
});
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,
name: item.name
||
null
,
track_type: item.track_type
||
null
,
instrument: item.instrument
||
null
,
volume_db: item.volume_db
||
null
,
pan: item.pan
||
null
,
mute: item.mute
||
false
,
solo: item.solo
||
false
,
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
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.name !== undefined) updatePayload.name = data.name;
if (data.track_type !== undefined) updatePayload.track_type = data.track_type;
if (data.instrument !== undefined) updatePayload.instrument = data.instrument;
if (data.volume_db !== undefined) updatePayload.volume_db = data.volume_db;
if (data.pan !== undefined) updatePayload.pan = data.pan;
if (data.mute !== undefined) updatePayload.mute = data.mute;
if (data.solo !== undefined) updatePayload.solo = data.solo;
updatePayload.updatedById = currentUser.id;
await tracks.update(updatePayload, {transaction});
if (data.song !== undefined) {
await tracks.setSong(
data.song,
{ transaction }
);
}
if (data.source_asset !== undefined) {
await tracks.setSource_asset(
data.source_asset,
{ transaction }
);
}
if (data.organizations !== undefined) {
await tracks.setOrganizations(
data.organizations,
{ transaction }
);
}
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.song = await tracks.getSong({
transaction
});
output.source_asset = await tracks.getSource_asset({
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.songs,
as: 'song',
where: filter.song ? {
[Op.or]: [
{ id: { [Op.in]: filter.song.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.song.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.assets,
as: 'source_asset',
where: filter.source_asset ? {
[Op.or]: [
{ id: { [Op.in]: filter.source_asset.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.source_asset.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(
'tracks',
'name',
filter.name,
),
};
}
if (filter.volume_dbRange) {
const [start, end] = filter.volume_dbRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
volume_db: {
...where.volume_db,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
volume_db: {
...where.volume_db,
[Op.lte]: end,
},
};
}
}
if (filter.panRange) {
const [start, end] = filter.panRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pan: {
...where.pan,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pan: {
...where.pan,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.track_type) {
where = {
...where,
track_type: filter.track_type,
};
}
if (filter.instrument) {
where = {
...where,
instrument: filter.instrument,
};
}
if (filter.mute) {
where = {
...where,
mute: filter.mute,
};
}
if (filter.solo) {
where = {
...where,
solo: filter.solo,
};
}
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',
'name',
query,
),
],
};
}
const records = await db.tracks.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,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,546 @@
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 Vocal_processing_presetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vocal_processing_presets = await db.vocal_processing_presets.create(
{
id: data.id || undefined,
name: data.name
||
null
,
preset_type: data.preset_type
||
null
,
description: data.description
||
null
,
intensity: data.intensity
||
null
,
is_default: data.is_default
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await vocal_processing_presets.setRecommended_genre( data.recommended_genre || null, {
transaction,
});
await vocal_processing_presets.setOrganizations( data.organizations || null, {
transaction,
});
return vocal_processing_presets;
}
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 vocal_processing_presetsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
preset_type: item.preset_type
||
null
,
description: item.description
||
null
,
intensity: item.intensity
||
null
,
is_default: item.is_default
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const vocal_processing_presets = await db.vocal_processing_presets.bulkCreate(vocal_processing_presetsData, { transaction });
// For each item created, replace relation files
return vocal_processing_presets;
}
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 vocal_processing_presets = await db.vocal_processing_presets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.preset_type !== undefined) updatePayload.preset_type = data.preset_type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.intensity !== undefined) updatePayload.intensity = data.intensity;
if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
updatePayload.updatedById = currentUser.id;
await vocal_processing_presets.update(updatePayload, {transaction});
if (data.recommended_genre !== undefined) {
await vocal_processing_presets.setRecommended_genre(
data.recommended_genre,
{ transaction }
);
}
if (data.organizations !== undefined) {
await vocal_processing_presets.setOrganizations(
data.organizations,
{ transaction }
);
}
return vocal_processing_presets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vocal_processing_presets = await db.vocal_processing_presets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of vocal_processing_presets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of vocal_processing_presets) {
await record.destroy({transaction});
}
});
return vocal_processing_presets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const vocal_processing_presets = await db.vocal_processing_presets.findByPk(id, options);
await vocal_processing_presets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await vocal_processing_presets.destroy({
transaction
});
return vocal_processing_presets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const vocal_processing_presets = await db.vocal_processing_presets.findOne(
{ where },
{ transaction },
);
if (!vocal_processing_presets) {
return vocal_processing_presets;
}
const output = vocal_processing_presets.get({plain: true});
output.recommended_genre = await vocal_processing_presets.getRecommended_genre({
transaction
});
output.organizations = await vocal_processing_presets.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: 'recommended_genre',
where: filter.recommended_genre ? {
[Op.or]: [
{ id: { [Op.in]: filter.recommended_genre.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.recommended_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(
'vocal_processing_presets',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'vocal_processing_presets',
'description',
filter.description,
),
};
}
if (filter.intensityRange) {
const [start, end] = filter.intensityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
intensity: {
...where.intensity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
intensity: {
...where.intensity,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.preset_type) {
where = {
...where,
preset_type: filter.preset_type,
};
}
if (filter.is_default) {
where = {
...where,
is_default: filter.is_default,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.vocal_processing_presets.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(
'vocal_processing_presets',
'name',
query,
),
],
};
}
const records = await db.vocal_processing_presets.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,535 @@
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 Workspace_membershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const workspace_memberships = await db.workspace_memberships.create(
{
id: data.id || undefined,
role: data.role
||
null
,
joined_at: data.joined_at
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await workspace_memberships.setWorkspace( data.workspace || null, {
transaction,
});
await workspace_memberships.setMember_user( data.member_user || null, {
transaction,
});
await workspace_memberships.setOrganizations( data.organizations || null, {
transaction,
});
return workspace_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 workspace_membershipsData = data.map((item, index) => ({
id: item.id || undefined,
role: item.role
||
null
,
joined_at: item.joined_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 workspace_memberships = await db.workspace_memberships.bulkCreate(workspace_membershipsData, { transaction });
// For each item created, replace relation files
return workspace_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 workspace_memberships = await db.workspace_memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.role !== undefined) updatePayload.role = data.role;
if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await workspace_memberships.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await workspace_memberships.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.member_user !== undefined) {
await workspace_memberships.setMember_user(
data.member_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await workspace_memberships.setOrganizations(
data.organizations,
{ transaction }
);
}
return workspace_memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const workspace_memberships = await db.workspace_memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of workspace_memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of workspace_memberships) {
await record.destroy({transaction});
}
});
return workspace_memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const workspace_memberships = await db.workspace_memberships.findByPk(id, options);
await workspace_memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await workspace_memberships.destroy({
transaction
});
return workspace_memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const workspace_memberships = await db.workspace_memberships.findOne(
{ where },
{ transaction },
);
if (!workspace_memberships) {
return workspace_memberships;
}
const output = workspace_memberships.get({plain: true});
output.workspace = await workspace_memberships.getWorkspace({
transaction
});
output.member_user = await workspace_memberships.getMember_user({
transaction
});
output.organizations = await workspace_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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.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.joined_atRange) {
const [start, end] = filter.joined_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.role) {
where = {
...where,
role: filter.role,
};
}
if (filter.is_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.workspace_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(
'workspace_memberships',
'role',
query,
),
],
};
}
const records = await db.workspace_memberships.findAll({
attributes: [ 'id', 'role' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['role', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.role,
}));
}
};

View File

@ -0,0 +1,603 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class WorkspacesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const workspaces = await db.workspaces.create(
{
id: data.id || undefined,
name: data.name
||
null
,
slug: data.slug
||
null
,
plan: data.plan
||
null
,
plan_started_at: data.plan_started_at
||
null
,
plan_ends_at: data.plan_ends_at
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await workspaces.setOwner_user( data.owner_user || null, {
transaction,
});
await workspaces.setOrganizations( data.organizations || null, {
transaction,
});
return workspaces;
}
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 workspacesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
slug: item.slug
||
null
,
plan: item.plan
||
null
,
plan_started_at: item.plan_started_at
||
null
,
plan_ends_at: item.plan_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 workspaces = await db.workspaces.bulkCreate(workspacesData, { transaction });
// For each item created, replace relation files
return workspaces;
}
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 workspaces = await db.workspaces.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.plan !== undefined) updatePayload.plan = data.plan;
if (data.plan_started_at !== undefined) updatePayload.plan_started_at = data.plan_started_at;
if (data.plan_ends_at !== undefined) updatePayload.plan_ends_at = data.plan_ends_at;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await workspaces.update(updatePayload, {transaction});
if (data.owner_user !== undefined) {
await workspaces.setOwner_user(
data.owner_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await workspaces.setOrganizations(
data.organizations,
{ transaction }
);
}
return workspaces;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const workspaces = await db.workspaces.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of workspaces) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of workspaces) {
await record.destroy({transaction});
}
});
return workspaces;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const workspaces = await db.workspaces.findByPk(id, options);
await workspaces.update({
deletedBy: currentUser.id
}, {
transaction,
});
await workspaces.destroy({
transaction
});
return workspaces;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const workspaces = await db.workspaces.findOne(
{ where },
{ transaction },
);
if (!workspaces) {
return workspaces;
}
const output = workspaces.get({plain: true});
output.workspace_memberships_workspace = await workspaces.getWorkspace_memberships_workspace({
transaction
});
output.projects_workspace = await workspaces.getProjects_workspace({
transaction
});
output.assets_workspace = await workspaces.getAssets_workspace({
transaction
});
output.generation_requests_workspace = await workspaces.getGeneration_requests_workspace({
transaction
});
output.marketplace_listings_workspace = await workspaces.getMarketplace_listings_workspace({
transaction
});
output.owner_user = await workspaces.getOwner_user({
transaction
});
output.organizations = await workspaces.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'owner_user',
where: filter.owner_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'workspaces',
'name',
filter.name,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'workspaces',
'slug',
filter.slug,
),
};
}
if (filter.plan_started_atRange) {
const [start, end] = filter.plan_started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
plan_started_at: {
...where.plan_started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
plan_started_at: {
...where.plan_started_at,
[Op.lte]: end,
},
};
}
}
if (filter.plan_ends_atRange) {
const [start, end] = filter.plan_ends_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
plan_ends_at: {
...where.plan_ends_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
plan_ends_at: {
...where.plan_ends_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.plan) {
where = {
...where,
plan: filter.plan,
};
}
if (filter.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.workspaces.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(
'workspaces',
'name',
query,
),
],
};
}
const records = await db.workspaces.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,33 @@
module.exports = {
production: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
},
development: {
username: 'postgres',
dialect: 'postgres',
password: '',
database: 'db_sa_ai_music_studio',
host: process.env.DB_HOST || 'localhost',
logging: console.log,
seederStorage: 'sequelize',
},
dev_stage: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
}
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,124 @@
module.exports = {
async up(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.files') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (tableName) {
await transaction.commit();
return;
}
await queryInterface.createTable(
'files',
{
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV4,
primaryKey: true,
},
belongsTo: {
type: Sequelize.DataTypes.STRING(255),
allowNull: true,
},
belongsToId: {
type: Sequelize.DataTypes.UUID,
allowNull: true,
},
belongsToColumn: {
type: Sequelize.DataTypes.STRING(255),
allowNull: true,
},
name: {
type: Sequelize.DataTypes.STRING(2083),
allowNull: false,
},
sizeInBytes: {
type: Sequelize.DataTypes.INTEGER,
allowNull: true,
},
privateUrl: {
type: Sequelize.DataTypes.STRING(2083),
allowNull: true,
},
publicUrl: {
type: Sequelize.DataTypes.STRING(2083),
allowNull: false,
},
createdAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
deletedAt: {
type: Sequelize.DataTypes.DATE,
allowNull: true,
},
createdById: {
type: Sequelize.DataTypes.UUID,
allowNull: true,
references: {
key: 'id',
model: 'users',
},
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
},
updatedById: {
type: Sequelize.DataTypes.UUID,
allowNull: true,
references: {
key: 'id',
model: 'users',
},
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
async down(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.files') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (!tableName) {
await transaction.commit();
return;
}
await queryInterface.dropTable('files', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,77 @@
module.exports = {
async up(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.\"usersCustom_permissionsPermissions\"') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (tableName) {
await transaction.commit();
return;
}
await queryInterface.createTable(
'usersCustom_permissionsPermissions',
{
createdAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
users_custom_permissionsId: {
type: Sequelize.DataTypes.UUID,
allowNull: false,
primaryKey: true,
},
permissionId: {
type: Sequelize.DataTypes.UUID,
allowNull: false,
primaryKey: true,
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
async down(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.\"usersCustom_permissionsPermissions\"') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (!tableName) {
await transaction.commit();
return;
}
await queryInterface.dropTable('usersCustom_permissionsPermissions', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,159 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ai_models = sequelize.define(
'ai_models',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
model_type: {
type: DataTypes.ENUM,
values: [
"music_generation",
"vocal_processing",
"mixing",
"mastering",
"cover_art",
"metadata"
],
},
provider: {
type: DataTypes.TEXT,
},
version: {
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,
},
);
ai_models.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.ai_models.hasMany(db.generation_requests, {
as: 'generation_requests_model',
foreignKey: {
name: 'modelId',
},
constraints: false,
});
//end loop
db.ai_models.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.ai_models.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_models.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_models;
};

View File

@ -0,0 +1,159 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const arrangement_sections = sequelize.define(
'arrangement_sections',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
section_type: {
type: DataTypes.ENUM,
values: [
"intro",
"verse",
"chorus",
"bridge",
"outro",
"breakdown",
"drop"
],
},
label: {
type: DataTypes.TEXT,
},
start_bar: {
type: DataTypes.INTEGER,
},
bar_length: {
type: DataTypes.INTEGER,
},
order_index: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
arrangement_sections.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.arrangement_sections.belongsTo(db.songs, {
as: 'song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.arrangement_sections.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.arrangement_sections.belongsTo(db.users, {
as: 'createdBy',
});
db.arrangement_sections.belongsTo(db.users, {
as: 'updatedBy',
});
};
return arrangement_sections;
};

View File

@ -0,0 +1,319 @@
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 assets = sequelize.define(
'assets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
asset_type: {
type: DataTypes.ENUM,
values: [
"audio",
"midi",
"image",
"document",
"preset"
],
},
audio_role: {
type: DataTypes.ENUM,
values: [
"vocal_raw",
"vocal_processed",
"instrumental",
"drums",
"bass",
"instruments",
"mix",
"master",
"stem",
"reference"
],
},
name: {
type: DataTypes.TEXT,
},
duration_seconds: {
type: DataTypes.DECIMAL,
},
sample_rate_hz: {
type: DataTypes.INTEGER,
},
bit_depth: {
type: DataTypes.INTEGER,
},
is_stereo: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
assets.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.assets.hasMany(db.tracks, {
as: 'tracks_source_asset',
foreignKey: {
name: 'source_assetId',
},
constraints: false,
});
db.assets.hasMany(db.generation_requests, {
as: 'generation_requests_input_asset',
foreignKey: {
name: 'input_assetId',
},
constraints: false,
});
db.assets.hasMany(db.generation_requests, {
as: 'generation_requests_output_asset',
foreignKey: {
name: 'output_assetId',
},
constraints: false,
});
db.assets.hasMany(db.mix_sessions, {
as: 'mix_sessions_result_mix_asset',
foreignKey: {
name: 'result_mix_assetId',
},
constraints: false,
});
db.assets.hasMany(db.mastering_sessions, {
as: 'mastering_sessions_input_mix_asset',
foreignKey: {
name: 'input_mix_assetId',
},
constraints: false,
});
db.assets.hasMany(db.mastering_sessions, {
as: 'mastering_sessions_result_master_asset',
foreignKey: {
name: 'result_master_assetId',
},
constraints: false,
});
db.assets.hasMany(db.exports, {
as: 'exports_export_asset',
foreignKey: {
name: 'export_assetId',
},
constraints: false,
});
db.assets.hasMany(db.marketplace_listings, {
as: 'marketplace_listings_preview_asset',
foreignKey: {
name: 'preview_assetId',
},
constraints: false,
});
db.assets.hasMany(db.marketplace_listings, {
as: 'marketplace_listings_deliverable_asset',
foreignKey: {
name: 'deliverable_assetId',
},
constraints: false,
});
//end loop
db.assets.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.assets.belongsTo(db.users, {
as: 'uploaded_user',
foreignKey: {
name: 'uploaded_userId',
},
constraints: false,
});
db.assets.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.assets.belongsTo(db.songs, {
as: 'song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.assets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.assets.hasMany(db.file, {
as: 'file_blobs',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.assets.getTableName(),
belongsToColumn: 'file_blobs',
},
});
db.assets.hasMany(db.file, {
as: 'image_blobs',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.assets.getTableName(),
belongsToColumn: 'image_blobs',
},
});
db.assets.belongsTo(db.users, {
as: 'createdBy',
});
db.assets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return assets;
};

View File

@ -0,0 +1,136 @@
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 cover_artworks = sequelize.define(
'cover_artworks',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
prompt: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"generated",
"selected",
"archived"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
cover_artworks.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.cover_artworks.belongsTo(db.songs, {
as: 'song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.cover_artworks.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.cover_artworks.hasMany(db.file, {
as: 'art_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.cover_artworks.getTableName(),
belongsToColumn: 'art_images',
},
});
db.cover_artworks.belongsTo(db.users, {
as: 'createdBy',
});
db.cover_artworks.belongsTo(db.users, {
as: 'updatedBy',
});
};
return cover_artworks;
};

View File

@ -0,0 +1,200 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const exports = sequelize.define(
'exports',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
format: {
type: DataTypes.ENUM,
values: [
"wav",
"mp3",
"stems_zip"
],
},
quality: {
type: DataTypes.ENUM,
values: [
"draft",
"standard",
"studio"
],
},
include_stems: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"processing",
"completed",
"failed"
],
},
requested_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
exports.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.exports.belongsTo(db.songs, {
as: 'song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.exports.belongsTo(db.users, {
as: 'requested_user',
foreignKey: {
name: 'requested_userId',
},
constraints: false,
});
db.exports.belongsTo(db.assets, {
as: 'export_asset',
foreignKey: {
name: 'export_assetId',
},
constraints: false,
});
db.exports.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.exports.belongsTo(db.users, {
as: 'createdBy',
});
db.exports.belongsTo(db.users, {
as: 'updatedBy',
});
};
return exports;
};

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,318 @@
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 generation_requests = sequelize.define(
'generation_requests',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
request_type: {
type: DataTypes.ENUM,
values: [
"generate_beat_from_text",
"generate_beat_from_vocals",
"arrangement_builder",
"vocal_processing",
"auto_mix",
"mastering",
"cover_art",
"song_naming",
"metadata_tagging",
"genre_suggestion",
"make_it_amapiano"
],
},
prompt_text: {
type: DataTypes.TEXT,
},
target_bpm: {
type: DataTypes.INTEGER,
},
target_key: {
type: DataTypes.TEXT,
},
mood: {
type: DataTypes.ENUM,
values: [
"happy",
"sad",
"spiritual",
"energetic",
"romantic",
"chill",
"aggressive"
],
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"succeeded",
"failed",
"canceled"
],
},
queued_at: {
type: DataTypes.DATE,
},
started_at: {
type: DataTypes.DATE,
},
finished_at: {
type: DataTypes.DATE,
},
error_message: {
type: DataTypes.TEXT,
},
compute_seconds: {
type: DataTypes.INTEGER,
},
estimated_cost: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
generation_requests.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.generation_requests.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.generation_requests.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.generation_requests.belongsTo(db.songs, {
as: 'song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.generation_requests.belongsTo(db.users, {
as: 'requested_user',
foreignKey: {
name: 'requested_userId',
},
constraints: false,
});
db.generation_requests.belongsTo(db.ai_models, {
as: 'model',
foreignKey: {
name: 'modelId',
},
constraints: false,
});
db.generation_requests.belongsTo(db.assets, {
as: 'input_asset',
foreignKey: {
name: 'input_assetId',
},
constraints: false,
});
db.generation_requests.belongsTo(db.genres, {
as: 'target_genre',
foreignKey: {
name: 'target_genreId',
},
constraints: false,
});
db.generation_requests.belongsTo(db.assets, {
as: 'output_asset',
foreignKey: {
name: 'output_assetId',
},
constraints: false,
});
db.generation_requests.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.generation_requests.belongsTo(db.users, {
as: 'createdBy',
});
db.generation_requests.belongsTo(db.users, {
as: 'updatedBy',
});
};
return generation_requests;
};

View File

@ -0,0 +1,192 @@
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,
},
origin: {
type: DataTypes.ENUM,
values: [
"south_africa",
"global"
],
},
description: {
type: DataTypes.TEXT,
},
typical_bpm_min: {
type: DataTypes.INTEGER,
},
typical_bpm_max: {
type: DataTypes.INTEGER,
},
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.projects, {
as: 'projects_primary_genre',
foreignKey: {
name: 'primary_genreId',
},
constraints: false,
});
db.genres.hasMany(db.songs, {
as: 'songs_genre',
foreignKey: {
name: 'genreId',
},
constraints: false,
});
db.genres.hasMany(db.generation_requests, {
as: 'generation_requests_target_genre',
foreignKey: {
name: 'target_genreId',
},
constraints: false,
});
db.genres.hasMany(db.vocal_processing_presets, {
as: 'vocal_processing_presets_recommended_genre',
foreignKey: {
name: 'recommended_genreId',
},
constraints: false,
});
db.genres.hasMany(db.mastering_presets, {
as: 'mastering_presets_genre',
foreignKey: {
name: 'genreId',
},
constraints: false,
});
db.genres.hasMany(db.marketplace_listings, {
as: 'marketplace_listings_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,124 @@
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 languages = sequelize.define(
'languages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
iso_code: {
type: DataTypes.TEXT,
},
is_supported: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
languages.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.languages.hasMany(db.songs, {
as: 'songs_vocal_language',
foreignKey: {
name: 'vocal_languageId',
},
constraints: false,
});
//end loop
db.languages.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.languages.belongsTo(db.users, {
as: 'createdBy',
});
db.languages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return languages;
};

View File

@ -0,0 +1,234 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const marketplace_listings = sequelize.define(
'marketplace_listings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
listing_type: {
type: DataTypes.ENUM,
values: [
"beat",
"stem_pack",
"preset_pack"
],
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
price: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.ENUM,
values: [
"ZAR",
"USD",
"EUR",
"GBP"
],
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"paused",
"sold_out",
"archived"
],
},
published_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
marketplace_listings.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.marketplace_listings.hasMany(db.marketplace_orders, {
as: 'marketplace_orders_listing',
foreignKey: {
name: 'listingId',
},
constraints: false,
});
//end loop
db.marketplace_listings.belongsTo(db.users, {
as: 'seller_user',
foreignKey: {
name: 'seller_userId',
},
constraints: false,
});
db.marketplace_listings.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.marketplace_listings.belongsTo(db.genres, {
as: 'genre',
foreignKey: {
name: 'genreId',
},
constraints: false,
});
db.marketplace_listings.belongsTo(db.assets, {
as: 'preview_asset',
foreignKey: {
name: 'preview_assetId',
},
constraints: false,
});
db.marketplace_listings.belongsTo(db.assets, {
as: 'deliverable_asset',
foreignKey: {
name: 'deliverable_assetId',
},
constraints: false,
});
db.marketplace_listings.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.marketplace_listings.belongsTo(db.users, {
as: 'createdBy',
});
db.marketplace_listings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return marketplace_listings;
};

View File

@ -0,0 +1,176 @@
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 marketplace_orders = sequelize.define(
'marketplace_orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.ENUM,
values: [
"ZAR",
"USD",
"EUR",
"GBP"
],
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"paid",
"fulfilled",
"refunded",
"canceled"
],
},
ordered_at: {
type: DataTypes.DATE,
},
fulfilled_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
marketplace_orders.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.marketplace_orders.belongsTo(db.marketplace_listings, {
as: 'listing',
foreignKey: {
name: 'listingId',
},
constraints: false,
});
db.marketplace_orders.belongsTo(db.users, {
as: 'buyer_user',
foreignKey: {
name: 'buyer_userId',
},
constraints: false,
});
db.marketplace_orders.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.marketplace_orders.belongsTo(db.users, {
as: 'createdBy',
});
db.marketplace_orders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return marketplace_orders;
};

View File

@ -0,0 +1,161 @@
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 mastering_presets = sequelize.define(
'mastering_presets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
target: {
type: DataTypes.ENUM,
values: [
"streaming",
"radio_broadcast",
"club_loud",
"genre_aware"
],
},
lufs_target: {
type: DataTypes.DECIMAL,
},
true_peak_db: {
type: DataTypes.DECIMAL,
},
is_default: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
mastering_presets.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.mastering_presets.hasMany(db.mastering_sessions, {
as: 'mastering_sessions_preset',
foreignKey: {
name: 'presetId',
},
constraints: false,
});
//end loop
db.mastering_presets.belongsTo(db.genres, {
as: 'genre',
foreignKey: {
name: 'genreId',
},
constraints: false,
});
db.mastering_presets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.mastering_presets.belongsTo(db.users, {
as: 'createdBy',
});
db.mastering_presets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return mastering_presets;
};

View File

@ -0,0 +1,182 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const mastering_sessions = sequelize.define(
'mastering_sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"completed",
"failed"
],
},
lufs_measured: {
type: DataTypes.DECIMAL,
},
true_peak_measured_db: {
type: DataTypes.DECIMAL,
},
started_at: {
type: DataTypes.DATE,
},
finished_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
mastering_sessions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.mastering_sessions.belongsTo(db.songs, {
as: 'song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.mastering_sessions.belongsTo(db.users, {
as: 'requested_user',
foreignKey: {
name: 'requested_userId',
},
constraints: false,
});
db.mastering_sessions.belongsTo(db.mastering_presets, {
as: 'preset',
foreignKey: {
name: 'presetId',
},
constraints: false,
});
db.mastering_sessions.belongsTo(db.assets, {
as: 'input_mix_asset',
foreignKey: {
name: 'input_mix_assetId',
},
constraints: false,
});
db.mastering_sessions.belongsTo(db.assets, {
as: 'result_master_asset',
foreignKey: {
name: 'result_master_assetId',
},
constraints: false,
});
db.mastering_sessions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.mastering_sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.mastering_sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return mastering_sessions;
};

View File

@ -0,0 +1,189 @@
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 mix_sessions = sequelize.define(
'mix_sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
mix_type: {
type: DataTypes.ENUM,
values: [
"auto_mix",
"assisted_mix"
],
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"completed",
"failed"
],
},
stereo_widening_amount: {
type: DataTypes.DECIMAL,
},
compression_amount: {
type: DataTypes.DECIMAL,
},
eq_amount: {
type: DataTypes.DECIMAL,
},
started_at: {
type: DataTypes.DATE,
},
finished_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
mix_sessions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.mix_sessions.belongsTo(db.songs, {
as: 'song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.mix_sessions.belongsTo(db.users, {
as: 'requested_user',
foreignKey: {
name: 'requested_userId',
},
constraints: false,
});
db.mix_sessions.belongsTo(db.assets, {
as: 'result_mix_asset',
foreignKey: {
name: 'result_mix_assetId',
},
constraints: false,
});
db.mix_sessions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.mix_sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.mix_sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return mix_sessions;
};

View File

@ -0,0 +1,275 @@
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.workspaces, {
as: 'workspaces_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.workspace_memberships, {
as: 'workspace_memberships_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.genres, {
as: 'genres_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.languages, {
as: 'languages_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.ai_models, {
as: 'ai_models_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.projects, {
as: 'projects_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.project_collaborations, {
as: 'project_collaborations_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.songs, {
as: 'songs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.song_metadata, {
as: 'song_metadata_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.assets, {
as: 'assets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.recording_sessions, {
as: 'recording_sessions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.tracks, {
as: 'tracks_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.arrangement_sections, {
as: 'arrangement_sections_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.generation_requests, {
as: 'generation_requests_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.vocal_processing_presets, {
as: 'vocal_processing_presets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.mastering_presets, {
as: 'mastering_presets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.mix_sessions, {
as: 'mix_sessions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.mastering_sessions, {
as: 'mastering_sessions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.exports, {
as: 'exports_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.cover_artworks, {
as: 'cover_artworks_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.marketplace_listings, {
as: 'marketplace_listings_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.marketplace_orders, {
as: 'marketplace_orders_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,91 @@
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,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 project_collaborations = sequelize.define(
'project_collaborations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
permission_level: {
type: DataTypes.ENUM,
values: [
"view",
"comment",
"edit",
"admin"
],
},
invited_at: {
type: DataTypes.DATE,
},
accepted_at: {
type: DataTypes.DATE,
},
invite_status: {
type: DataTypes.ENUM,
values: [
"pending",
"accepted",
"declined",
"revoked"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
project_collaborations.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.project_collaborations.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.project_collaborations.belongsTo(db.users, {
as: 'collaborator_user',
foreignKey: {
name: 'collaborator_userId',
},
constraints: false,
});
db.project_collaborations.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.project_collaborations.belongsTo(db.users, {
as: 'createdBy',
});
db.project_collaborations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return project_collaborations;
};

View File

@ -0,0 +1,267 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const projects = sequelize.define(
'projects',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"in_progress",
"ready_for_mix",
"ready_for_master",
"exported",
"archived"
],
},
target_bpm: {
type: DataTypes.INTEGER,
},
target_key: {
type: DataTypes.TEXT,
},
mood: {
type: DataTypes.ENUM,
values: [
"happy",
"sad",
"spiritual",
"energetic",
"romantic",
"chill",
"aggressive"
],
},
target_duration_seconds: {
type: DataTypes.INTEGER,
},
collaboration_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
last_opened_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
projects.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.projects.hasMany(db.project_collaborations, {
as: 'project_collaborations_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.projects.hasMany(db.songs, {
as: 'songs_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.projects.hasMany(db.assets, {
as: 'assets_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.projects.hasMany(db.recording_sessions, {
as: 'recording_sessions_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.projects.hasMany(db.generation_requests, {
as: 'generation_requests_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
//end loop
db.projects.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.projects.belongsTo(db.users, {
as: 'created_user',
foreignKey: {
name: 'created_userId',
},
constraints: false,
});
db.projects.belongsTo(db.genres, {
as: 'primary_genre',
foreignKey: {
name: 'primary_genreId',
},
constraints: false,
});
db.projects.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.projects.belongsTo(db.users, {
as: 'createdBy',
});
db.projects.belongsTo(db.users, {
as: 'updatedBy',
});
};
return projects;
};

View File

@ -0,0 +1,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 recording_sessions = sequelize.define(
'recording_sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"planned",
"recording",
"completed",
"abandoned"
],
},
started_at: {
type: DataTypes.DATE,
},
ended_at: {
type: DataTypes.DATE,
},
input_channels: {
type: DataTypes.INTEGER,
},
sample_rate_hz: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
recording_sessions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.recording_sessions.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.recording_sessions.belongsTo(db.songs, {
as: 'song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.recording_sessions.belongsTo(db.users, {
as: 'started_user',
foreignKey: {
name: 'started_userId',
},
constraints: false,
});
db.recording_sessions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.recording_sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.recording_sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return recording_sessions;
};

View File

@ -0,0 +1,134 @@
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,171 @@
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 song_metadata = sequelize.define(
'song_metadata',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
isrc: {
type: DataTypes.TEXT,
},
upc: {
type: DataTypes.TEXT,
},
release_title: {
type: DataTypes.TEXT,
},
release_date: {
type: DataTypes.DATE,
},
label_name: {
type: DataTypes.TEXT,
},
publisher: {
type: DataTypes.TEXT,
},
copyright_notice: {
type: DataTypes.TEXT,
},
distribution_status: {
type: DataTypes.ENUM,
values: [
"not_set",
"ready",
"submitted",
"distributed"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
song_metadata.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.song_metadata.belongsTo(db.songs, {
as: 'song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.song_metadata.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.song_metadata.belongsTo(db.users, {
as: 'createdBy',
});
db.song_metadata.belongsTo(db.users, {
as: 'updatedBy',
});
};
return song_metadata;
};

View File

@ -0,0 +1,279 @@
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 songs = sequelize.define(
'songs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
artist_display: {
type: DataTypes.TEXT,
},
bpm: {
type: DataTypes.INTEGER,
},
key_signature: {
type: DataTypes.TEXT,
},
mood: {
type: DataTypes.ENUM,
values: [
"happy",
"sad",
"spiritual",
"energetic",
"romantic",
"chill",
"aggressive"
],
},
duration_seconds: {
type: DataTypes.INTEGER,
},
explicit_content: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
lyrics: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
songs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.songs.hasMany(db.song_metadata, {
as: 'song_metadata_song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.songs.hasMany(db.assets, {
as: 'assets_song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.songs.hasMany(db.recording_sessions, {
as: 'recording_sessions_song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.songs.hasMany(db.tracks, {
as: 'tracks_song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.songs.hasMany(db.arrangement_sections, {
as: 'arrangement_sections_song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.songs.hasMany(db.generation_requests, {
as: 'generation_requests_song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.songs.hasMany(db.mix_sessions, {
as: 'mix_sessions_song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.songs.hasMany(db.mastering_sessions, {
as: 'mastering_sessions_song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.songs.hasMany(db.exports, {
as: 'exports_song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.songs.hasMany(db.cover_artworks, {
as: 'cover_artworks_song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
//end loop
db.songs.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.songs.belongsTo(db.genres, {
as: 'genre',
foreignKey: {
name: 'genreId',
},
constraints: false,
});
db.songs.belongsTo(db.languages, {
as: 'vocal_language',
foreignKey: {
name: 'vocal_languageId',
},
constraints: false,
});
db.songs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.songs.belongsTo(db.users, {
as: 'createdBy',
});
db.songs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return songs;
};

View File

@ -0,0 +1,223 @@
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 tracks = sequelize.define(
'tracks',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
track_type: {
type: DataTypes.ENUM,
values: [
"vocal",
"drums",
"bass",
"instrument",
"fx",
"bus",
"master"
],
},
instrument: {
type: DataTypes.ENUM,
values: [
"voice",
"piano",
"log_drum",
"synth",
"brass",
"guitar",
"traditional_drums",
"perc",
"pads",
"strings",
"other"
],
},
volume_db: {
type: DataTypes.DECIMAL,
},
pan: {
type: DataTypes.DECIMAL,
},
mute: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
solo: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tracks.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.tracks.belongsTo(db.songs, {
as: 'song',
foreignKey: {
name: 'songId',
},
constraints: false,
});
db.tracks.belongsTo(db.assets, {
as: 'source_asset',
foreignKey: {
name: 'source_assetId',
},
constraints: false,
});
db.tracks.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.tracks.belongsTo(db.users, {
as: 'createdBy',
});
db.tracks.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tracks;
};

View File

@ -0,0 +1,353 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const users = sequelize.define(
'users',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
firstName: {
type: DataTypes.TEXT,
},
lastName: {
type: DataTypes.TEXT,
},
phoneNumber: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
disabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
password: {
type: DataTypes.TEXT,
},
emailVerified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
emailVerificationToken: {
type: DataTypes.TEXT,
},
emailVerificationTokenExpiresAt: {
type: DataTypes.DATE,
},
passwordResetToken: {
type: DataTypes.TEXT,
},
passwordResetTokenExpiresAt: {
type: DataTypes.DATE,
},
provider: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
users.associate = (db) => {
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions_filter',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.users.hasMany(db.workspaces, {
as: 'workspaces_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.users.hasMany(db.workspace_memberships, {
as: 'workspace_memberships_member_user',
foreignKey: {
name: 'member_userId',
},
constraints: false,
});
db.users.hasMany(db.projects, {
as: 'projects_created_user',
foreignKey: {
name: 'created_userId',
},
constraints: false,
});
db.users.hasMany(db.project_collaborations, {
as: 'project_collaborations_collaborator_user',
foreignKey: {
name: 'collaborator_userId',
},
constraints: false,
});
db.users.hasMany(db.assets, {
as: 'assets_uploaded_user',
foreignKey: {
name: 'uploaded_userId',
},
constraints: false,
});
db.users.hasMany(db.recording_sessions, {
as: 'recording_sessions_started_user',
foreignKey: {
name: 'started_userId',
},
constraints: false,
});
db.users.hasMany(db.generation_requests, {
as: 'generation_requests_requested_user',
foreignKey: {
name: 'requested_userId',
},
constraints: false,
});
db.users.hasMany(db.mix_sessions, {
as: 'mix_sessions_requested_user',
foreignKey: {
name: 'requested_userId',
},
constraints: false,
});
db.users.hasMany(db.mastering_sessions, {
as: 'mastering_sessions_requested_user',
foreignKey: {
name: 'requested_userId',
},
constraints: false,
});
db.users.hasMany(db.exports, {
as: 'exports_requested_user',
foreignKey: {
name: 'requested_userId',
},
constraints: false,
});
db.users.hasMany(db.marketplace_listings, {
as: 'marketplace_listings_seller_user',
foreignKey: {
name: 'seller_userId',
},
constraints: false,
});
db.users.hasMany(db.marketplace_orders, {
as: 'marketplace_orders_buyer_user',
foreignKey: {
name: 'buyer_userId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

View File

@ -0,0 +1,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 vocal_processing_presets = sequelize.define(
'vocal_processing_presets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
preset_type: {
type: DataTypes.ENUM,
values: [
"pitch_correction",
"harmony_generation",
"layering",
"noise_reduction",
"de_essing",
"eq",
"full_chain"
],
},
description: {
type: DataTypes.TEXT,
},
intensity: {
type: DataTypes.DECIMAL,
},
is_default: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
vocal_processing_presets.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.vocal_processing_presets.belongsTo(db.genres, {
as: 'recommended_genre',
foreignKey: {
name: 'recommended_genreId',
},
constraints: false,
});
db.vocal_processing_presets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.vocal_processing_presets.belongsTo(db.users, {
as: 'createdBy',
});
db.vocal_processing_presets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return vocal_processing_presets;
};

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 workspace_memberships = sequelize.define(
'workspace_memberships',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
role: {
type: DataTypes.ENUM,
values: [
"owner",
"admin",
"editor",
"viewer"
],
},
joined_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,
},
);
workspace_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.workspace_memberships.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspace_memberships.belongsTo(db.users, {
as: 'member_user',
foreignKey: {
name: 'member_userId',
},
constraints: false,
});
db.workspace_memberships.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.workspace_memberships.belongsTo(db.users, {
as: 'createdBy',
});
db.workspace_memberships.belongsTo(db.users, {
as: 'updatedBy',
});
};
return workspace_memberships;
};

View File

@ -0,0 +1,203 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const workspaces = sequelize.define(
'workspaces',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
plan: {
type: DataTypes.ENUM,
values: [
"free",
"creator",
"pro",
"studio",
"enterprise"
],
},
plan_started_at: {
type: DataTypes.DATE,
},
plan_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,
},
);
workspaces.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.workspaces.hasMany(db.workspace_memberships, {
as: 'workspace_memberships_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.projects, {
as: 'projects_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.assets, {
as: 'assets_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.generation_requests, {
as: 'generation_requests_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.marketplace_listings, {
as: 'marketplace_listings_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
//end loop
db.workspaces.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.workspaces.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.workspaces.belongsTo(db.users, {
as: 'createdBy',
});
db.workspaces.belongsTo(db.users, {
as: 'updatedBy',
});
};
return workspaces;
};

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

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

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

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

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

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

@ -0,0 +1,235 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const organizationForAuthRoutes = require('./routes/organizationLogin');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const organizationsRoutes = require('./routes/organizations');
const workspacesRoutes = require('./routes/workspaces');
const workspace_membershipsRoutes = require('./routes/workspace_memberships');
const genresRoutes = require('./routes/genres');
const languagesRoutes = require('./routes/languages');
const ai_modelsRoutes = require('./routes/ai_models');
const projectsRoutes = require('./routes/projects');
const project_collaborationsRoutes = require('./routes/project_collaborations');
const songsRoutes = require('./routes/songs');
const song_metadataRoutes = require('./routes/song_metadata');
const assetsRoutes = require('./routes/assets');
const recording_sessionsRoutes = require('./routes/recording_sessions');
const tracksRoutes = require('./routes/tracks');
const arrangement_sectionsRoutes = require('./routes/arrangement_sections');
const generation_requestsRoutes = require('./routes/generation_requests');
const vocal_processing_presetsRoutes = require('./routes/vocal_processing_presets');
const mastering_presetsRoutes = require('./routes/mastering_presets');
const mix_sessionsRoutes = require('./routes/mix_sessions');
const mastering_sessionsRoutes = require('./routes/mastering_sessions');
const exportsRoutes = require('./routes/exports');
const cover_artworksRoutes = require('./routes/cover_artworks');
const marketplace_listingsRoutes = require('./routes/marketplace_listings');
const marketplace_ordersRoutes = require('./routes/marketplace_orders');
const getBaseUrl = (url) => {
if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url;
};
const options = {
definition: {
openapi: "3.0.0",
info: {
version: "1.0.0",
title: "SA AI Music Studio",
description: "SA AI Music Studio Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
},
servers: [
{
url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
description: "Development server",
}
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
},
responses: {
UnauthorizedError: {
description: "Access token is missing or invalid"
}
}
},
security: [{
bearerAuth: []
}]
},
apis: ["./src/routes/*.js"],
};
const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
next()
}, swaggerUI.serve, swaggerUI.setup(specs))
app.use(cors({origin: true}));
require('./auth/auth');
app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');
app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);
app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);
app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);
app.use('/api/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);
app.use('/api/workspaces', passport.authenticate('jwt', {session: false}), workspacesRoutes);
app.use('/api/workspace_memberships', passport.authenticate('jwt', {session: false}), workspace_membershipsRoutes);
app.use('/api/genres', passport.authenticate('jwt', {session: false}), genresRoutes);
app.use('/api/languages', passport.authenticate('jwt', {session: false}), languagesRoutes);
app.use('/api/ai_models', passport.authenticate('jwt', {session: false}), ai_modelsRoutes);
app.use('/api/projects', passport.authenticate('jwt', {session: false}), projectsRoutes);
app.use('/api/project_collaborations', passport.authenticate('jwt', {session: false}), project_collaborationsRoutes);
app.use('/api/songs', passport.authenticate('jwt', {session: false}), songsRoutes);
app.use('/api/song_metadata', passport.authenticate('jwt', {session: false}), song_metadataRoutes);
app.use('/api/assets', passport.authenticate('jwt', {session: false}), assetsRoutes);
app.use('/api/recording_sessions', passport.authenticate('jwt', {session: false}), recording_sessionsRoutes);
app.use('/api/tracks', passport.authenticate('jwt', {session: false}), tracksRoutes);
app.use('/api/arrangement_sections', passport.authenticate('jwt', {session: false}), arrangement_sectionsRoutes);
app.use('/api/generation_requests', passport.authenticate('jwt', {session: false}), generation_requestsRoutes);
app.use('/api/vocal_processing_presets', passport.authenticate('jwt', {session: false}), vocal_processing_presetsRoutes);
app.use('/api/mastering_presets', passport.authenticate('jwt', {session: false}), mastering_presetsRoutes);
app.use('/api/mix_sessions', passport.authenticate('jwt', {session: false}), mix_sessionsRoutes);
app.use('/api/mastering_sessions', passport.authenticate('jwt', {session: false}), mastering_sessionsRoutes);
app.use('/api/exports', passport.authenticate('jwt', {session: false}), exportsRoutes);
app.use('/api/cover_artworks', passport.authenticate('jwt', {session: false}), cover_artworksRoutes);
app.use('/api/marketplace_listings', passport.authenticate('jwt', {session: false}), marketplace_listingsRoutes);
app.use('/api/marketplace_orders', passport.authenticate('jwt', {session: false}), marketplace_ordersRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
app.use(
'/api/org-for-auth',
organizationForAuthRoutes,
);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
module.exports = app;

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

View File

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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