Initial version

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

1
backend/.env Normal file
View File

@ -0,0 +1 @@
PORT=8080

4
backend/.eslintignore Normal file
View File

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

15
backend/.eslintrc.cjs Normal file
View File

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

11
backend/.prettierrc Normal file
View File

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

7
backend/.sequelizerc Normal file
View File

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

23
backend/Dockerfile Normal file
View File

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

56
backend/README.md Normal file
View File

@ -0,0 +1,56 @@
#Event Media Platform - template backend,
#### Run App on local machine:
##### Install local dependencies:
- `yarn install`
------------
##### Adjust local db:
###### 1. Install postgres:
- MacOS:
- `brew install postgres`
- Ubuntu:
- `sudo apt update`
- `sudo apt install postgresql postgresql-contrib`
###### 2. Create db and admin user:
- Before run and test connection, make sure you have created a database as described in the above configuration. You can use the `psql` command to create a user and database.
- `psql postgres --u postgres`
- Next, type this command for creating a new user with password then give access for creating the database.
- `postgres-# CREATE ROLE admin WITH LOGIN PASSWORD 'admin_pass';`
- `postgres-# ALTER ROLE admin CREATEDB;`
- Quit `psql` then log in again using the new user that previously created.
- `postgres-# \q`
- `psql postgres -U admin`
- Type this command to creating a new database.
- `postgres=> CREATE DATABASE db_event_media_platform;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_event_media_platform TO admin;`
- `postgres=> \q`
------------
#### Api Documentation (Swagger)
http://localhost:8080/api-docs (local host)
http://host_name/api-docs
------------
##### Setup database tables or update after schema change
- `yarn db:migrate`
##### Seed the initial data (admin accounts, relevant for the first setup):
- `yarn db:seed`
##### Start build:
- `yarn start`

56
backend/package.json Normal file
View File

@ -0,0 +1,56 @@
{
"name": "eventmediaplatform",
"description": "Event Media Platform - template backend",
"scripts": {
"start": "npm run db:migrate && npm run db:seed && npm run watch",
"lint": "eslint . --ext .js",
"db:migrate": "sequelize-cli db:migrate",
"db:seed": "sequelize-cli db:seed:all",
"db:drop": "sequelize-cli db:drop",
"db:create": "sequelize-cli db:create",
"watch": "node watcher.js"
},
"dependencies": {
"@google-cloud/storage": "^5.18.2",
"axios": "^1.6.7",
"bcrypt": "5.1.1",
"chokidar": "^4.0.3",
"cors": "2.8.5",
"csv-parser": "^3.0.0",
"express": "4.18.2",
"formidable": "1.2.2",
"helmet": "4.1.1",
"json2csv": "^5.0.7",
"jsonwebtoken": "8.5.1",
"lodash": "4.17.21",
"moment": "2.30.1",
"multer": "^1.4.4",
"mysql2": "2.2.5",
"nodemailer": "6.9.9",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
"passport-jwt": "^4.0.1",
"passport-microsoft": "^0.1.0",
"pg": "8.4.1",
"pg-hstore": "2.3.4",
"sequelize": "6.35.2",
"sequelize-json-schema": "^2.1.1",
"sqlite": "4.0.15",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0",
"tedious": "^18.2.4"
},
"engines": {
"node": ">=18"
},
"private": true,
"devDependencies": {
"cross-env": "7.0.3",
"eslint": "^8.23.1",
"eslint-plugin-import": "^2.29.1",
"mocha": "8.1.3",
"node-mocks-http": "1.9.0",
"nodemon": "2.0.5",
"sequelize-cli": "6.6.2"
}
}

View File

@ -0,0 +1,484 @@
"use strict";
const fs = require("fs");
const path = require("path");
const http = require("http");
const https = require("https");
const { URL } = require("url");
let CONFIG_CACHE = null;
class LocalAIApi {
static createResponse(params, options) {
return createResponse(params, options);
}
static request(pathValue, payload, options) {
return request(pathValue, payload, options);
}
static fetchStatus(aiRequestId, options) {
return fetchStatus(aiRequestId, options);
}
static awaitResponse(aiRequestId, options) {
return awaitResponse(aiRequestId, options);
}
static extractText(response) {
return extractText(response);
}
static decodeJsonFromResponse(response) {
return decodeJsonFromResponse(response);
}
}
async function createResponse(params, options = {}) {
const payload = { ...(params || {}) };
if (!Array.isArray(payload.input) || payload.input.length === 0) {
return {
success: false,
error: "input_missing",
message: 'Parameter "input" is required and must be a non-empty array.',
};
}
const cfg = config();
if (!payload.model) {
payload.model = cfg.defaultModel;
}
const initial = await request(options.path, payload, options);
if (!initial.success) {
return initial;
}
const data = initial.data;
if (data && typeof data === "object" && data.ai_request_id) {
const pollTimeout = Number(options.poll_timeout ?? 300);
const pollInterval = Number(options.poll_interval ?? 5);
return await awaitResponse(data.ai_request_id, {
interval: pollInterval,
timeout: pollTimeout,
headers: options.headers,
timeout_per_call: options.timeout,
verify_tls: options.verify_tls,
});
}
return initial;
}
async function request(pathValue, payload = {}, options = {}) {
const cfg = config();
const resolvedPath = pathValue || options.path || cfg.responsesPath;
if (!resolvedPath) {
return {
success: false,
error: "project_id_missing",
message: "PROJECT_ID is not defined; cannot resolve AI proxy endpoint.",
};
}
if (!cfg.projectUuid) {
return {
success: false,
error: "project_uuid_missing",
message: "PROJECT_UUID is not defined; aborting AI request.",
};
}
const bodyPayload = { ...(payload || {}) };
if (!bodyPayload.project_uuid) {
bodyPayload.project_uuid = cfg.projectUuid;
}
const url = buildUrl(resolvedPath, cfg.baseUrl);
const timeout = resolveTimeout(options.timeout, cfg.timeout);
const verifyTls = resolveVerifyTls(options.verify_tls, cfg.verifyTls);
const headers = {
Accept: "application/json",
"Content-Type": "application/json",
[cfg.projectHeader]: cfg.projectUuid,
};
if (Array.isArray(options.headers)) {
for (const header of options.headers) {
if (typeof header === "string" && header.includes(":")) {
const [name, value] = header.split(":", 2);
headers[name.trim()] = value.trim();
}
}
}
const body = JSON.stringify(bodyPayload);
return sendRequest(url, "POST", body, headers, timeout, verifyTls);
}
async function fetchStatus(aiRequestId, options = {}) {
const cfg = config();
if (!cfg.projectUuid) {
return {
success: false,
error: "project_uuid_missing",
message: "PROJECT_UUID is not defined; aborting status check.",
};
}
const statusPath = resolveStatusPath(aiRequestId, cfg);
const url = buildUrl(statusPath, cfg.baseUrl);
const timeout = resolveTimeout(options.timeout, cfg.timeout);
const verifyTls = resolveVerifyTls(options.verify_tls, cfg.verifyTls);
const headers = {
Accept: "application/json",
[cfg.projectHeader]: cfg.projectUuid,
};
if (Array.isArray(options.headers)) {
for (const header of options.headers) {
if (typeof header === "string" && header.includes(":")) {
const [name, value] = header.split(":", 2);
headers[name.trim()] = value.trim();
}
}
}
return sendRequest(url, "GET", null, headers, timeout, verifyTls);
}
async function awaitResponse(aiRequestId, options = {}) {
const timeout = Number(options.timeout ?? 300);
const interval = Math.max(Number(options.interval ?? 5), 1);
const deadline = Date.now() + Math.max(timeout, interval) * 1000;
while (true) {
const statusResp = await fetchStatus(aiRequestId, {
headers: options.headers,
timeout: options.timeout_per_call,
verify_tls: options.verify_tls,
});
if (statusResp.success) {
const data = statusResp.data || {};
if (data && typeof data === "object") {
if (data.status === "success") {
return {
success: true,
status: 200,
data: data.response || data,
};
}
if (data.status === "failed") {
return {
success: false,
status: 500,
error: String(data.error || "AI request failed"),
data,
};
}
}
} else {
return statusResp;
}
if (Date.now() >= deadline) {
return {
success: false,
error: "timeout",
message: "Timed out waiting for AI response.",
};
}
await sleep(interval * 1000);
}
}
function extractText(response) {
const payload = response && typeof response === "object" ? response.data || response : null;
if (!payload || typeof payload !== "object") {
return "";
}
if (Array.isArray(payload.output)) {
let combined = "";
for (const item of payload.output) {
if (!item || !Array.isArray(item.content)) {
continue;
}
for (const block of item.content) {
if (
block &&
typeof block === "object" &&
block.type === "output_text" &&
typeof block.text === "string" &&
block.text.length > 0
) {
combined += block.text;
}
}
}
if (combined) {
return combined;
}
}
if (
payload.choices &&
payload.choices[0] &&
payload.choices[0].message &&
typeof payload.choices[0].message.content === "string"
) {
return payload.choices[0].message.content;
}
return "";
}
function decodeJsonFromResponse(response) {
const text = extractText(response);
if (!text) {
throw new Error("No text found in AI response.");
}
const parsed = parseJson(text);
if (parsed.ok && parsed.value && typeof parsed.value === "object") {
return parsed.value;
}
const stripped = stripJsonFence(text);
if (stripped !== text) {
const parsedStripped = parseJson(stripped);
if (parsedStripped.ok && parsedStripped.value && typeof parsedStripped.value === "object") {
return parsedStripped.value;
}
throw new Error(`JSON parse failed after stripping fences: ${parsedStripped.error}`);
}
throw new Error(`JSON parse failed: ${parsed.error}`);
}
function config() {
if (CONFIG_CACHE) {
return CONFIG_CACHE;
}
ensureEnvLoaded();
const baseUrl = process.env.AI_PROXY_BASE_URL || "https://flatlogic.com";
const projectId = process.env.PROJECT_ID || null;
let responsesPath = process.env.AI_RESPONSES_PATH || null;
if (!responsesPath && projectId) {
responsesPath = `/projects/${projectId}/ai-request`;
}
const timeout = resolveTimeout(process.env.AI_TIMEOUT, 30);
const verifyTls = resolveVerifyTls(process.env.AI_VERIFY_TLS, true);
CONFIG_CACHE = {
baseUrl,
responsesPath,
projectId,
projectUuid: process.env.PROJECT_UUID || null,
projectHeader: process.env.AI_PROJECT_HEADER || "project-uuid",
defaultModel: process.env.AI_DEFAULT_MODEL || "gpt-5-mini",
timeout,
verifyTls,
};
return CONFIG_CACHE;
}
function buildUrl(pathValue, baseUrl) {
const trimmed = String(pathValue || "").trim();
if (trimmed === "") {
return baseUrl;
}
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
return trimmed;
}
if (trimmed.startsWith("/")) {
return `${baseUrl}${trimmed}`;
}
return `${baseUrl}/${trimmed}`;
}
function resolveStatusPath(aiRequestId, cfg) {
const basePath = (cfg.responsesPath || "").replace(/\/+$/, "");
if (!basePath) {
return `/ai-request/${encodeURIComponent(String(aiRequestId))}/status`;
}
const normalized = basePath.endsWith("/ai-request") ? basePath : `${basePath}/ai-request`;
return `${normalized}/${encodeURIComponent(String(aiRequestId))}/status`;
}
function sendRequest(urlString, method, body, headers, timeoutSeconds, verifyTls) {
return new Promise((resolve) => {
let targetUrl;
try {
targetUrl = new URL(urlString);
} catch (err) {
resolve({
success: false,
error: "invalid_url",
message: err.message,
});
return;
}
const isHttps = targetUrl.protocol === "https:";
const requestFn = isHttps ? https.request : http.request;
const options = {
protocol: targetUrl.protocol,
hostname: targetUrl.hostname,
port: targetUrl.port || (isHttps ? 443 : 80),
path: `${targetUrl.pathname}${targetUrl.search}`,
method: method.toUpperCase(),
headers,
timeout: Math.max(Number(timeoutSeconds || 30), 1) * 1000,
};
if (isHttps) {
options.rejectUnauthorized = Boolean(verifyTls);
}
const req = requestFn(options, (res) => {
let responseBody = "";
res.setEncoding("utf8");
res.on("data", (chunk) => {
responseBody += chunk;
});
res.on("end", () => {
const status = res.statusCode || 0;
const parsed = parseJson(responseBody);
const payload = parsed.ok ? parsed.value : responseBody;
if (status >= 200 && status < 300) {
const result = {
success: true,
status,
data: payload,
};
if (!parsed.ok) {
result.json_error = parsed.error;
}
resolve(result);
return;
}
const errorMessage =
parsed.ok && payload && typeof payload === "object"
? String(payload.error || payload.message || "AI proxy request failed")
: String(responseBody || "AI proxy request failed");
resolve({
success: false,
status,
error: errorMessage,
response: payload,
json_error: parsed.ok ? undefined : parsed.error,
});
});
});
req.on("timeout", () => {
req.destroy(new Error("request_timeout"));
});
req.on("error", (err) => {
resolve({
success: false,
error: "request_failed",
message: err.message,
});
});
if (body) {
req.write(body);
}
req.end();
});
}
function parseJson(value) {
if (typeof value !== "string" || value.trim() === "") {
return { ok: false, error: "empty_response" };
}
try {
return { ok: true, value: JSON.parse(value) };
} catch (err) {
return { ok: false, error: err.message };
}
}
function stripJsonFence(text) {
const trimmed = text.trim();
if (trimmed.startsWith("```json")) {
return trimmed.replace(/^```json/, "").replace(/```$/, "").trim();
}
if (trimmed.startsWith("```")) {
return trimmed.replace(/^```/, "").replace(/```$/, "").trim();
}
return text;
}
function resolveTimeout(value, fallback) {
const parsed = Number.parseInt(String(value ?? fallback), 10);
return Number.isNaN(parsed) ? Number(fallback) : parsed;
}
function resolveVerifyTls(value, fallback) {
if (value === undefined || value === null) {
return Boolean(fallback);
}
return String(value).toLowerCase() !== "false" && String(value) !== "0";
}
function ensureEnvLoaded() {
if (process.env.PROJECT_UUID && process.env.PROJECT_ID) {
return;
}
const envPath = path.resolve(__dirname, "../../../../.env");
if (!fs.existsSync(envPath)) {
return;
}
let content;
try {
content = fs.readFileSync(envPath, "utf8");
} catch (err) {
throw new Error(`Failed to read executor .env: ${err.message}`);
}
for (const line of content.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#") || !trimmed.includes("=")) {
continue;
}
const [rawKey, ...rest] = trimmed.split("=");
const key = rawKey.trim();
if (!key) {
continue;
}
const value = rest.join("=").trim().replace(/^['"]|['"]$/g, "");
if (!process.env[key]) {
process.env[key] = value;
}
}
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
module.exports = {
LocalAIApi,
createResponse,
request,
fetchStatus,
awaitResponse,
extractText,
decodeJsonFromResponse,
};

68
backend/src/auth/auth.js Normal file
View File

@ -0,0 +1,68 @@
const config = require('../config');
const providers = config.providers;
const helpers = require('../helpers');
const db = require('../db/models');
const passport = require('passport');
const JWTstrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJwt;
const GoogleStrategy = require('passport-google-oauth2').Strategy;
const MicrosoftStrategy = require('passport-microsoft').Strategy;
const UsersDBApi = require('../db/api/users');
passport.use(new JWTstrategy({
passReqToCallback: true,
secretOrKey: config.secret_key,
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken()
}, async (req, token, done) => {
try {
const user = await UsersDBApi.findBy( {email: token.user.email});
if (user && user.disabled) {
return done (new Error(`User '${user.email}' is disabled`));
}
req.currentUser = user;
return done(null, user);
} catch (error) {
done(error);
}
}));
passport.use(new GoogleStrategy({
clientID: config.google.clientId,
clientSecret: config.google.clientSecret,
callbackURL: config.apiUrl + '/auth/signin/google/callback',
passReqToCallback: true
},
function (request, accessToken, refreshToken, profile, done) {
socialStrategy(profile.email, profile, providers.GOOGLE, done);
}
));
passport.use(new MicrosoftStrategy({
clientID: config.microsoft.clientId,
clientSecret: config.microsoft.clientSecret,
callbackURL: config.apiUrl + '/auth/signin/microsoft/callback',
passReqToCallback: true
},
function (request, accessToken, refreshToken, profile, done) {
const email = profile._json.mail || profile._json.userPrincipalName;
socialStrategy(email, profile, providers.MICROSOFT, done);
}
));
function socialStrategy(email, profile, provider, done) {
db.users.findOrCreate({where: {email, provider}}).then(([user, created]) => {
const body = {
id: user.id,
email: user.email,
name: profile.displayName,
};
const token = helpers.jwtSign({user: body});
return done(null, {token});
});
}

81
backend/src/config.js Normal file
View File

@ -0,0 +1,81 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "1b28307c",
user_pass: "f3f85dd375f6",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '1b28307c-6488-49a8-a56b-f3f85dd375f6',
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: 'Event Media Platform <app@flatlogic.app>',
host: 'email-smtp.us-east-1.amazonaws.com',
port: 587,
auth: {
user: process.env.EMAIL_USER || '',
pass: process.env.EMAIL_PASS,
},
tls: {
rejectUnauthorized: false
}
},
roles: {
super_admin: 'Super Administrator',
admin: 'Administrator',
user: 'Event Viewer',
},
project_uuid: '1b28307c-6488-49a8-a56b-f3f85dd375f6',
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 = 'City lights through glass prism';
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,619 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Access_rulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const access_rules = await db.access_rules.create(
{
id: data.id || undefined,
subject_type: data.subject_type
||
null
,
permission: data.permission
||
null
,
expires_at: data.expires_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await access_rules.setAlbum( data.album || null, {
transaction,
});
await access_rules.setRole( data.role || null, {
transaction,
});
await access_rules.setUser( data.user || null, {
transaction,
});
await access_rules.setMembership( data.membership || null, {
transaction,
});
await access_rules.setOrganizations( data.organizations || null, {
transaction,
});
return access_rules;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const access_rulesData = data.map((item, index) => ({
id: item.id || undefined,
subject_type: item.subject_type
||
null
,
permission: item.permission
||
null
,
expires_at: item.expires_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const access_rules = await db.access_rules.bulkCreate(access_rulesData, { transaction });
// For each item created, replace relation files
return access_rules;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const access_rules = await db.access_rules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.subject_type !== undefined) updatePayload.subject_type = data.subject_type;
if (data.permission !== undefined) updatePayload.permission = data.permission;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
updatePayload.updatedById = currentUser.id;
await access_rules.update(updatePayload, {transaction});
if (data.album !== undefined) {
await access_rules.setAlbum(
data.album,
{ transaction }
);
}
if (data.role !== undefined) {
await access_rules.setRole(
data.role,
{ transaction }
);
}
if (data.user !== undefined) {
await access_rules.setUser(
data.user,
{ transaction }
);
}
if (data.membership !== undefined) {
await access_rules.setMembership(
data.membership,
{ transaction }
);
}
if (data.organizations !== undefined) {
await access_rules.setOrganizations(
data.organizations,
{ transaction }
);
}
return access_rules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const access_rules = await db.access_rules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of access_rules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of access_rules) {
await record.destroy({transaction});
}
});
return access_rules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const access_rules = await db.access_rules.findByPk(id, options);
await access_rules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await access_rules.destroy({
transaction
});
return access_rules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const access_rules = await db.access_rules.findOne(
{ where },
{ transaction },
);
if (!access_rules) {
return access_rules;
}
const output = access_rules.get({plain: true});
output.album = await access_rules.getAlbum({
transaction
});
output.role = await access_rules.getRole({
transaction
});
output.user = await access_rules.getUser({
transaction
});
output.membership = await access_rules.getMembership({
transaction
});
output.organizations = await access_rules.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.albums,
as: 'album',
where: filter.album ? {
[Op.or]: [
{ id: { [Op.in]: filter.album.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.album.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.roles,
as: 'role',
where: filter.role ? {
[Op.or]: [
{ id: { [Op.in]: filter.role.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.role.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.memberships,
as: 'membership',
where: filter.membership ? {
[Op.or]: [
{ id: { [Op.in]: filter.membership.split('|').map(term => Utils.uuid(term)) } },
{
status: {
[Op.or]: filter.membership.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.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.subject_type) {
where = {
...where,
subject_type: filter.subject_type,
};
}
if (filter.permission) {
where = {
...where,
permission: filter.permission,
};
}
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.access_rules.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'access_rules',
'permission',
query,
),
],
};
}
const records = await db.access_rules.findAll({
attributes: [ 'id', 'permission' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['permission', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.permission,
}));
}
};

View File

@ -0,0 +1,549 @@
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_captionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_captions = await db.ai_captions.create(
{
id: data.id || undefined,
caption_text: data.caption_text
||
null
,
confidence: data.confidence
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_captions.setMedia_item( data.media_item || null, {
transaction,
});
await ai_captions.setAi_model( data.ai_model || null, {
transaction,
});
await ai_captions.setOrganizations( data.organizations || null, {
transaction,
});
return ai_captions;
}
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_captionsData = data.map((item, index) => ({
id: item.id || undefined,
caption_text: item.caption_text
||
null
,
confidence: item.confidence
||
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 ai_captions = await db.ai_captions.bulkCreate(ai_captionsData, { transaction });
// For each item created, replace relation files
return ai_captions;
}
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_captions = await db.ai_captions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.caption_text !== undefined) updatePayload.caption_text = data.caption_text;
if (data.confidence !== undefined) updatePayload.confidence = data.confidence;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await ai_captions.update(updatePayload, {transaction});
if (data.media_item !== undefined) {
await ai_captions.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.ai_model !== undefined) {
await ai_captions.setAi_model(
data.ai_model,
{ transaction }
);
}
if (data.organizations !== undefined) {
await ai_captions.setOrganizations(
data.organizations,
{ transaction }
);
}
return ai_captions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_captions = await db.ai_captions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ai_captions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ai_captions) {
await record.destroy({transaction});
}
});
return ai_captions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_captions = await db.ai_captions.findByPk(id, options);
await ai_captions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ai_captions.destroy({
transaction
});
return ai_captions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ai_captions = await db.ai_captions.findOne(
{ where },
{ transaction },
);
if (!ai_captions) {
return ai_captions;
}
const output = ai_captions.get({plain: true});
output.media_item = await ai_captions.getMedia_item({
transaction
});
output.ai_model = await ai_captions.getAi_model({
transaction
});
output.organizations = await ai_captions.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.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.ai_models,
as: 'ai_model',
where: filter.ai_model ? {
[Op.or]: [
{ id: { [Op.in]: filter.ai_model.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.ai_model.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.caption_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_captions',
'caption_text',
filter.caption_text,
),
};
}
if (filter.confidenceRange) {
const [start, end] = filter.confidenceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
confidence: {
...where.confidence,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
confidence: {
...where.confidence,
[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.ai_captions.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_captions',
'caption_text',
query,
),
],
};
}
const records = await db.ai_captions.findAll({
attributes: [ 'id', 'caption_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['caption_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.caption_text,
}));
}
};

View File

@ -0,0 +1,631 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Ai_embeddingsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_embeddings = await db.ai_embeddings.create(
{
id: data.id || undefined,
vector_ref: data.vector_ref
||
null
,
dimensions: data.dimensions
||
null
,
embedding_type: data.embedding_type
||
null
,
quality_score: data.quality_score
||
null
,
indexed_at: data.indexed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_embeddings.setMedia_item( data.media_item || null, {
transaction,
});
await ai_embeddings.setAi_model( data.ai_model || null, {
transaction,
});
await ai_embeddings.setOrganizations( data.organizations || null, {
transaction,
});
return ai_embeddings;
}
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_embeddingsData = data.map((item, index) => ({
id: item.id || undefined,
vector_ref: item.vector_ref
||
null
,
dimensions: item.dimensions
||
null
,
embedding_type: item.embedding_type
||
null
,
quality_score: item.quality_score
||
null
,
indexed_at: item.indexed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ai_embeddings = await db.ai_embeddings.bulkCreate(ai_embeddingsData, { transaction });
// For each item created, replace relation files
return ai_embeddings;
}
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_embeddings = await db.ai_embeddings.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.vector_ref !== undefined) updatePayload.vector_ref = data.vector_ref;
if (data.dimensions !== undefined) updatePayload.dimensions = data.dimensions;
if (data.embedding_type !== undefined) updatePayload.embedding_type = data.embedding_type;
if (data.quality_score !== undefined) updatePayload.quality_score = data.quality_score;
if (data.indexed_at !== undefined) updatePayload.indexed_at = data.indexed_at;
updatePayload.updatedById = currentUser.id;
await ai_embeddings.update(updatePayload, {transaction});
if (data.media_item !== undefined) {
await ai_embeddings.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.ai_model !== undefined) {
await ai_embeddings.setAi_model(
data.ai_model,
{ transaction }
);
}
if (data.organizations !== undefined) {
await ai_embeddings.setOrganizations(
data.organizations,
{ transaction }
);
}
return ai_embeddings;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_embeddings = await db.ai_embeddings.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ai_embeddings) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ai_embeddings) {
await record.destroy({transaction});
}
});
return ai_embeddings;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_embeddings = await db.ai_embeddings.findByPk(id, options);
await ai_embeddings.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ai_embeddings.destroy({
transaction
});
return ai_embeddings;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ai_embeddings = await db.ai_embeddings.findOne(
{ where },
{ transaction },
);
if (!ai_embeddings) {
return ai_embeddings;
}
const output = ai_embeddings.get({plain: true});
output.face_detections_face_embedding = await ai_embeddings.getFace_detections_face_embedding({
transaction
});
output.selfie_references_selfie_embedding = await ai_embeddings.getSelfie_references_selfie_embedding({
transaction
});
output.media_item = await ai_embeddings.getMedia_item({
transaction
});
output.ai_model = await ai_embeddings.getAi_model({
transaction
});
output.organizations = await ai_embeddings.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.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.ai_models,
as: 'ai_model',
where: filter.ai_model ? {
[Op.or]: [
{ id: { [Op.in]: filter.ai_model.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.ai_model.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.vector_ref) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_embeddings',
'vector_ref',
filter.vector_ref,
),
};
}
if (filter.dimensionsRange) {
const [start, end] = filter.dimensionsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
dimensions: {
...where.dimensions,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
dimensions: {
...where.dimensions,
[Op.lte]: end,
},
};
}
}
if (filter.quality_scoreRange) {
const [start, end] = filter.quality_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quality_score: {
...where.quality_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quality_score: {
...where.quality_score,
[Op.lte]: end,
},
};
}
}
if (filter.indexed_atRange) {
const [start, end] = filter.indexed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
indexed_at: {
...where.indexed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
indexed_at: {
...where.indexed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.embedding_type) {
where = {
...where,
embedding_type: filter.embedding_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.ai_embeddings.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_embeddings',
'vector_ref',
query,
),
],
};
}
const records = await db.ai_embeddings.findAll({
attributes: [ 'id', 'vector_ref' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['vector_ref', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.vector_ref,
}));
}
};

View File

@ -0,0 +1,522 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class 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
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_models.setOrganization(currentUser.organization.id || 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
,
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 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.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await ai_models.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await ai_models.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ 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.ai_embeddings_ai_model = await ai_models.getAi_embeddings_ai_model({
transaction
});
output.face_detections_ai_model = await ai_models.getFace_detections_ai_model({
transaction
});
output.selfie_references_ai_model = await ai_models.getSelfie_references_ai_model({
transaction
});
output.ai_captions_ai_model = await ai_models.getAi_captions_ai_model({
transaction
});
output.organization = await ai_models.getOrganization({
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: 'organization',
},
];
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.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[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,545 @@
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 Album_collaboratorsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const album_collaborators = await db.album_collaborators.create(
{
id: data.id || undefined,
role: data.role
||
null
,
status: data.status
||
null
,
invited_at: data.invited_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await album_collaborators.setAlbum( data.album || null, {
transaction,
});
await album_collaborators.setUser( data.user || null, {
transaction,
});
await album_collaborators.setOrganizations( data.organizations || null, {
transaction,
});
return album_collaborators;
}
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 album_collaboratorsData = data.map((item, index) => ({
id: item.id || undefined,
role: item.role
||
null
,
status: item.status
||
null
,
invited_at: item.invited_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const album_collaborators = await db.album_collaborators.bulkCreate(album_collaboratorsData, { transaction });
// For each item created, replace relation files
return album_collaborators;
}
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 album_collaborators = await db.album_collaborators.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.role !== undefined) updatePayload.role = data.role;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.invited_at !== undefined) updatePayload.invited_at = data.invited_at;
updatePayload.updatedById = currentUser.id;
await album_collaborators.update(updatePayload, {transaction});
if (data.album !== undefined) {
await album_collaborators.setAlbum(
data.album,
{ transaction }
);
}
if (data.user !== undefined) {
await album_collaborators.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await album_collaborators.setOrganizations(
data.organizations,
{ transaction }
);
}
return album_collaborators;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const album_collaborators = await db.album_collaborators.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of album_collaborators) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of album_collaborators) {
await record.destroy({transaction});
}
});
return album_collaborators;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const album_collaborators = await db.album_collaborators.findByPk(id, options);
await album_collaborators.update({
deletedBy: currentUser.id
}, {
transaction,
});
await album_collaborators.destroy({
transaction
});
return album_collaborators;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const album_collaborators = await db.album_collaborators.findOne(
{ where },
{ transaction },
);
if (!album_collaborators) {
return album_collaborators;
}
const output = album_collaborators.get({plain: true});
output.album = await album_collaborators.getAlbum({
transaction
});
output.user = await album_collaborators.getUser({
transaction
});
output.organizations = await album_collaborators.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.albums,
as: 'album',
where: filter.album ? {
[Op.or]: [
{ id: { [Op.in]: filter.album.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.album.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.role) {
where = {
...where,
role: filter.role,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.album_collaborators.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(
'album_collaborators',
'role',
query,
),
],
};
}
const records = await db.album_collaborators.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,890 @@
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 AlbumsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const albums = await db.albums.create(
{
id: data.id || undefined,
title: data.title
||
null
,
description: data.description
||
null
,
privacy: data.privacy
||
null
,
collaboration_mode: data.collaboration_mode
||
null
,
allow_downloads: data.allow_downloads
||
false
,
allow_comments: data.allow_comments
||
false
,
allow_likes: data.allow_likes
||
false
,
allow_tagging: data.allow_tagging
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await albums.setEvent( data.event || null, {
transaction,
});
await albums.setOwner( data.owner || null, {
transaction,
});
await albums.setOrganizations( data.organizations || null, {
transaction,
});
await albums.setCollaborators(data.collaborators || [], {
transaction,
});
await albums.setAccess_rules(data.access_rules || [], {
transaction,
});
await albums.setShares(data.shares || [], {
transaction,
});
await albums.setStories(data.stories || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.albums.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: albums.id,
},
data.cover_image,
options,
);
return albums;
}
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 albumsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
description: item.description
||
null
,
privacy: item.privacy
||
null
,
collaboration_mode: item.collaboration_mode
||
null
,
allow_downloads: item.allow_downloads
||
false
,
allow_comments: item.allow_comments
||
false
,
allow_likes: item.allow_likes
||
false
,
allow_tagging: item.allow_tagging
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const albums = await db.albums.bulkCreate(albumsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < albums.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.albums.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: albums[i].id,
},
data[i].cover_image,
options,
);
}
return albums;
}
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 albums = await db.albums.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.privacy !== undefined) updatePayload.privacy = data.privacy;
if (data.collaboration_mode !== undefined) updatePayload.collaboration_mode = data.collaboration_mode;
if (data.allow_downloads !== undefined) updatePayload.allow_downloads = data.allow_downloads;
if (data.allow_comments !== undefined) updatePayload.allow_comments = data.allow_comments;
if (data.allow_likes !== undefined) updatePayload.allow_likes = data.allow_likes;
if (data.allow_tagging !== undefined) updatePayload.allow_tagging = data.allow_tagging;
updatePayload.updatedById = currentUser.id;
await albums.update(updatePayload, {transaction});
if (data.event !== undefined) {
await albums.setEvent(
data.event,
{ transaction }
);
}
if (data.owner !== undefined) {
await albums.setOwner(
data.owner,
{ transaction }
);
}
if (data.organizations !== undefined) {
await albums.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.collaborators !== undefined) {
await albums.setCollaborators(data.collaborators, { transaction });
}
if (data.access_rules !== undefined) {
await albums.setAccess_rules(data.access_rules, { transaction });
}
if (data.shares !== undefined) {
await albums.setShares(data.shares, { transaction });
}
if (data.stories !== undefined) {
await albums.setStories(data.stories, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.albums.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: albums.id,
},
data.cover_image,
options,
);
return albums;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const albums = await db.albums.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of albums) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of albums) {
await record.destroy({transaction});
}
});
return albums;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const albums = await db.albums.findByPk(id, options);
await albums.update({
deletedBy: currentUser.id
}, {
transaction,
});
await albums.destroy({
transaction
});
return albums;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const albums = await db.albums.findOne(
{ where },
{ transaction },
);
if (!albums) {
return albums;
}
const output = albums.get({plain: true});
output.events_default_album = await albums.getEvents_default_album({
transaction
});
output.album_collaborators_album = await albums.getAlbum_collaborators_album({
transaction
});
output.access_rules_album = await albums.getAccess_rules_album({
transaction
});
output.media_items_album = await albums.getMedia_items_album({
transaction
});
output.upload_sessions_album = await albums.getUpload_sessions_album({
transaction
});
output.notifications_album = await albums.getNotifications_album({
transaction
});
output.shares_album = await albums.getShares_album({
transaction
});
output.stories_album = await albums.getStories_album({
transaction
});
output.analytics_events_album = await albums.getAnalytics_events_album({
transaction
});
output.event = await albums.getEvent({
transaction
});
output.owner = await albums.getOwner({
transaction
});
output.cover_image = await albums.getCover_image({
transaction
});
output.collaborators = await albums.getCollaborators({
transaction
});
output.access_rules = await albums.getAccess_rules({
transaction
});
output.shares = await albums.getShares({
transaction
});
output.stories = await albums.getStories({
transaction
});
output.organizations = await albums.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.events,
as: 'event',
where: filter.event ? {
[Op.or]: [
{ id: { [Op.in]: filter.event.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.album_collaborators,
as: 'collaborators',
required: false,
},
{
model: db.access_rules,
as: 'access_rules',
required: false,
},
{
model: db.shares,
as: 'shares',
required: false,
},
{
model: db.stories,
as: 'stories',
required: false,
},
{
model: db.file,
as: 'cover_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'albums',
'title',
filter.title,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'albums',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.privacy) {
where = {
...where,
privacy: filter.privacy,
};
}
if (filter.collaboration_mode) {
where = {
...where,
collaboration_mode: filter.collaboration_mode,
};
}
if (filter.allow_downloads) {
where = {
...where,
allow_downloads: filter.allow_downloads,
};
}
if (filter.allow_comments) {
where = {
...where,
allow_comments: filter.allow_comments,
};
}
if (filter.allow_likes) {
where = {
...where,
allow_likes: filter.allow_likes,
};
}
if (filter.allow_tagging) {
where = {
...where,
allow_tagging: filter.allow_tagging,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.collaborators) {
const searchTerms = filter.collaborators.split('|');
include = [
{
model: db.album_collaborators,
as: 'collaborators_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
role: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.access_rules) {
const searchTerms = filter.access_rules.split('|');
include = [
{
model: db.access_rules,
as: 'access_rules_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
permission: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.shares) {
const searchTerms = filter.shares.split('|');
include = [
{
model: db.shares,
as: 'shares_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
token: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.stories) {
const searchTerms = filter.stories.split('|');
include = [
{
model: db.stories,
as: 'stories_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.albums.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(
'albums',
'title',
query,
),
],
};
}
const records = await db.albums.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,623 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Analytics_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analytics_events = await db.analytics_events.create(
{
id: data.id || undefined,
event_type: data.event_type
||
null
,
metadata_json: data.metadata_json
||
null
,
occurred_at: data.occurred_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await analytics_events.setOrganization(currentUser.organization.id || null, {
transaction,
});
await analytics_events.setUser( data.user || null, {
transaction,
});
await analytics_events.setEvent( data.event || null, {
transaction,
});
await analytics_events.setAlbum( data.album || null, {
transaction,
});
await analytics_events.setMedia_item( data.media_item || null, {
transaction,
});
return analytics_events;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const analytics_eventsData = data.map((item, index) => ({
id: item.id || undefined,
event_type: item.event_type
||
null
,
metadata_json: item.metadata_json
||
null
,
occurred_at: item.occurred_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const analytics_events = await db.analytics_events.bulkCreate(analytics_eventsData, { transaction });
// For each item created, replace relation files
return analytics_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const analytics_events = await db.analytics_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
if (data.metadata_json !== undefined) updatePayload.metadata_json = data.metadata_json;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
updatePayload.updatedById = currentUser.id;
await analytics_events.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await analytics_events.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.user !== undefined) {
await analytics_events.setUser(
data.user,
{ transaction }
);
}
if (data.event !== undefined) {
await analytics_events.setEvent(
data.event,
{ transaction }
);
}
if (data.album !== undefined) {
await analytics_events.setAlbum(
data.album,
{ transaction }
);
}
if (data.media_item !== undefined) {
await analytics_events.setMedia_item(
data.media_item,
{ transaction }
);
}
return analytics_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analytics_events = await db.analytics_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of analytics_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of analytics_events) {
await record.destroy({transaction});
}
});
return analytics_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const analytics_events = await db.analytics_events.findByPk(id, options);
await analytics_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await analytics_events.destroy({
transaction
});
return analytics_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const analytics_events = await db.analytics_events.findOne(
{ where },
{ transaction },
);
if (!analytics_events) {
return analytics_events;
}
const output = analytics_events.get({plain: true});
output.organization = await analytics_events.getOrganization({
transaction
});
output.user = await analytics_events.getUser({
transaction
});
output.event = await analytics_events.getEvent({
transaction
});
output.album = await analytics_events.getAlbum({
transaction
});
output.media_item = await analytics_events.getMedia_item({
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: 'organization',
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.events,
as: 'event',
where: filter.event ? {
[Op.or]: [
{ id: { [Op.in]: filter.event.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.albums,
as: 'album',
where: filter.album ? {
[Op.or]: [
{ id: { [Op.in]: filter.album.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.album.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.metadata_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'analytics_events',
'metadata_json',
filter.metadata_json,
),
};
}
if (filter.occurred_atRange) {
const [start, end] = filter.occurred_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.event_type) {
where = {
...where,
event_type: filter.event_type,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.analytics_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'analytics_events',
'event_type',
query,
),
],
};
}
const records = await db.analytics_events.findAll({
attributes: [ 'id', 'event_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['event_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.event_type,
}));
}
};

View File

@ -0,0 +1,632 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class CommentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const comments = await db.comments.create(
{
id: data.id || undefined,
content: data.content
||
null
,
status: data.status
||
null
,
posted_at: data.posted_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await comments.setMedia_item( data.media_item || null, {
transaction,
});
await comments.setAuthor( data.author || null, {
transaction,
});
await comments.setParent_comment( data.parent_comment || null, {
transaction,
});
await comments.setOrganizations( data.organizations || null, {
transaction,
});
await comments.setMentions(data.mentions || [], {
transaction,
});
return comments;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const commentsData = data.map((item, index) => ({
id: item.id || undefined,
content: item.content
||
null
,
status: item.status
||
null
,
posted_at: item.posted_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const comments = await db.comments.bulkCreate(commentsData, { transaction });
// For each item created, replace relation files
return comments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const comments = await db.comments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.content !== undefined) updatePayload.content = data.content;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
updatePayload.updatedById = currentUser.id;
await comments.update(updatePayload, {transaction});
if (data.media_item !== undefined) {
await comments.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.author !== undefined) {
await comments.setAuthor(
data.author,
{ transaction }
);
}
if (data.parent_comment !== undefined) {
await comments.setParent_comment(
data.parent_comment,
{ transaction }
);
}
if (data.organizations !== undefined) {
await comments.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.mentions !== undefined) {
await comments.setMentions(data.mentions, { transaction });
}
return comments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const comments = await db.comments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of comments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of comments) {
await record.destroy({transaction});
}
});
return comments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const comments = await db.comments.findByPk(id, options);
await comments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await comments.destroy({
transaction
});
return comments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const comments = await db.comments.findOne(
{ where },
{ transaction },
);
if (!comments) {
return comments;
}
const output = comments.get({plain: true});
output.mentions_comment = await comments.getMentions_comment({
transaction
});
output.media_item = await comments.getMedia_item({
transaction
});
output.author = await comments.getAuthor({
transaction
});
output.parent_comment = await comments.getParent_comment({
transaction
});
output.mentions = await comments.getMentions({
transaction
});
output.organizations = await comments.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'author',
where: filter.author ? {
[Op.or]: [
{ id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.comments,
as: 'parent_comment',
where: filter.parent_comment ? {
[Op.or]: [
{ id: { [Op.in]: filter.parent_comment.split('|').map(term => Utils.uuid(term)) } },
{
content: {
[Op.or]: filter.parent_comment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.mentions,
as: 'mentions',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'comments',
'content',
filter.content,
),
};
}
if (filter.posted_atRange) {
const [start, end] = filter.posted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.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.mentions) {
const searchTerms = filter.mentions.split('|');
include = [
{
model: db.mentions,
as: 'mentions_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
mentioned_user: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.comments.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'comments',
'content',
query,
),
],
};
}
const records = await db.comments.findAll({
attributes: [ 'id', 'content' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['content', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.content,
}));
}
};

View File

@ -0,0 +1,689 @@
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 Download_jobsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const download_jobs = await db.download_jobs.create(
{
id: data.id || undefined,
status: data.status
||
null
,
watermark_text: data.watermark_text
||
null
,
requested_at: data.requested_at
||
null
,
completed_at: data.completed_at
||
null
,
error_message: data.error_message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await download_jobs.setMedia_item( data.media_item || null, {
transaction,
});
await download_jobs.setRequested_by( data.requested_by || null, {
transaction,
});
await download_jobs.setWatermark_profile( data.watermark_profile || null, {
transaction,
});
await download_jobs.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.download_jobs.getTableName(),
belongsToColumn: 'output_file',
belongsToId: download_jobs.id,
},
data.output_file,
options,
);
return download_jobs;
}
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 download_jobsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
watermark_text: item.watermark_text
||
null
,
requested_at: item.requested_at
||
null
,
completed_at: item.completed_at
||
null
,
error_message: item.error_message
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const download_jobs = await db.download_jobs.bulkCreate(download_jobsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < download_jobs.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.download_jobs.getTableName(),
belongsToColumn: 'output_file',
belongsToId: download_jobs[i].id,
},
data[i].output_file,
options,
);
}
return download_jobs;
}
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 download_jobs = await db.download_jobs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.watermark_text !== undefined) updatePayload.watermark_text = data.watermark_text;
if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
updatePayload.updatedById = currentUser.id;
await download_jobs.update(updatePayload, {transaction});
if (data.media_item !== undefined) {
await download_jobs.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.requested_by !== undefined) {
await download_jobs.setRequested_by(
data.requested_by,
{ transaction }
);
}
if (data.watermark_profile !== undefined) {
await download_jobs.setWatermark_profile(
data.watermark_profile,
{ transaction }
);
}
if (data.organizations !== undefined) {
await download_jobs.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.download_jobs.getTableName(),
belongsToColumn: 'output_file',
belongsToId: download_jobs.id,
},
data.output_file,
options,
);
return download_jobs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const download_jobs = await db.download_jobs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of download_jobs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of download_jobs) {
await record.destroy({transaction});
}
});
return download_jobs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const download_jobs = await db.download_jobs.findByPk(id, options);
await download_jobs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await download_jobs.destroy({
transaction
});
return download_jobs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const download_jobs = await db.download_jobs.findOne(
{ where },
{ transaction },
);
if (!download_jobs) {
return download_jobs;
}
const output = download_jobs.get({plain: true});
output.media_item = await download_jobs.getMedia_item({
transaction
});
output.requested_by = await download_jobs.getRequested_by({
transaction
});
output.watermark_profile = await download_jobs.getWatermark_profile({
transaction
});
output.output_file = await download_jobs.getOutput_file({
transaction
});
output.organizations = await download_jobs.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.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.watermark_profiles,
as: 'watermark_profile',
where: filter.watermark_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.watermark_profile.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.watermark_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'output_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.watermark_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'download_jobs',
'watermark_text',
filter.watermark_text,
),
};
}
if (filter.error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'download_jobs',
'error_message',
filter.error_message,
),
};
}
if (filter.requested_atRange) {
const [start, end] = filter.requested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.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.download_jobs.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(
'download_jobs',
'status',
query,
),
],
};
}
const records = await db.download_jobs.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,727 @@
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 EventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const events = await db.events.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
category: data.category
||
null
,
starts_at: data.starts_at
||
null
,
ends_at: data.ends_at
||
null
,
privacy: data.privacy
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await events.setOrganization(currentUser.organization.id || null, {
transaction,
});
await events.setDefault_album( data.default_album || null, {
transaction,
});
await events.setAlbums(data.albums || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.events.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: events.id,
},
data.cover_image,
options,
);
return events;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const eventsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
category: item.category
||
null
,
starts_at: item.starts_at
||
null
,
ends_at: item.ends_at
||
null
,
privacy: item.privacy
||
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 events = await db.events.bulkCreate(eventsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < events.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.events.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: events[i].id,
},
data[i].cover_image,
options,
);
}
return events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const events = await db.events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
if (data.privacy !== undefined) updatePayload.privacy = data.privacy;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await events.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await events.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.default_album !== undefined) {
await events.setDefault_album(
data.default_album,
{ transaction }
);
}
if (data.albums !== undefined) {
await events.setAlbums(data.albums, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.events.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: events.id,
},
data.cover_image,
options,
);
return events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const events = await db.events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of events) {
await record.destroy({transaction});
}
});
return events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const events = await db.events.findByPk(id, options);
await events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await events.destroy({
transaction
});
return events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const events = await db.events.findOne(
{ where },
{ transaction },
);
if (!events) {
return events;
}
const output = events.get({plain: true});
output.albums_event = await events.getAlbums_event({
transaction
});
output.notifications_event = await events.getNotifications_event({
transaction
});
output.analytics_events_event = await events.getAnalytics_events_event({
transaction
});
output.organization = await events.getOrganization({
transaction
});
output.cover_image = await events.getCover_image({
transaction
});
output.default_album = await events.getDefault_album({
transaction
});
output.albums = await events.getAlbums({
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: 'organization',
},
{
model: db.albums,
as: 'default_album',
where: filter.default_album ? {
[Op.or]: [
{ id: { [Op.in]: filter.default_album.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.default_album.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.albums,
as: 'albums',
required: false,
},
{
model: db.file,
as: 'cover_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'events',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'events',
'description',
filter.description,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
starts_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ends_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.starts_atRange) {
const [start, end] = filter.starts_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.lte]: end,
},
};
}
}
if (filter.ends_atRange) {
const [start, end] = filter.ends_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.privacy) {
where = {
...where,
privacy: filter.privacy,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.albums) {
const searchTerms = filter.albums.split('|');
include = [
{
model: db.albums,
as: 'albums_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'events',
'name',
query,
),
],
};
}
const records = await db.events.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,694 @@
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 Face_detectionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const face_detections = await db.face_detections.create(
{
id: data.id || undefined,
bbox_x: data.bbox_x
||
null
,
bbox_y: data.bbox_y
||
null
,
bbox_width: data.bbox_width
||
null
,
bbox_height: data.bbox_height
||
null
,
confidence: data.confidence
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await face_detections.setMedia_item( data.media_item || null, {
transaction,
});
await face_detections.setAi_model( data.ai_model || null, {
transaction,
});
await face_detections.setFace_embedding( data.face_embedding || null, {
transaction,
});
await face_detections.setOrganizations( data.organizations || null, {
transaction,
});
return face_detections;
}
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 face_detectionsData = data.map((item, index) => ({
id: item.id || undefined,
bbox_x: item.bbox_x
||
null
,
bbox_y: item.bbox_y
||
null
,
bbox_width: item.bbox_width
||
null
,
bbox_height: item.bbox_height
||
null
,
confidence: item.confidence
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const face_detections = await db.face_detections.bulkCreate(face_detectionsData, { transaction });
// For each item created, replace relation files
return face_detections;
}
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 face_detections = await db.face_detections.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.bbox_x !== undefined) updatePayload.bbox_x = data.bbox_x;
if (data.bbox_y !== undefined) updatePayload.bbox_y = data.bbox_y;
if (data.bbox_width !== undefined) updatePayload.bbox_width = data.bbox_width;
if (data.bbox_height !== undefined) updatePayload.bbox_height = data.bbox_height;
if (data.confidence !== undefined) updatePayload.confidence = data.confidence;
updatePayload.updatedById = currentUser.id;
await face_detections.update(updatePayload, {transaction});
if (data.media_item !== undefined) {
await face_detections.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.ai_model !== undefined) {
await face_detections.setAi_model(
data.ai_model,
{ transaction }
);
}
if (data.face_embedding !== undefined) {
await face_detections.setFace_embedding(
data.face_embedding,
{ transaction }
);
}
if (data.organizations !== undefined) {
await face_detections.setOrganizations(
data.organizations,
{ transaction }
);
}
return face_detections;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const face_detections = await db.face_detections.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of face_detections) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of face_detections) {
await record.destroy({transaction});
}
});
return face_detections;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const face_detections = await db.face_detections.findByPk(id, options);
await face_detections.update({
deletedBy: currentUser.id
}, {
transaction,
});
await face_detections.destroy({
transaction
});
return face_detections;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const face_detections = await db.face_detections.findOne(
{ where },
{ transaction },
);
if (!face_detections) {
return face_detections;
}
const output = face_detections.get({plain: true});
output.face_matches_face_detection = await face_detections.getFace_matches_face_detection({
transaction
});
output.media_item = await face_detections.getMedia_item({
transaction
});
output.ai_model = await face_detections.getAi_model({
transaction
});
output.face_embedding = await face_detections.getFace_embedding({
transaction
});
output.organizations = await face_detections.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.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.ai_models,
as: 'ai_model',
where: filter.ai_model ? {
[Op.or]: [
{ id: { [Op.in]: filter.ai_model.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.ai_model.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.ai_embeddings,
as: 'face_embedding',
where: filter.face_embedding ? {
[Op.or]: [
{ id: { [Op.in]: filter.face_embedding.split('|').map(term => Utils.uuid(term)) } },
{
vector_ref: {
[Op.or]: filter.face_embedding.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.bbox_xRange) {
const [start, end] = filter.bbox_xRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bbox_x: {
...where.bbox_x,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bbox_x: {
...where.bbox_x,
[Op.lte]: end,
},
};
}
}
if (filter.bbox_yRange) {
const [start, end] = filter.bbox_yRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bbox_y: {
...where.bbox_y,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bbox_y: {
...where.bbox_y,
[Op.lte]: end,
},
};
}
}
if (filter.bbox_widthRange) {
const [start, end] = filter.bbox_widthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bbox_width: {
...where.bbox_width,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bbox_width: {
...where.bbox_width,
[Op.lte]: end,
},
};
}
}
if (filter.bbox_heightRange) {
const [start, end] = filter.bbox_heightRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bbox_height: {
...where.bbox_height,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bbox_height: {
...where.bbox_height,
[Op.lte]: end,
},
};
}
}
if (filter.confidenceRange) {
const [start, end] = filter.confidenceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
confidence: {
...where.confidence,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
confidence: {
...where.confidence,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.face_detections.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(
'face_detections',
'confidence',
query,
),
],
};
}
const records = await db.face_detections.findAll({
attributes: [ 'id', 'confidence' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['confidence', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.confidence,
}));
}
};

View File

@ -0,0 +1,562 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Face_matchesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const face_matches = await db.face_matches.create(
{
id: data.id || undefined,
match_score: data.match_score
||
null
,
confidence_badge: data.confidence_badge
||
null
,
matched_at: data.matched_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await face_matches.setSelfie_reference( data.selfie_reference || null, {
transaction,
});
await face_matches.setFace_detection( data.face_detection || null, {
transaction,
});
await face_matches.setOrganizations( data.organizations || null, {
transaction,
});
return face_matches;
}
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 face_matchesData = data.map((item, index) => ({
id: item.id || undefined,
match_score: item.match_score
||
null
,
confidence_badge: item.confidence_badge
||
null
,
matched_at: item.matched_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const face_matches = await db.face_matches.bulkCreate(face_matchesData, { transaction });
// For each item created, replace relation files
return face_matches;
}
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 face_matches = await db.face_matches.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.match_score !== undefined) updatePayload.match_score = data.match_score;
if (data.confidence_badge !== undefined) updatePayload.confidence_badge = data.confidence_badge;
if (data.matched_at !== undefined) updatePayload.matched_at = data.matched_at;
updatePayload.updatedById = currentUser.id;
await face_matches.update(updatePayload, {transaction});
if (data.selfie_reference !== undefined) {
await face_matches.setSelfie_reference(
data.selfie_reference,
{ transaction }
);
}
if (data.face_detection !== undefined) {
await face_matches.setFace_detection(
data.face_detection,
{ transaction }
);
}
if (data.organizations !== undefined) {
await face_matches.setOrganizations(
data.organizations,
{ transaction }
);
}
return face_matches;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const face_matches = await db.face_matches.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of face_matches) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of face_matches) {
await record.destroy({transaction});
}
});
return face_matches;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const face_matches = await db.face_matches.findByPk(id, options);
await face_matches.update({
deletedBy: currentUser.id
}, {
transaction,
});
await face_matches.destroy({
transaction
});
return face_matches;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const face_matches = await db.face_matches.findOne(
{ where },
{ transaction },
);
if (!face_matches) {
return face_matches;
}
const output = face_matches.get({plain: true});
output.selfie_reference = await face_matches.getSelfie_reference({
transaction
});
output.face_detection = await face_matches.getFace_detection({
transaction
});
output.organizations = await face_matches.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.selfie_references,
as: 'selfie_reference',
where: filter.selfie_reference ? {
[Op.or]: [
{ id: { [Op.in]: filter.selfie_reference.split('|').map(term => Utils.uuid(term)) } },
{
status: {
[Op.or]: filter.selfie_reference.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.face_detections,
as: 'face_detection',
where: filter.face_detection ? {
[Op.or]: [
{ id: { [Op.in]: filter.face_detection.split('|').map(term => Utils.uuid(term)) } },
{
confidence: {
[Op.or]: filter.face_detection.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.match_scoreRange) {
const [start, end] = filter.match_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
match_score: {
...where.match_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
match_score: {
...where.match_score,
[Op.lte]: end,
},
};
}
}
if (filter.matched_atRange) {
const [start, end] = filter.matched_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
matched_at: {
...where.matched_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
matched_at: {
...where.matched_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.confidence_badge) {
where = {
...where,
confidence_badge: filter.confidence_badge,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.face_matches.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(
'face_matches',
'confidence_badge',
query,
),
],
};
}
const records = await db.face_matches.findAll({
attributes: [ 'id', 'confidence_badge' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['confidence_badge', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.confidence_badge,
}));
}
};

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

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

505
backend/src/db/api/likes.js Normal file
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 LikesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const likes = await db.likes.create(
{
id: data.id || undefined,
liked_at: data.liked_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await likes.setMedia_item( data.media_item || null, {
transaction,
});
await likes.setUser( data.user || null, {
transaction,
});
await likes.setOrganizations( data.organizations || null, {
transaction,
});
return likes;
}
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 likesData = data.map((item, index) => ({
id: item.id || undefined,
liked_at: item.liked_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const likes = await db.likes.bulkCreate(likesData, { transaction });
// For each item created, replace relation files
return likes;
}
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 likes = await db.likes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.liked_at !== undefined) updatePayload.liked_at = data.liked_at;
updatePayload.updatedById = currentUser.id;
await likes.update(updatePayload, {transaction});
if (data.media_item !== undefined) {
await likes.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.user !== undefined) {
await likes.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await likes.setOrganizations(
data.organizations,
{ transaction }
);
}
return likes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const likes = await db.likes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of likes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of likes) {
await record.destroy({transaction});
}
});
return likes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const likes = await db.likes.findByPk(id, options);
await likes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await likes.destroy({
transaction
});
return likes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const likes = await db.likes.findOne(
{ where },
{ transaction },
);
if (!likes) {
return likes;
}
const output = likes.get({plain: true});
output.media_item = await likes.getMedia_item({
transaction
});
output.user = await likes.getUser({
transaction
});
output.organizations = await likes.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.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.liked_atRange) {
const [start, end] = filter.liked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
liked_at: {
...where.liked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
liked_at: {
...where.liked_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.likes.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(
'likes',
'liked_at',
query,
),
],
};
}
const records = await db.likes.findAll({
attributes: [ 'id', 'liked_at' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['liked_at', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.liked_at,
}));
}
};

View File

@ -0,0 +1,525 @@
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 Media_ai_tagsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const media_ai_tags = await db.media_ai_tags.create(
{
id: data.id || undefined,
confidence: data.confidence
||
null
,
source: data.source
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await media_ai_tags.setMedia_item( data.media_item || null, {
transaction,
});
await media_ai_tags.setTag( data.tag || null, {
transaction,
});
await media_ai_tags.setOrganizations( data.organizations || null, {
transaction,
});
return media_ai_tags;
}
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 media_ai_tagsData = data.map((item, index) => ({
id: item.id || undefined,
confidence: item.confidence
||
null
,
source: item.source
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const media_ai_tags = await db.media_ai_tags.bulkCreate(media_ai_tagsData, { transaction });
// For each item created, replace relation files
return media_ai_tags;
}
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 media_ai_tags = await db.media_ai_tags.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.confidence !== undefined) updatePayload.confidence = data.confidence;
if (data.source !== undefined) updatePayload.source = data.source;
updatePayload.updatedById = currentUser.id;
await media_ai_tags.update(updatePayload, {transaction});
if (data.media_item !== undefined) {
await media_ai_tags.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.tag !== undefined) {
await media_ai_tags.setTag(
data.tag,
{ transaction }
);
}
if (data.organizations !== undefined) {
await media_ai_tags.setOrganizations(
data.organizations,
{ transaction }
);
}
return media_ai_tags;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const media_ai_tags = await db.media_ai_tags.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of media_ai_tags) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of media_ai_tags) {
await record.destroy({transaction});
}
});
return media_ai_tags;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const media_ai_tags = await db.media_ai_tags.findByPk(id, options);
await media_ai_tags.update({
deletedBy: currentUser.id
}, {
transaction,
});
await media_ai_tags.destroy({
transaction
});
return media_ai_tags;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const media_ai_tags = await db.media_ai_tags.findOne(
{ where },
{ transaction },
);
if (!media_ai_tags) {
return media_ai_tags;
}
const output = media_ai_tags.get({plain: true});
output.media_item = await media_ai_tags.getMedia_item({
transaction
});
output.tag = await media_ai_tags.getTag({
transaction
});
output.organizations = await media_ai_tags.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.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.tags,
as: 'tag',
where: filter.tag ? {
[Op.or]: [
{ id: { [Op.in]: filter.tag.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tag.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.confidenceRange) {
const [start, end] = filter.confidenceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
confidence: {
...where.confidence,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
confidence: {
...where.confidence,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.source) {
where = {
...where,
source: filter.source,
};
}
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.media_ai_tags.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(
'media_ai_tags',
'source',
query,
),
],
};
}
const records = await db.media_ai_tags.findAll({
attributes: [ 'id', 'source' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['source', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.source,
}));
}
};

File diff suppressed because it is too large Load Diff

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 Media_user_tagsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const media_user_tags = await db.media_user_tags.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await media_user_tags.setMedia_item( data.media_item || null, {
transaction,
});
await media_user_tags.setTag( data.tag || null, {
transaction,
});
await media_user_tags.setTagged_by( data.tagged_by || null, {
transaction,
});
await media_user_tags.setOrganizations( data.organizations || null, {
transaction,
});
return media_user_tags;
}
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 media_user_tagsData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const media_user_tags = await db.media_user_tags.bulkCreate(media_user_tagsData, { transaction });
// For each item created, replace relation files
return media_user_tags;
}
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 media_user_tags = await db.media_user_tags.findByPk(id, {}, {transaction});
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await media_user_tags.update(updatePayload, {transaction});
if (data.media_item !== undefined) {
await media_user_tags.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.tag !== undefined) {
await media_user_tags.setTag(
data.tag,
{ transaction }
);
}
if (data.tagged_by !== undefined) {
await media_user_tags.setTagged_by(
data.tagged_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await media_user_tags.setOrganizations(
data.organizations,
{ transaction }
);
}
return media_user_tags;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const media_user_tags = await db.media_user_tags.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of media_user_tags) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of media_user_tags) {
await record.destroy({transaction});
}
});
return media_user_tags;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const media_user_tags = await db.media_user_tags.findByPk(id, options);
await media_user_tags.update({
deletedBy: currentUser.id
}, {
transaction,
});
await media_user_tags.destroy({
transaction
});
return media_user_tags;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const media_user_tags = await db.media_user_tags.findOne(
{ where },
{ transaction },
);
if (!media_user_tags) {
return media_user_tags;
}
const output = media_user_tags.get({plain: true});
output.media_item = await media_user_tags.getMedia_item({
transaction
});
output.tag = await media_user_tags.getTag({
transaction
});
output.tagged_by = await media_user_tags.getTagged_by({
transaction
});
output.organizations = await media_user_tags.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.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.tags,
as: 'tag',
where: filter.tag ? {
[Op.or]: [
{ id: { [Op.in]: filter.tag.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tag.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'tagged_by',
where: filter.tagged_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.tagged_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.tagged_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.media_user_tags.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(
'media_user_tags',
'tagged_by',
query,
),
],
};
}
const records = await db.media_user_tags.findAll({
attributes: [ 'id', 'tagged_by' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['tagged_by', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.tagged_by,
}));
}
};

View File

@ -0,0 +1,529 @@
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 MembershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const memberships = await db.memberships.create(
{
id: data.id || undefined,
status: data.status
||
null
,
joined_at: data.joined_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await memberships.setOrganization(currentUser.organization.id || null, {
transaction,
});
await memberships.setUser( data.user || null, {
transaction,
});
await memberships.setRole( data.role || null, {
transaction,
});
return 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 membershipsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
joined_at: item.joined_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const memberships = await db.memberships.bulkCreate(membershipsData, { transaction });
// For each item created, replace relation files
return 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 memberships = await db.memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
updatePayload.updatedById = currentUser.id;
await memberships.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await memberships.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.user !== undefined) {
await memberships.setUser(
data.user,
{ transaction }
);
}
if (data.role !== undefined) {
await memberships.setRole(
data.role,
{ transaction }
);
}
return memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const memberships = await db.memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of memberships) {
await record.destroy({transaction});
}
});
return memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const memberships = await db.memberships.findByPk(id, options);
await memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await memberships.destroy({
transaction
});
return memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const memberships = await db.memberships.findOne(
{ where },
{ transaction },
);
if (!memberships) {
return memberships;
}
const output = memberships.get({plain: true});
output.access_rules_membership = await memberships.getAccess_rules_membership({
transaction
});
output.organization = await memberships.getOrganization({
transaction
});
output.user = await memberships.getUser({
transaction
});
output.role = await memberships.getRole({
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: 'organization',
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.roles,
as: 'role',
where: filter.role ? {
[Op.or]: [
{ id: { [Op.in]: filter.role.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.role.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
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.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[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.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(
'memberships',
'status',
query,
),
],
};
}
const records = await db.memberships.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

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 MentionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mentions = await db.mentions.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await mentions.setComment( data.comment || null, {
transaction,
});
await mentions.setMedia_item( data.media_item || null, {
transaction,
});
await mentions.setMentioned_user( data.mentioned_user || null, {
transaction,
});
await mentions.setOrganizations( data.organizations || null, {
transaction,
});
return mentions;
}
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 mentionsData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const mentions = await db.mentions.bulkCreate(mentionsData, { transaction });
// For each item created, replace relation files
return mentions;
}
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 mentions = await db.mentions.findByPk(id, {}, {transaction});
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await mentions.update(updatePayload, {transaction});
if (data.comment !== undefined) {
await mentions.setComment(
data.comment,
{ transaction }
);
}
if (data.media_item !== undefined) {
await mentions.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.mentioned_user !== undefined) {
await mentions.setMentioned_user(
data.mentioned_user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await mentions.setOrganizations(
data.organizations,
{ transaction }
);
}
return mentions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mentions = await db.mentions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of mentions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of mentions) {
await record.destroy({transaction});
}
});
return mentions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mentions = await db.mentions.findByPk(id, options);
await mentions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await mentions.destroy({
transaction
});
return mentions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const mentions = await db.mentions.findOne(
{ where },
{ transaction },
);
if (!mentions) {
return mentions;
}
const output = mentions.get({plain: true});
output.comment = await mentions.getComment({
transaction
});
output.media_item = await mentions.getMedia_item({
transaction
});
output.mentioned_user = await mentions.getMentioned_user({
transaction
});
output.organizations = await mentions.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.comments,
as: 'comment',
where: filter.comment ? {
[Op.or]: [
{ id: { [Op.in]: filter.comment.split('|').map(term => Utils.uuid(term)) } },
{
content: {
[Op.or]: filter.comment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'mentioned_user',
where: filter.mentioned_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.mentioned_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.mentioned_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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.mentions.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(
'mentions',
'mentioned_user',
query,
),
],
};
}
const records = await db.mentions.findAll({
attributes: [ 'id', 'mentioned_user' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['mentioned_user', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.mentioned_user,
}));
}
};

View File

@ -0,0 +1,643 @@
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 Moderation_flagsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const moderation_flags = await db.moderation_flags.create(
{
id: data.id || undefined,
reason: data.reason
||
null
,
details: data.details
||
null
,
status: data.status
||
null
,
reported_at: data.reported_at
||
null
,
resolved_at: data.resolved_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await moderation_flags.setMedia_item( data.media_item || null, {
transaction,
});
await moderation_flags.setReported_by( data.reported_by || null, {
transaction,
});
await moderation_flags.setReviewed_by( data.reviewed_by || null, {
transaction,
});
await moderation_flags.setOrganizations( data.organizations || null, {
transaction,
});
return moderation_flags;
}
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 moderation_flagsData = data.map((item, index) => ({
id: item.id || undefined,
reason: item.reason
||
null
,
details: item.details
||
null
,
status: item.status
||
null
,
reported_at: item.reported_at
||
null
,
resolved_at: item.resolved_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const moderation_flags = await db.moderation_flags.bulkCreate(moderation_flagsData, { transaction });
// For each item created, replace relation files
return moderation_flags;
}
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 moderation_flags = await db.moderation_flags.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.reason !== undefined) updatePayload.reason = data.reason;
if (data.details !== undefined) updatePayload.details = data.details;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
updatePayload.updatedById = currentUser.id;
await moderation_flags.update(updatePayload, {transaction});
if (data.media_item !== undefined) {
await moderation_flags.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.reported_by !== undefined) {
await moderation_flags.setReported_by(
data.reported_by,
{ transaction }
);
}
if (data.reviewed_by !== undefined) {
await moderation_flags.setReviewed_by(
data.reviewed_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await moderation_flags.setOrganizations(
data.organizations,
{ transaction }
);
}
return moderation_flags;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const moderation_flags = await db.moderation_flags.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of moderation_flags) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of moderation_flags) {
await record.destroy({transaction});
}
});
return moderation_flags;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const moderation_flags = await db.moderation_flags.findByPk(id, options);
await moderation_flags.update({
deletedBy: currentUser.id
}, {
transaction,
});
await moderation_flags.destroy({
transaction
});
return moderation_flags;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const moderation_flags = await db.moderation_flags.findOne(
{ where },
{ transaction },
);
if (!moderation_flags) {
return moderation_flags;
}
const output = moderation_flags.get({plain: true});
output.media_item = await moderation_flags.getMedia_item({
transaction
});
output.reported_by = await moderation_flags.getReported_by({
transaction
});
output.reviewed_by = await moderation_flags.getReviewed_by({
transaction
});
output.organizations = await moderation_flags.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.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'reported_by',
where: filter.reported_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.reported_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.reported_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'reviewed_by',
where: filter.reviewed_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.reviewed_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.reviewed_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'moderation_flags',
'details',
filter.details,
),
};
}
if (filter.reported_atRange) {
const [start, end] = filter.reported_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reported_at: {
...where.reported_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reported_at: {
...where.reported_at,
[Op.lte]: end,
},
};
}
}
if (filter.resolved_atRange) {
const [start, end] = filter.resolved_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
resolved_at: {
...where.resolved_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
resolved_at: {
...where.resolved_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.reason) {
where = {
...where,
reason: filter.reason,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.moderation_flags.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(
'moderation_flags',
'reason',
query,
),
],
};
}
const records = await db.moderation_flags.findAll({
attributes: [ 'id', 'reason' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reason', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reason,
}));
}
};

View File

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

View File

@ -0,0 +1,706 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class NotificationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.create(
{
id: data.id || undefined,
type: data.type
||
null
,
title: data.title
||
null
,
body: data.body
||
null
,
is_read: data.is_read
||
false
,
read_at: data.read_at
||
null
,
sent_at: data.sent_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notifications.setRecipient( data.recipient || null, {
transaction,
});
await notifications.setMedia_item( data.media_item || null, {
transaction,
});
await notifications.setEvent( data.event || null, {
transaction,
});
await notifications.setAlbum( data.album || null, {
transaction,
});
await notifications.setOrganizations( data.organizations || null, {
transaction,
});
return notifications;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const notificationsData = data.map((item, index) => ({
id: item.id || undefined,
type: item.type
||
null
,
title: item.title
||
null
,
body: item.body
||
null
,
is_read: item.is_read
||
false
,
read_at: item.read_at
||
null
,
sent_at: item.sent_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const notifications = await db.notifications.bulkCreate(notificationsData, { transaction });
// For each item created, replace relation files
return notifications;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const notifications = await db.notifications.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.type !== undefined) updatePayload.type = data.type;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.is_read !== undefined) updatePayload.is_read = data.is_read;
if (data.read_at !== undefined) updatePayload.read_at = data.read_at;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
updatePayload.updatedById = currentUser.id;
await notifications.update(updatePayload, {transaction});
if (data.recipient !== undefined) {
await notifications.setRecipient(
data.recipient,
{ transaction }
);
}
if (data.media_item !== undefined) {
await notifications.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.event !== undefined) {
await notifications.setEvent(
data.event,
{ transaction }
);
}
if (data.album !== undefined) {
await notifications.setAlbum(
data.album,
{ transaction }
);
}
if (data.organizations !== undefined) {
await notifications.setOrganizations(
data.organizations,
{ transaction }
);
}
return notifications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notifications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notifications) {
await record.destroy({transaction});
}
});
return notifications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findByPk(id, options);
await notifications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notifications.destroy({
transaction
});
return notifications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findOne(
{ where },
{ transaction },
);
if (!notifications) {
return notifications;
}
const output = notifications.get({plain: true});
output.recipient = await notifications.getRecipient({
transaction
});
output.media_item = await notifications.getMedia_item({
transaction
});
output.event = await notifications.getEvent({
transaction
});
output.album = await notifications.getAlbum({
transaction
});
output.organizations = await notifications.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'recipient',
where: filter.recipient ? {
[Op.or]: [
{ id: { [Op.in]: filter.recipient.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recipient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.events,
as: 'event',
where: filter.event ? {
[Op.or]: [
{ id: { [Op.in]: filter.event.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.albums,
as: 'album',
where: filter.album ? {
[Op.or]: [
{ id: { [Op.in]: filter.album.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.album.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'title',
filter.title,
),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'body',
filter.body,
),
};
}
if (filter.read_atRange) {
const [start, end] = filter.read_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
read_at: {
...where.read_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
read_at: {
...where.read_at,
[Op.lte]: end,
},
};
}
}
if (filter.sent_atRange) {
const [start, end] = filter.sent_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.type) {
where = {
...where,
type: filter.type,
};
}
if (filter.is_read) {
where = {
...where,
is_read: filter.is_read,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.notifications.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'notifications',
'title',
query,
),
],
};
}
const records = await db.notifications.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

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

View File

@ -0,0 +1,521 @@
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.role_permissions_organizations = await organizations.getRole_permissions_organizations({
transaction
});
output.memberships_organization = await organizations.getMemberships_organization({
transaction
});
output.events_organization = await organizations.getEvents_organization({
transaction
});
output.albums_organizations = await organizations.getAlbums_organizations({
transaction
});
output.album_collaborators_organizations = await organizations.getAlbum_collaborators_organizations({
transaction
});
output.access_rules_organizations = await organizations.getAccess_rules_organizations({
transaction
});
output.media_items_organizations = await organizations.getMedia_items_organizations({
transaction
});
output.storage_buckets_organization = await organizations.getStorage_buckets_organization({
transaction
});
output.storage_objects_organizations = await organizations.getStorage_objects_organizations({
transaction
});
output.upload_sessions_organizations = await organizations.getUpload_sessions_organizations({
transaction
});
output.upload_files_organizations = await organizations.getUpload_files_organizations({
transaction
});
output.tags_organization = await organizations.getTags_organization({
transaction
});
output.media_ai_tags_organizations = await organizations.getMedia_ai_tags_organizations({
transaction
});
output.media_user_tags_organizations = await organizations.getMedia_user_tags_organizations({
transaction
});
output.likes_organizations = await organizations.getLikes_organizations({
transaction
});
output.favourites_organizations = await organizations.getFavourites_organizations({
transaction
});
output.comments_organizations = await organizations.getComments_organizations({
transaction
});
output.mentions_organizations = await organizations.getMentions_organizations({
transaction
});
output.notifications_organizations = await organizations.getNotifications_organizations({
transaction
});
output.notification_preferences_organizations = await organizations.getNotification_preferences_organizations({
transaction
});
output.shares_organizations = await organizations.getShares_organizations({
transaction
});
output.download_jobs_organizations = await organizations.getDownload_jobs_organizations({
transaction
});
output.watermark_profiles_organization = await organizations.getWatermark_profiles_organization({
transaction
});
output.ai_models_organization = await organizations.getAi_models_organization({
transaction
});
output.ai_embeddings_organizations = await organizations.getAi_embeddings_organizations({
transaction
});
output.face_detections_organizations = await organizations.getFace_detections_organizations({
transaction
});
output.selfie_references_organizations = await organizations.getSelfie_references_organizations({
transaction
});
output.face_matches_organizations = await organizations.getFace_matches_organizations({
transaction
});
output.ai_captions_organizations = await organizations.getAi_captions_organizations({
transaction
});
output.moderation_flags_organizations = await organizations.getModeration_flags_organizations({
transaction
});
output.stories_organizations = await organizations.getStories_organizations({
transaction
});
output.story_items_organizations = await organizations.getStory_items_organizations({
transaction
});
output.analytics_events_organization = await organizations.getAnalytics_events_organization({
transaction
});
output.oauth_accounts_organizations = await organizations.getOauth_accounts_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,367 @@
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,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 Role_permissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const role_permissions = await db.role_permissions.create(
{
id: data.id || undefined,
resource: data.resource
||
null
,
action: data.action
||
null
,
allowed: data.allowed
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await role_permissions.setOrganizations( data.organizations || null, {
transaction,
});
return role_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 role_permissionsData = data.map((item, index) => ({
id: item.id || undefined,
resource: item.resource
||
null
,
action: item.action
||
null
,
allowed: item.allowed
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const role_permissions = await db.role_permissions.bulkCreate(role_permissionsData, { transaction });
// For each item created, replace relation files
return role_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 role_permissions = await db.role_permissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.resource !== undefined) updatePayload.resource = data.resource;
if (data.action !== undefined) updatePayload.action = data.action;
if (data.allowed !== undefined) updatePayload.allowed = data.allowed;
updatePayload.updatedById = currentUser.id;
await role_permissions.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await role_permissions.setOrganizations(
data.organizations,
{ transaction }
);
}
return role_permissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const role_permissions = await db.role_permissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of role_permissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of role_permissions) {
await record.destroy({transaction});
}
});
return role_permissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const role_permissions = await db.role_permissions.findByPk(id, options);
await role_permissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await role_permissions.destroy({
transaction
});
return role_permissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const role_permissions = await db.role_permissions.findOne(
{ where },
{ transaction },
);
if (!role_permissions) {
return role_permissions;
}
const output = role_permissions.get({plain: true});
output.organizations = await role_permissions.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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.resource) {
where = {
...where,
resource: filter.resource,
};
}
if (filter.action) {
where = {
...where,
action: filter.action,
};
}
if (filter.allowed) {
where = {
...where,
allowed: filter.allowed,
};
}
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.role_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'role_permissions',
'resource',
query,
),
],
};
}
const records = await db.role_permissions.findAll({
attributes: [ 'id', 'resource' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['resource', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.resource,
}));
}
};

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

@ -0,0 +1,477 @@
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.memberships_role = await roles.getMemberships_role({
transaction
});
output.access_rules_role = await roles.getAccess_rules_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,608 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Selfie_referencesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const selfie_references = await db.selfie_references.create(
{
id: data.id || undefined,
status: data.status
||
null
,
uploaded_at: data.uploaded_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await selfie_references.setUser( data.user || null, {
transaction,
});
await selfie_references.setAi_model( data.ai_model || null, {
transaction,
});
await selfie_references.setSelfie_embedding( data.selfie_embedding || null, {
transaction,
});
await selfie_references.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.selfie_references.getTableName(),
belongsToColumn: 'selfie_image',
belongsToId: selfie_references.id,
},
data.selfie_image,
options,
);
return selfie_references;
}
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 selfie_referencesData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
uploaded_at: item.uploaded_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const selfie_references = await db.selfie_references.bulkCreate(selfie_referencesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < selfie_references.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.selfie_references.getTableName(),
belongsToColumn: 'selfie_image',
belongsToId: selfie_references[i].id,
},
data[i].selfie_image,
options,
);
}
return selfie_references;
}
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 selfie_references = await db.selfie_references.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.uploaded_at !== undefined) updatePayload.uploaded_at = data.uploaded_at;
updatePayload.updatedById = currentUser.id;
await selfie_references.update(updatePayload, {transaction});
if (data.user !== undefined) {
await selfie_references.setUser(
data.user,
{ transaction }
);
}
if (data.ai_model !== undefined) {
await selfie_references.setAi_model(
data.ai_model,
{ transaction }
);
}
if (data.selfie_embedding !== undefined) {
await selfie_references.setSelfie_embedding(
data.selfie_embedding,
{ transaction }
);
}
if (data.organizations !== undefined) {
await selfie_references.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.selfie_references.getTableName(),
belongsToColumn: 'selfie_image',
belongsToId: selfie_references.id,
},
data.selfie_image,
options,
);
return selfie_references;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const selfie_references = await db.selfie_references.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of selfie_references) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of selfie_references) {
await record.destroy({transaction});
}
});
return selfie_references;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const selfie_references = await db.selfie_references.findByPk(id, options);
await selfie_references.update({
deletedBy: currentUser.id
}, {
transaction,
});
await selfie_references.destroy({
transaction
});
return selfie_references;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const selfie_references = await db.selfie_references.findOne(
{ where },
{ transaction },
);
if (!selfie_references) {
return selfie_references;
}
const output = selfie_references.get({plain: true});
output.face_matches_selfie_reference = await selfie_references.getFace_matches_selfie_reference({
transaction
});
output.user = await selfie_references.getUser({
transaction
});
output.selfie_image = await selfie_references.getSelfie_image({
transaction
});
output.ai_model = await selfie_references.getAi_model({
transaction
});
output.selfie_embedding = await selfie_references.getSelfie_embedding({
transaction
});
output.organizations = await selfie_references.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.ai_models,
as: 'ai_model',
where: filter.ai_model ? {
[Op.or]: [
{ id: { [Op.in]: filter.ai_model.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.ai_model.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.ai_embeddings,
as: 'selfie_embedding',
where: filter.selfie_embedding ? {
[Op.or]: [
{ id: { [Op.in]: filter.selfie_embedding.split('|').map(term => Utils.uuid(term)) } },
{
vector_ref: {
[Op.or]: filter.selfie_embedding.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'selfie_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.uploaded_atRange) {
const [start, end] = filter.uploaded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
uploaded_at: {
...where.uploaded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
uploaded_at: {
...where.uploaded_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.selfie_references.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(
'selfie_references',
'status',
query,
),
],
};
}
const records = await db.selfie_references.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,702 @@
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 SharesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shares = await db.shares.create(
{
id: data.id || undefined,
share_type: data.share_type
||
null
,
token: data.token
||
null
,
access_level: data.access_level
||
null
,
expires_at: data.expires_at
||
null
,
max_uses: data.max_uses
||
null
,
uses_count: data.uses_count
||
null
,
revoked: data.revoked
||
false
,
revoked_at: data.revoked_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await shares.setAlbum( data.album || null, {
transaction,
});
await shares.setCreated_by( data.created_by || null, {
transaction,
});
await shares.setOrganizations( data.organizations || null, {
transaction,
});
return shares;
}
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 sharesData = data.map((item, index) => ({
id: item.id || undefined,
share_type: item.share_type
||
null
,
token: item.token
||
null
,
access_level: item.access_level
||
null
,
expires_at: item.expires_at
||
null
,
max_uses: item.max_uses
||
null
,
uses_count: item.uses_count
||
null
,
revoked: item.revoked
||
false
,
revoked_at: item.revoked_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const shares = await db.shares.bulkCreate(sharesData, { transaction });
// For each item created, replace relation files
return shares;
}
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 shares = await db.shares.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.share_type !== undefined) updatePayload.share_type = data.share_type;
if (data.token !== undefined) updatePayload.token = data.token;
if (data.access_level !== undefined) updatePayload.access_level = data.access_level;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.max_uses !== undefined) updatePayload.max_uses = data.max_uses;
if (data.uses_count !== undefined) updatePayload.uses_count = data.uses_count;
if (data.revoked !== undefined) updatePayload.revoked = data.revoked;
if (data.revoked_at !== undefined) updatePayload.revoked_at = data.revoked_at;
updatePayload.updatedById = currentUser.id;
await shares.update(updatePayload, {transaction});
if (data.album !== undefined) {
await shares.setAlbum(
data.album,
{ transaction }
);
}
if (data.created_by !== undefined) {
await shares.setCreated_by(
data.created_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await shares.setOrganizations(
data.organizations,
{ transaction }
);
}
return shares;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shares = await db.shares.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of shares) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of shares) {
await record.destroy({transaction});
}
});
return shares;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const shares = await db.shares.findByPk(id, options);
await shares.update({
deletedBy: currentUser.id
}, {
transaction,
});
await shares.destroy({
transaction
});
return shares;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const shares = await db.shares.findOne(
{ where },
{ transaction },
);
if (!shares) {
return shares;
}
const output = shares.get({plain: true});
output.album = await shares.getAlbum({
transaction
});
output.created_by = await shares.getCreated_by({
transaction
});
output.organizations = await shares.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.albums,
as: 'album',
where: filter.album ? {
[Op.or]: [
{ id: { [Op.in]: filter.album.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.album.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'created_by',
where: filter.created_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.token) {
where = {
...where,
[Op.and]: Utils.ilike(
'shares',
'token',
filter.token,
),
};
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.max_usesRange) {
const [start, end] = filter.max_usesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_uses: {
...where.max_uses,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_uses: {
...where.max_uses,
[Op.lte]: end,
},
};
}
}
if (filter.uses_countRange) {
const [start, end] = filter.uses_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
uses_count: {
...where.uses_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
uses_count: {
...where.uses_count,
[Op.lte]: end,
},
};
}
}
if (filter.revoked_atRange) {
const [start, end] = filter.revoked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.share_type) {
where = {
...where,
share_type: filter.share_type,
};
}
if (filter.access_level) {
where = {
...where,
access_level: filter.access_level,
};
}
if (filter.revoked) {
where = {
...where,
revoked: filter.revoked,
};
}
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.shares.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(
'shares',
'token',
query,
),
],
};
}
const records = await db.shares.findAll({
attributes: [ 'id', 'token' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['token', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.token,
}));
}
};

View File

@ -0,0 +1,578 @@
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 Storage_bucketsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const storage_buckets = await db.storage_buckets.create(
{
id: data.id || undefined,
provider: data.provider
||
null
,
bucket_name: data.bucket_name
||
null
,
region: data.region
||
null
,
cdn_domain: data.cdn_domain
||
null
,
default_bucket: data.default_bucket
||
false
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await storage_buckets.setOrganization(currentUser.organization.id || null, {
transaction,
});
await storage_buckets.setStorage_objects(data.storage_objects || [], {
transaction,
});
return storage_buckets;
}
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 storage_bucketsData = data.map((item, index) => ({
id: item.id || undefined,
provider: item.provider
||
null
,
bucket_name: item.bucket_name
||
null
,
region: item.region
||
null
,
cdn_domain: item.cdn_domain
||
null
,
default_bucket: item.default_bucket
||
false
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const storage_buckets = await db.storage_buckets.bulkCreate(storage_bucketsData, { transaction });
// For each item created, replace relation files
return storage_buckets;
}
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 storage_buckets = await db.storage_buckets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.provider !== undefined) updatePayload.provider = data.provider;
if (data.bucket_name !== undefined) updatePayload.bucket_name = data.bucket_name;
if (data.region !== undefined) updatePayload.region = data.region;
if (data.cdn_domain !== undefined) updatePayload.cdn_domain = data.cdn_domain;
if (data.default_bucket !== undefined) updatePayload.default_bucket = data.default_bucket;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await storage_buckets.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await storage_buckets.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.storage_objects !== undefined) {
await storage_buckets.setStorage_objects(data.storage_objects, { transaction });
}
return storage_buckets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const storage_buckets = await db.storage_buckets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of storage_buckets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of storage_buckets) {
await record.destroy({transaction});
}
});
return storage_buckets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const storage_buckets = await db.storage_buckets.findByPk(id, options);
await storage_buckets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await storage_buckets.destroy({
transaction
});
return storage_buckets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const storage_buckets = await db.storage_buckets.findOne(
{ where },
{ transaction },
);
if (!storage_buckets) {
return storage_buckets;
}
const output = storage_buckets.get({plain: true});
output.storage_objects_bucket = await storage_buckets.getStorage_objects_bucket({
transaction
});
output.organization = await storage_buckets.getOrganization({
transaction
});
output.storage_objects = await storage_buckets.getStorage_objects({
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: 'organization',
},
{
model: db.storage_objects,
as: 'storage_objects',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.provider) {
where = {
...where,
[Op.and]: Utils.ilike(
'storage_buckets',
'provider',
filter.provider,
),
};
}
if (filter.bucket_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'storage_buckets',
'bucket_name',
filter.bucket_name,
),
};
}
if (filter.region) {
where = {
...where,
[Op.and]: Utils.ilike(
'storage_buckets',
'region',
filter.region,
),
};
}
if (filter.cdn_domain) {
where = {
...where,
[Op.and]: Utils.ilike(
'storage_buckets',
'cdn_domain',
filter.cdn_domain,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.default_bucket) {
where = {
...where,
default_bucket: filter.default_bucket,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[Op.or]: listItems}
};
}
if (filter.storage_objects) {
const searchTerms = filter.storage_objects.split('|');
include = [
{
model: db.storage_objects,
as: 'storage_objects_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
object_key: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.storage_buckets.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(
'storage_buckets',
'bucket_name',
query,
),
],
};
}
const records = await db.storage_buckets.findAll({
attributes: [ 'id', 'bucket_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['bucket_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.bucket_name,
}));
}
};

View File

@ -0,0 +1,825 @@
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 Storage_objectsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const storage_objects = await db.storage_objects.create(
{
id: data.id || undefined,
object_key: data.object_key
||
null
,
content_type: data.content_type
||
null
,
size_bytes: data.size_bytes
||
null
,
etag: data.etag
||
null
,
sha256: data.sha256
||
null
,
compression_ratio: data.compression_ratio
||
null
,
status: data.status
||
null
,
trashed_at: data.trashed_at
||
null
,
purge_after: data.purge_after
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await storage_objects.setBucket( data.bucket || null, {
transaction,
});
await storage_objects.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'thumbnail_image',
belongsToId: storage_objects.id,
},
data.thumbnail_image,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'preview_file',
belongsToId: storage_objects.id,
},
data.preview_file,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'original_file',
belongsToId: storage_objects.id,
},
data.original_file,
options,
);
return storage_objects;
}
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 storage_objectsData = data.map((item, index) => ({
id: item.id || undefined,
object_key: item.object_key
||
null
,
content_type: item.content_type
||
null
,
size_bytes: item.size_bytes
||
null
,
etag: item.etag
||
null
,
sha256: item.sha256
||
null
,
compression_ratio: item.compression_ratio
||
null
,
status: item.status
||
null
,
trashed_at: item.trashed_at
||
null
,
purge_after: item.purge_after
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const storage_objects = await db.storage_objects.bulkCreate(storage_objectsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < storage_objects.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'thumbnail_image',
belongsToId: storage_objects[i].id,
},
data[i].thumbnail_image,
options,
);
}
for (let i = 0; i < storage_objects.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'preview_file',
belongsToId: storage_objects[i].id,
},
data[i].preview_file,
options,
);
}
for (let i = 0; i < storage_objects.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'original_file',
belongsToId: storage_objects[i].id,
},
data[i].original_file,
options,
);
}
return storage_objects;
}
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 storage_objects = await db.storage_objects.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.object_key !== undefined) updatePayload.object_key = data.object_key;
if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
if (data.size_bytes !== undefined) updatePayload.size_bytes = data.size_bytes;
if (data.etag !== undefined) updatePayload.etag = data.etag;
if (data.sha256 !== undefined) updatePayload.sha256 = data.sha256;
if (data.compression_ratio !== undefined) updatePayload.compression_ratio = data.compression_ratio;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.trashed_at !== undefined) updatePayload.trashed_at = data.trashed_at;
if (data.purge_after !== undefined) updatePayload.purge_after = data.purge_after;
updatePayload.updatedById = currentUser.id;
await storage_objects.update(updatePayload, {transaction});
if (data.bucket !== undefined) {
await storage_objects.setBucket(
data.bucket,
{ transaction }
);
}
if (data.organizations !== undefined) {
await storage_objects.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'thumbnail_image',
belongsToId: storage_objects.id,
},
data.thumbnail_image,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'preview_file',
belongsToId: storage_objects.id,
},
data.preview_file,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'original_file',
belongsToId: storage_objects.id,
},
data.original_file,
options,
);
return storage_objects;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const storage_objects = await db.storage_objects.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of storage_objects) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of storage_objects) {
await record.destroy({transaction});
}
});
return storage_objects;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const storage_objects = await db.storage_objects.findByPk(id, options);
await storage_objects.update({
deletedBy: currentUser.id
}, {
transaction,
});
await storage_objects.destroy({
transaction
});
return storage_objects;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const storage_objects = await db.storage_objects.findOne(
{ where },
{ transaction },
);
if (!storage_objects) {
return storage_objects;
}
const output = storage_objects.get({plain: true});
output.media_items_storage_object = await storage_objects.getMedia_items_storage_object({
transaction
});
output.bucket = await storage_objects.getBucket({
transaction
});
output.thumbnail_image = await storage_objects.getThumbnail_image({
transaction
});
output.preview_file = await storage_objects.getPreview_file({
transaction
});
output.original_file = await storage_objects.getOriginal_file({
transaction
});
output.organizations = await storage_objects.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.storage_buckets,
as: 'bucket',
where: filter.bucket ? {
[Op.or]: [
{ id: { [Op.in]: filter.bucket.split('|').map(term => Utils.uuid(term)) } },
{
bucket_name: {
[Op.or]: filter.bucket.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'thumbnail_image',
},
{
model: db.file,
as: 'preview_file',
},
{
model: db.file,
as: 'original_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.object_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'storage_objects',
'object_key',
filter.object_key,
),
};
}
if (filter.content_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'storage_objects',
'content_type',
filter.content_type,
),
};
}
if (filter.etag) {
where = {
...where,
[Op.and]: Utils.ilike(
'storage_objects',
'etag',
filter.etag,
),
};
}
if (filter.sha256) {
where = {
...where,
[Op.and]: Utils.ilike(
'storage_objects',
'sha256',
filter.sha256,
),
};
}
if (filter.size_bytesRange) {
const [start, end] = filter.size_bytesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
size_bytes: {
...where.size_bytes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
size_bytes: {
...where.size_bytes,
[Op.lte]: end,
},
};
}
}
if (filter.compression_ratioRange) {
const [start, end] = filter.compression_ratioRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
compression_ratio: {
...where.compression_ratio,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
compression_ratio: {
...where.compression_ratio,
[Op.lte]: end,
},
};
}
}
if (filter.trashed_atRange) {
const [start, end] = filter.trashed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
trashed_at: {
...where.trashed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
trashed_at: {
...where.trashed_at,
[Op.lte]: end,
},
};
}
}
if (filter.purge_afterRange) {
const [start, end] = filter.purge_afterRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
purge_after: {
...where.purge_after,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
purge_after: {
...where.purge_after,
[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.storage_objects.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(
'storage_objects',
'object_key',
query,
),
],
};
}
const records = await db.storage_objects.findAll({
attributes: [ 'id', 'object_key' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['object_key', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.object_key,
}));
}
};

View File

@ -0,0 +1,674 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class StoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stories = await db.stories.create(
{
id: data.id || undefined,
title: data.title
||
null
,
description: data.description
||
null
,
status: data.status
||
null
,
starts_at: data.starts_at
||
null
,
ends_at: data.ends_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await stories.setAlbum( data.album || null, {
transaction,
});
await stories.setCreated_by( data.created_by || null, {
transaction,
});
await stories.setOrganizations( data.organizations || null, {
transaction,
});
await stories.setStory_items(data.story_items || [], {
transaction,
});
return stories;
}
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 storiesData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
description: item.description
||
null
,
status: item.status
||
null
,
starts_at: item.starts_at
||
null
,
ends_at: item.ends_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const stories = await db.stories.bulkCreate(storiesData, { transaction });
// For each item created, replace relation files
return stories;
}
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 stories = await db.stories.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at;
if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
updatePayload.updatedById = currentUser.id;
await stories.update(updatePayload, {transaction});
if (data.album !== undefined) {
await stories.setAlbum(
data.album,
{ transaction }
);
}
if (data.created_by !== undefined) {
await stories.setCreated_by(
data.created_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await stories.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.story_items !== undefined) {
await stories.setStory_items(data.story_items, { transaction });
}
return stories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stories = await db.stories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of stories) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of stories) {
await record.destroy({transaction});
}
});
return stories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stories = await db.stories.findByPk(id, options);
await stories.update({
deletedBy: currentUser.id
}, {
transaction,
});
await stories.destroy({
transaction
});
return stories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const stories = await db.stories.findOne(
{ where },
{ transaction },
);
if (!stories) {
return stories;
}
const output = stories.get({plain: true});
output.story_items_story = await stories.getStory_items_story({
transaction
});
output.album = await stories.getAlbum({
transaction
});
output.created_by = await stories.getCreated_by({
transaction
});
output.story_items = await stories.getStory_items({
transaction
});
output.organizations = await stories.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.albums,
as: 'album',
where: filter.album ? {
[Op.or]: [
{ id: { [Op.in]: filter.album.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.album.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'created_by',
where: filter.created_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.story_items,
as: 'story_items',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'stories',
'title',
filter.title,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'stories',
'description',
filter.description,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
starts_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ends_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.starts_atRange) {
const [start, end] = filter.starts_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
starts_at: {
...where.starts_at,
[Op.lte]: end,
},
};
}
}
if (filter.ends_atRange) {
const [start, end] = filter.ends_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.story_items) {
const searchTerms = filter.story_items.split('|');
include = [
{
model: db.story_items,
as: 'story_items_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
layout: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.stories.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(
'stories',
'title',
query,
),
],
};
}
const records = await db.stories.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,549 @@
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 Story_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const story_items = await db.story_items.create(
{
id: data.id || undefined,
sort_order: data.sort_order
||
null
,
layout: data.layout
||
null
,
overlay_text: data.overlay_text
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await story_items.setStory( data.story || null, {
transaction,
});
await story_items.setMedia_item( data.media_item || null, {
transaction,
});
await story_items.setOrganizations( data.organizations || null, {
transaction,
});
return story_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const story_itemsData = data.map((item, index) => ({
id: item.id || undefined,
sort_order: item.sort_order
||
null
,
layout: item.layout
||
null
,
overlay_text: item.overlay_text
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const story_items = await db.story_items.bulkCreate(story_itemsData, { transaction });
// For each item created, replace relation files
return story_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const story_items = await db.story_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.layout !== undefined) updatePayload.layout = data.layout;
if (data.overlay_text !== undefined) updatePayload.overlay_text = data.overlay_text;
updatePayload.updatedById = currentUser.id;
await story_items.update(updatePayload, {transaction});
if (data.story !== undefined) {
await story_items.setStory(
data.story,
{ transaction }
);
}
if (data.media_item !== undefined) {
await story_items.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.organizations !== undefined) {
await story_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return story_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const story_items = await db.story_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of story_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of story_items) {
await record.destroy({transaction});
}
});
return story_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const story_items = await db.story_items.findByPk(id, options);
await story_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await story_items.destroy({
transaction
});
return story_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const story_items = await db.story_items.findOne(
{ where },
{ transaction },
);
if (!story_items) {
return story_items;
}
const output = story_items.get({plain: true});
output.story = await story_items.getStory({
transaction
});
output.media_item = await story_items.getMedia_item({
transaction
});
output.organizations = await story_items.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.stories,
as: 'story',
where: filter.story ? {
[Op.or]: [
{ id: { [Op.in]: filter.story.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.story.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.overlay_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'story_items',
'overlay_text',
filter.overlay_text,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.layout) {
where = {
...where,
layout: filter.layout,
};
}
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.story_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'story_items',
'layout',
query,
),
],
};
}
const records = await db.story_items.findAll({
attributes: [ 'id', 'layout' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['layout', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.layout,
}));
}
};

446
backend/src/db/api/tags.js Normal file
View File

@ -0,0 +1,446 @@
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 TagsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tags = await db.tags.create(
{
id: data.id || undefined,
name: data.name
||
null
,
tag_type: data.tag_type
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tags.setOrganization(currentUser.organization.id || null, {
transaction,
});
return tags;
}
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 tagsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
tag_type: item.tag_type
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tags = await db.tags.bulkCreate(tagsData, { transaction });
// For each item created, replace relation files
return tags;
}
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 tags = await db.tags.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.tag_type !== undefined) updatePayload.tag_type = data.tag_type;
updatePayload.updatedById = currentUser.id;
await tags.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await tags.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
return tags;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tags = await db.tags.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tags) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tags) {
await record.destroy({transaction});
}
});
return tags;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tags = await db.tags.findByPk(id, options);
await tags.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tags.destroy({
transaction
});
return tags;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tags = await db.tags.findOne(
{ where },
{ transaction },
);
if (!tags) {
return tags;
}
const output = tags.get({plain: true});
output.media_ai_tags_tag = await tags.getMedia_ai_tags_tag({
transaction
});
output.media_user_tags_tag = await tags.getMedia_user_tags_tag({
transaction
});
output.organization = await tags.getOrganization({
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: 'organization',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'tags',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.tag_type) {
where = {
...where,
tag_type: filter.tag_type,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[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.tags.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(
'tags',
'name',
query,
),
],
};
}
const records = await db.tags.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,634 @@
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 Upload_filesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const upload_files = await db.upload_files.create(
{
id: data.id || undefined,
file_name: data.file_name
||
null
,
content_type: data.content_type
||
null
,
size_bytes: data.size_bytes
||
null
,
status: data.status
||
null
,
progress_percent: data.progress_percent
||
null
,
error_message: data.error_message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await upload_files.setUpload_session( data.upload_session || null, {
transaction,
});
await upload_files.setMedia_item( data.media_item || null, {
transaction,
});
await upload_files.setOrganizations( data.organizations || null, {
transaction,
});
return upload_files;
}
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 upload_filesData = data.map((item, index) => ({
id: item.id || undefined,
file_name: item.file_name
||
null
,
content_type: item.content_type
||
null
,
size_bytes: item.size_bytes
||
null
,
status: item.status
||
null
,
progress_percent: item.progress_percent
||
null
,
error_message: item.error_message
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const upload_files = await db.upload_files.bulkCreate(upload_filesData, { transaction });
// For each item created, replace relation files
return upload_files;
}
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 upload_files = await db.upload_files.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.file_name !== undefined) updatePayload.file_name = data.file_name;
if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
if (data.size_bytes !== undefined) updatePayload.size_bytes = data.size_bytes;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.progress_percent !== undefined) updatePayload.progress_percent = data.progress_percent;
if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
updatePayload.updatedById = currentUser.id;
await upload_files.update(updatePayload, {transaction});
if (data.upload_session !== undefined) {
await upload_files.setUpload_session(
data.upload_session,
{ transaction }
);
}
if (data.media_item !== undefined) {
await upload_files.setMedia_item(
data.media_item,
{ transaction }
);
}
if (data.organizations !== undefined) {
await upload_files.setOrganizations(
data.organizations,
{ transaction }
);
}
return upload_files;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const upload_files = await db.upload_files.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of upload_files) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of upload_files) {
await record.destroy({transaction});
}
});
return upload_files;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const upload_files = await db.upload_files.findByPk(id, options);
await upload_files.update({
deletedBy: currentUser.id
}, {
transaction,
});
await upload_files.destroy({
transaction
});
return upload_files;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const upload_files = await db.upload_files.findOne(
{ where },
{ transaction },
);
if (!upload_files) {
return upload_files;
}
const output = upload_files.get({plain: true});
output.upload_session = await upload_files.getUpload_session({
transaction
});
output.media_item = await upload_files.getMedia_item({
transaction
});
output.organizations = await upload_files.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.upload_sessions,
as: 'upload_session',
where: filter.upload_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.upload_session.split('|').map(term => Utils.uuid(term)) } },
{
status: {
[Op.or]: filter.upload_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.media_items,
as: 'media_item',
where: filter.media_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.media_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.file_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'upload_files',
'file_name',
filter.file_name,
),
};
}
if (filter.content_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'upload_files',
'content_type',
filter.content_type,
),
};
}
if (filter.error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'upload_files',
'error_message',
filter.error_message,
),
};
}
if (filter.size_bytesRange) {
const [start, end] = filter.size_bytesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
size_bytes: {
...where.size_bytes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
size_bytes: {
...where.size_bytes,
[Op.lte]: end,
},
};
}
}
if (filter.progress_percentRange) {
const [start, end] = filter.progress_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
progress_percent: {
...where.progress_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
progress_percent: {
...where.progress_percent,
[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.upload_files.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(
'upload_files',
'file_name',
query,
),
],
};
}
const records = await db.upload_files.findAll({
attributes: [ 'id', 'file_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['file_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.file_name,
}));
}
};

View File

@ -0,0 +1,719 @@
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 Upload_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const upload_sessions = await db.upload_sessions.create(
{
id: data.id || undefined,
status: data.status
||
null
,
total_files: data.total_files
||
null
,
completed_files: data.completed_files
||
null
,
failed_files: data.failed_files
||
null
,
started_at: data.started_at
||
null
,
completed_at: data.completed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await upload_sessions.setAlbum( data.album || null, {
transaction,
});
await upload_sessions.setInitiator( data.initiator || null, {
transaction,
});
await upload_sessions.setOrganizations( data.organizations || null, {
transaction,
});
await upload_sessions.setUpload_files(data.upload_files || [], {
transaction,
});
return upload_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 upload_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
total_files: item.total_files
||
null
,
completed_files: item.completed_files
||
null
,
failed_files: item.failed_files
||
null
,
started_at: item.started_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 upload_sessions = await db.upload_sessions.bulkCreate(upload_sessionsData, { transaction });
// For each item created, replace relation files
return upload_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 upload_sessions = await db.upload_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.total_files !== undefined) updatePayload.total_files = data.total_files;
if (data.completed_files !== undefined) updatePayload.completed_files = data.completed_files;
if (data.failed_files !== undefined) updatePayload.failed_files = data.failed_files;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
updatePayload.updatedById = currentUser.id;
await upload_sessions.update(updatePayload, {transaction});
if (data.album !== undefined) {
await upload_sessions.setAlbum(
data.album,
{ transaction }
);
}
if (data.initiator !== undefined) {
await upload_sessions.setInitiator(
data.initiator,
{ transaction }
);
}
if (data.organizations !== undefined) {
await upload_sessions.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.upload_files !== undefined) {
await upload_sessions.setUpload_files(data.upload_files, { transaction });
}
return upload_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const upload_sessions = await db.upload_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of upload_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of upload_sessions) {
await record.destroy({transaction});
}
});
return upload_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const upload_sessions = await db.upload_sessions.findByPk(id, options);
await upload_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await upload_sessions.destroy({
transaction
});
return upload_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const upload_sessions = await db.upload_sessions.findOne(
{ where },
{ transaction },
);
if (!upload_sessions) {
return upload_sessions;
}
const output = upload_sessions.get({plain: true});
output.upload_files_upload_session = await upload_sessions.getUpload_files_upload_session({
transaction
});
output.album = await upload_sessions.getAlbum({
transaction
});
output.initiator = await upload_sessions.getInitiator({
transaction
});
output.upload_files = await upload_sessions.getUpload_files({
transaction
});
output.organizations = await upload_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.albums,
as: 'album',
where: filter.album ? {
[Op.or]: [
{ id: { [Op.in]: filter.album.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.album.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'initiator',
where: filter.initiator ? {
[Op.or]: [
{ id: { [Op.in]: filter.initiator.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.initiator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.upload_files,
as: 'upload_files',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.total_filesRange) {
const [start, end] = filter.total_filesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_files: {
...where.total_files,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_files: {
...where.total_files,
[Op.lte]: end,
},
};
}
}
if (filter.completed_filesRange) {
const [start, end] = filter.completed_filesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_files: {
...where.completed_files,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_files: {
...where.completed_files,
[Op.lte]: end,
},
};
}
}
if (filter.failed_filesRange) {
const [start, end] = filter.failed_filesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
failed_files: {
...where.failed_files,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
failed_files: {
...where.failed_files,
[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.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.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.upload_files) {
const searchTerms = filter.upload_files.split('|');
include = [
{
model: db.upload_files,
as: 'upload_files_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.upload_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(
'upload_sessions',
'status',
query,
),
],
};
}
const records = await db.upload_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,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,624 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Watermark_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const watermark_profiles = await db.watermark_profiles.create(
{
id: data.id || undefined,
name: data.name
||
null
,
mode: data.mode
||
null
,
default_text_template: data.default_text_template
||
null
,
opacity: data.opacity
||
null
,
position: data.position
||
null
,
scale: data.scale
||
null
,
enabled: data.enabled
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await watermark_profiles.setOrganization(currentUser.organization.id || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.watermark_profiles.getTableName(),
belongsToColumn: 'watermark_image',
belongsToId: watermark_profiles.id,
},
data.watermark_image,
options,
);
return watermark_profiles;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const watermark_profilesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
mode: item.mode
||
null
,
default_text_template: item.default_text_template
||
null
,
opacity: item.opacity
||
null
,
position: item.position
||
null
,
scale: item.scale
||
null
,
enabled: item.enabled
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const watermark_profiles = await db.watermark_profiles.bulkCreate(watermark_profilesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < watermark_profiles.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.watermark_profiles.getTableName(),
belongsToColumn: 'watermark_image',
belongsToId: watermark_profiles[i].id,
},
data[i].watermark_image,
options,
);
}
return watermark_profiles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const watermark_profiles = await db.watermark_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.mode !== undefined) updatePayload.mode = data.mode;
if (data.default_text_template !== undefined) updatePayload.default_text_template = data.default_text_template;
if (data.opacity !== undefined) updatePayload.opacity = data.opacity;
if (data.position !== undefined) updatePayload.position = data.position;
if (data.scale !== undefined) updatePayload.scale = data.scale;
if (data.enabled !== undefined) updatePayload.enabled = data.enabled;
updatePayload.updatedById = currentUser.id;
await watermark_profiles.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await watermark_profiles.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.watermark_profiles.getTableName(),
belongsToColumn: 'watermark_image',
belongsToId: watermark_profiles.id,
},
data.watermark_image,
options,
);
return watermark_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const watermark_profiles = await db.watermark_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of watermark_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of watermark_profiles) {
await record.destroy({transaction});
}
});
return watermark_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const watermark_profiles = await db.watermark_profiles.findByPk(id, options);
await watermark_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await watermark_profiles.destroy({
transaction
});
return watermark_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const watermark_profiles = await db.watermark_profiles.findOne(
{ where },
{ transaction },
);
if (!watermark_profiles) {
return watermark_profiles;
}
const output = watermark_profiles.get({plain: true});
output.download_jobs_watermark_profile = await watermark_profiles.getDownload_jobs_watermark_profile({
transaction
});
output.organization = await watermark_profiles.getOrganization({
transaction
});
output.watermark_image = await watermark_profiles.getWatermark_image({
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: 'organization',
},
{
model: db.file,
as: 'watermark_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'watermark_profiles',
'name',
filter.name,
),
};
}
if (filter.default_text_template) {
where = {
...where,
[Op.and]: Utils.ilike(
'watermark_profiles',
'default_text_template',
filter.default_text_template,
),
};
}
if (filter.opacityRange) {
const [start, end] = filter.opacityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
opacity: {
...where.opacity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
opacity: {
...where.opacity,
[Op.lte]: end,
},
};
}
}
if (filter.scaleRange) {
const [start, end] = filter.scaleRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scale: {
...where.scale,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scale: {
...where.scale,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.mode) {
where = {
...where,
mode: filter.mode,
};
}
if (filter.position) {
where = {
...where,
position: filter.position,
};
}
if (filter.enabled) {
where = {
...where,
enabled: filter.enabled,
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[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.watermark_profiles.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'watermark_profiles',
'name',
query,
),
],
};
}
const records = await db.watermark_profiles.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,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_event_media_platform',
host: process.env.DB_HOST || 'localhost',
logging: console.log,
seederStorage: 'sequelize',
},
dev_stage: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
}
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,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,190 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const access_rules = sequelize.define(
'access_rules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
subject_type: {
type: DataTypes.ENUM,
values: [
"role",
"user",
"membership"
],
},
permission: {
type: DataTypes.ENUM,
values: [
"view",
"upload",
"comment",
"like",
"download",
"manage"
],
},
expires_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
access_rules.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.access_rules.belongsTo(db.albums, {
as: 'album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.access_rules.belongsTo(db.roles, {
as: 'role',
foreignKey: {
name: 'roleId',
},
constraints: false,
});
db.access_rules.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.access_rules.belongsTo(db.memberships, {
as: 'membership',
foreignKey: {
name: 'membershipId',
},
constraints: false,
});
db.access_rules.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.access_rules.belongsTo(db.users, {
as: 'createdBy',
});
db.access_rules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return access_rules;
};

View File

@ -0,0 +1,156 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ai_captions = sequelize.define(
'ai_captions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
caption_text: {
type: DataTypes.TEXT,
},
confidence: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"generated",
"edited",
"approved",
"rejected"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ai_captions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.ai_captions.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.ai_captions.belongsTo(db.ai_models, {
as: 'ai_model',
foreignKey: {
name: 'ai_modelId',
},
constraints: false,
});
db.ai_captions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.ai_captions.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_captions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_captions;
};

View File

@ -0,0 +1,183 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ai_embeddings = sequelize.define(
'ai_embeddings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
vector_ref: {
type: DataTypes.TEXT,
},
dimensions: {
type: DataTypes.INTEGER,
},
embedding_type: {
type: DataTypes.ENUM,
values: [
"image",
"text",
"face"
],
},
quality_score: {
type: DataTypes.DECIMAL,
},
indexed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ai_embeddings.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_embeddings.hasMany(db.face_detections, {
as: 'face_detections_face_embedding',
foreignKey: {
name: 'face_embeddingId',
},
constraints: false,
});
db.ai_embeddings.hasMany(db.selfie_references, {
as: 'selfie_references_selfie_embedding',
foreignKey: {
name: 'selfie_embeddingId',
},
constraints: false,
});
//end loop
db.ai_embeddings.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.ai_embeddings.belongsTo(db.ai_models, {
as: 'ai_model',
foreignKey: {
name: 'ai_modelId',
},
constraints: false,
});
db.ai_embeddings.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.ai_embeddings.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_embeddings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_embeddings;
};

View File

@ -0,0 +1,201 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const 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: [
"tagging",
"embedding",
"face_recognition",
"captioning",
"moderation",
"duplicate_detection"
],
},
provider: {
type: DataTypes.TEXT,
},
version: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"disabled"
],
},
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.ai_embeddings, {
as: 'ai_embeddings_ai_model',
foreignKey: {
name: 'ai_modelId',
},
constraints: false,
});
db.ai_models.hasMany(db.face_detections, {
as: 'face_detections_ai_model',
foreignKey: {
name: 'ai_modelId',
},
constraints: false,
});
db.ai_models.hasMany(db.selfie_references, {
as: 'selfie_references_ai_model',
foreignKey: {
name: 'ai_modelId',
},
constraints: false,
});
db.ai_models.hasMany(db.ai_captions, {
as: 'ai_captions_ai_model',
foreignKey: {
name: 'ai_modelId',
},
constraints: false,
});
//end loop
db.ai_models.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
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,165 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const album_collaborators = sequelize.define(
'album_collaborators',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
role: {
type: DataTypes.ENUM,
values: [
"admin",
"contributor",
"viewer"
],
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"invited",
"removed"
],
},
invited_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
album_collaborators.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.album_collaborators.belongsTo(db.albums, {
as: 'album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.album_collaborators.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.album_collaborators.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.album_collaborators.belongsTo(db.users, {
as: 'createdBy',
});
db.album_collaborators.belongsTo(db.users, {
as: 'updatedBy',
});
};
return album_collaborators;
};

View File

@ -0,0 +1,366 @@
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 albums = sequelize.define(
'albums',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
privacy: {
type: DataTypes.ENUM,
values: [
"public",
"unlisted",
"private"
],
},
collaboration_mode: {
type: DataTypes.ENUM,
values: [
"owner_only",
"members_can_add",
"anyone_with_link_can_add"
],
},
allow_downloads: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
allow_comments: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
allow_likes: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
allow_tagging: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
albums.associate = (db) => {
db.albums.belongsToMany(db.album_collaborators, {
as: 'collaborators',
foreignKey: {
name: 'albums_collaboratorsId',
},
constraints: false,
through: 'albumsCollaboratorsAlbum_collaborators',
});
db.albums.belongsToMany(db.album_collaborators, {
as: 'collaborators_filter',
foreignKey: {
name: 'albums_collaboratorsId',
},
constraints: false,
through: 'albumsCollaboratorsAlbum_collaborators',
});
db.albums.belongsToMany(db.access_rules, {
as: 'access_rules',
foreignKey: {
name: 'albums_access_rulesId',
},
constraints: false,
through: 'albumsAccess_rulesAccess_rules',
});
db.albums.belongsToMany(db.access_rules, {
as: 'access_rules_filter',
foreignKey: {
name: 'albums_access_rulesId',
},
constraints: false,
through: 'albumsAccess_rulesAccess_rules',
});
db.albums.belongsToMany(db.shares, {
as: 'shares',
foreignKey: {
name: 'albums_sharesId',
},
constraints: false,
through: 'albumsSharesShares',
});
db.albums.belongsToMany(db.shares, {
as: 'shares_filter',
foreignKey: {
name: 'albums_sharesId',
},
constraints: false,
through: 'albumsSharesShares',
});
db.albums.belongsToMany(db.stories, {
as: 'stories',
foreignKey: {
name: 'albums_storiesId',
},
constraints: false,
through: 'albumsStoriesStories',
});
db.albums.belongsToMany(db.stories, {
as: 'stories_filter',
foreignKey: {
name: 'albums_storiesId',
},
constraints: false,
through: 'albumsStoriesStories',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.albums.hasMany(db.events, {
as: 'events_default_album',
foreignKey: {
name: 'default_albumId',
},
constraints: false,
});
db.albums.hasMany(db.album_collaborators, {
as: 'album_collaborators_album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.albums.hasMany(db.access_rules, {
as: 'access_rules_album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.albums.hasMany(db.media_items, {
as: 'media_items_album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.albums.hasMany(db.upload_sessions, {
as: 'upload_sessions_album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.albums.hasMany(db.notifications, {
as: 'notifications_album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.albums.hasMany(db.shares, {
as: 'shares_album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.albums.hasMany(db.stories, {
as: 'stories_album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.albums.hasMany(db.analytics_events, {
as: 'analytics_events_album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
//end loop
db.albums.belongsTo(db.events, {
as: 'event',
foreignKey: {
name: 'eventId',
},
constraints: false,
});
db.albums.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.albums.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.albums.hasMany(db.file, {
as: 'cover_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.albums.getTableName(),
belongsToColumn: 'cover_image',
},
});
db.albums.belongsTo(db.users, {
as: 'createdBy',
});
db.albums.belongsTo(db.users, {
as: 'updatedBy',
});
};
return albums;
};

View File

@ -0,0 +1,187 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const analytics_events = sequelize.define(
'analytics_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_type: {
type: DataTypes.ENUM,
values: [
"view",
"like",
"comment",
"share",
"download",
"upload",
"search",
"login",
"signup"
],
},
metadata_json: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
analytics_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.analytics_events.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.analytics_events.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.analytics_events.belongsTo(db.events, {
as: 'event',
foreignKey: {
name: 'eventId',
},
constraints: false,
});
db.analytics_events.belongsTo(db.albums, {
as: 'album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.analytics_events.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.analytics_events.belongsTo(db.users, {
as: 'createdBy',
});
db.analytics_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return analytics_events;
};

View File

@ -0,0 +1,190 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const comments = sequelize.define(
'comments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
content: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"visible",
"hidden",
"deleted",
"flagged"
],
},
posted_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
comments.associate = (db) => {
db.comments.belongsToMany(db.mentions, {
as: 'mentions',
foreignKey: {
name: 'comments_mentionsId',
},
constraints: false,
through: 'commentsMentionsMentions',
});
db.comments.belongsToMany(db.mentions, {
as: 'mentions_filter',
foreignKey: {
name: 'comments_mentionsId',
},
constraints: false,
through: 'commentsMentionsMentions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.comments.hasMany(db.mentions, {
as: 'mentions_comment',
foreignKey: {
name: 'commentId',
},
constraints: false,
});
//end loop
db.comments.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.comments.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.comments.belongsTo(db.comments, {
as: 'parent_comment',
foreignKey: {
name: 'parent_commentId',
},
constraints: false,
});
db.comments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.comments.belongsTo(db.users, {
as: 'createdBy',
});
db.comments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return comments;
};

View File

@ -0,0 +1,188 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const download_jobs = sequelize.define(
'download_jobs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"processing",
"ready",
"failed"
],
},
watermark_text: {
type: DataTypes.TEXT,
},
requested_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
error_message: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
download_jobs.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.download_jobs.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.download_jobs.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.download_jobs.belongsTo(db.watermark_profiles, {
as: 'watermark_profile',
foreignKey: {
name: 'watermark_profileId',
},
constraints: false,
});
db.download_jobs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.download_jobs.hasMany(db.file, {
as: 'output_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.download_jobs.getTableName(),
belongsToColumn: 'output_file',
},
});
db.download_jobs.belongsTo(db.users, {
as: 'createdBy',
});
db.download_jobs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return download_jobs;
};

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 events = sequelize.define(
'events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
category: {
type: DataTypes.ENUM,
values: [
"photoshoot",
"workshop",
"fest",
"trip",
"competition",
"party",
"conference",
"meetup",
"other"
],
},
starts_at: {
type: DataTypes.DATE,
},
ends_at: {
type: DataTypes.DATE,
},
privacy: {
type: DataTypes.ENUM,
values: [
"public",
"unlisted",
"private"
],
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"archived"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
events.associate = (db) => {
db.events.belongsToMany(db.albums, {
as: 'albums',
foreignKey: {
name: 'events_albumsId',
},
constraints: false,
through: 'eventsAlbumsAlbums',
});
db.events.belongsToMany(db.albums, {
as: 'albums_filter',
foreignKey: {
name: 'events_albumsId',
},
constraints: false,
through: 'eventsAlbumsAlbums',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.events.hasMany(db.albums, {
as: 'albums_event',
foreignKey: {
name: 'eventId',
},
constraints: false,
});
db.events.hasMany(db.notifications, {
as: 'notifications_event',
foreignKey: {
name: 'eventId',
},
constraints: false,
});
db.events.hasMany(db.analytics_events, {
as: 'analytics_events_event',
foreignKey: {
name: 'eventId',
},
constraints: false,
});
//end loop
db.events.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.events.belongsTo(db.albums, {
as: 'default_album',
foreignKey: {
name: 'default_albumId',
},
constraints: false,
});
db.events.hasMany(db.file, {
as: 'cover_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.events.getTableName(),
belongsToColumn: 'cover_image',
},
});
db.events.belongsTo(db.users, {
as: 'createdBy',
});
db.events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return events;
};

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 face_detections = sequelize.define(
'face_detections',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
bbox_x: {
type: DataTypes.DECIMAL,
},
bbox_y: {
type: DataTypes.DECIMAL,
},
bbox_width: {
type: DataTypes.DECIMAL,
},
bbox_height: {
type: DataTypes.DECIMAL,
},
confidence: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
face_detections.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.face_detections.hasMany(db.face_matches, {
as: 'face_matches_face_detection',
foreignKey: {
name: 'face_detectionId',
},
constraints: false,
});
//end loop
db.face_detections.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.face_detections.belongsTo(db.ai_models, {
as: 'ai_model',
foreignKey: {
name: 'ai_modelId',
},
constraints: false,
});
db.face_detections.belongsTo(db.ai_embeddings, {
as: 'face_embedding',
foreignKey: {
name: 'face_embeddingId',
},
constraints: false,
});
db.face_detections.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.face_detections.belongsTo(db.users, {
as: 'createdBy',
});
db.face_detections.belongsTo(db.users, {
as: 'updatedBy',
});
};
return face_detections;
};

View File

@ -0,0 +1,156 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const face_matches = sequelize.define(
'face_matches',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
match_score: {
type: DataTypes.DECIMAL,
},
confidence_badge: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high",
"very_high"
],
},
matched_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
face_matches.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.face_matches.belongsTo(db.selfie_references, {
as: 'selfie_reference',
foreignKey: {
name: 'selfie_referenceId',
},
constraints: false,
});
db.face_matches.belongsTo(db.face_detections, {
as: 'face_detection',
foreignKey: {
name: 'face_detectionId',
},
constraints: false,
});
db.face_matches.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.face_matches.belongsTo(db.users, {
as: 'createdBy',
});
db.face_matches.belongsTo(db.users, {
as: 'updatedBy',
});
};
return face_matches;
};

View File

@ -0,0 +1,127 @@
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 favourites = sequelize.define(
'favourites',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
saved_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
favourites.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.favourites.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.favourites.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.favourites.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.favourites.belongsTo(db.users, {
as: 'createdBy',
});
db.favourites.belongsTo(db.users, {
as: 'updatedBy',
});
};
return favourites;
};

View File

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

View File

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

View File

@ -0,0 +1,127 @@
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 likes = sequelize.define(
'likes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
liked_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
likes.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.likes.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.likes.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.likes.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.likes.belongsTo(db.users, {
as: 'createdBy',
});
db.likes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return likes;
};

View File

@ -0,0 +1,146 @@
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 media_ai_tags = sequelize.define(
'media_ai_tags',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
confidence: {
type: DataTypes.DECIMAL,
},
source: {
type: DataTypes.ENUM,
values: [
"vision_api",
"custom_model",
"manual_review"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
media_ai_tags.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.media_ai_tags.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_ai_tags.belongsTo(db.tags, {
as: 'tag',
foreignKey: {
name: 'tagId',
},
constraints: false,
});
db.media_ai_tags.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.media_ai_tags.belongsTo(db.users, {
as: 'createdBy',
});
db.media_ai_tags.belongsTo(db.users, {
as: 'updatedBy',
});
};
return media_ai_tags;
};

View File

@ -0,0 +1,524 @@
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 media_items = sequelize.define(
'media_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
media_type: {
type: DataTypes.ENUM,
values: [
"photo",
"video"
],
},
title: {
type: DataTypes.TEXT,
},
caption: {
type: DataTypes.TEXT,
},
captured_at: {
type: DataTypes.DATE,
},
uploaded_at: {
type: DataTypes.DATE,
},
width: {
type: DataTypes.INTEGER,
},
height: {
type: DataTypes.INTEGER,
},
duration_seconds: {
type: DataTypes.DECIMAL,
},
camera_make: {
type: DataTypes.TEXT,
},
camera_model: {
type: DataTypes.TEXT,
},
gps_latitude: {
type: DataTypes.DECIMAL,
},
gps_longitude: {
type: DataTypes.DECIMAL,
},
visibility: {
type: DataTypes.ENUM,
values: [
"visible",
"hidden",
"flagged",
"deleted"
],
},
is_duplicate: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
duplicate_group_key: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
media_items.associate = (db) => {
db.media_items.belongsToMany(db.media_ai_tags, {
as: 'ai_tags',
foreignKey: {
name: 'media_items_ai_tagsId',
},
constraints: false,
through: 'media_itemsAi_tagsMedia_ai_tags',
});
db.media_items.belongsToMany(db.media_ai_tags, {
as: 'ai_tags_filter',
foreignKey: {
name: 'media_items_ai_tagsId',
},
constraints: false,
through: 'media_itemsAi_tagsMedia_ai_tags',
});
db.media_items.belongsToMany(db.media_user_tags, {
as: 'user_tags',
foreignKey: {
name: 'media_items_user_tagsId',
},
constraints: false,
through: 'media_itemsUser_tagsMedia_user_tags',
});
db.media_items.belongsToMany(db.media_user_tags, {
as: 'user_tags_filter',
foreignKey: {
name: 'media_items_user_tagsId',
},
constraints: false,
through: 'media_itemsUser_tagsMedia_user_tags',
});
db.media_items.belongsToMany(db.likes, {
as: 'likes',
foreignKey: {
name: 'media_items_likesId',
},
constraints: false,
through: 'media_itemsLikesLikes',
});
db.media_items.belongsToMany(db.likes, {
as: 'likes_filter',
foreignKey: {
name: 'media_items_likesId',
},
constraints: false,
through: 'media_itemsLikesLikes',
});
db.media_items.belongsToMany(db.comments, {
as: 'comments',
foreignKey: {
name: 'media_items_commentsId',
},
constraints: false,
through: 'media_itemsCommentsComments',
});
db.media_items.belongsToMany(db.comments, {
as: 'comments_filter',
foreignKey: {
name: 'media_items_commentsId',
},
constraints: false,
through: 'media_itemsCommentsComments',
});
db.media_items.belongsToMany(db.favourites, {
as: 'saves',
foreignKey: {
name: 'media_items_savesId',
},
constraints: false,
through: 'media_itemsSavesFavourites',
});
db.media_items.belongsToMany(db.favourites, {
as: 'saves_filter',
foreignKey: {
name: 'media_items_savesId',
},
constraints: false,
through: 'media_itemsSavesFavourites',
});
db.media_items.belongsToMany(db.mentions, {
as: 'mentions',
foreignKey: {
name: 'media_items_mentionsId',
},
constraints: false,
through: 'media_itemsMentionsMentions',
});
db.media_items.belongsToMany(db.mentions, {
as: 'mentions_filter',
foreignKey: {
name: 'media_items_mentionsId',
},
constraints: false,
through: 'media_itemsMentionsMentions',
});
db.media_items.belongsToMany(db.face_detections, {
as: 'face_detections',
foreignKey: {
name: 'media_items_face_detectionsId',
},
constraints: false,
through: 'media_itemsFace_detectionsFace_detections',
});
db.media_items.belongsToMany(db.face_detections, {
as: 'face_detections_filter',
foreignKey: {
name: 'media_items_face_detectionsId',
},
constraints: false,
through: 'media_itemsFace_detectionsFace_detections',
});
db.media_items.belongsToMany(db.download_jobs, {
as: 'watermarked_downloads',
foreignKey: {
name: 'media_items_watermarked_downloadsId',
},
constraints: false,
through: 'media_itemsWatermarked_downloadsDownload_jobs',
});
db.media_items.belongsToMany(db.download_jobs, {
as: 'watermarked_downloads_filter',
foreignKey: {
name: 'media_items_watermarked_downloadsId',
},
constraints: false,
through: 'media_itemsWatermarked_downloadsDownload_jobs',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.media_items.hasMany(db.upload_files, {
as: 'upload_files_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.media_ai_tags, {
as: 'media_ai_tags_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.media_user_tags, {
as: 'media_user_tags_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.likes, {
as: 'likes_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.favourites, {
as: 'favourites_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.comments, {
as: 'comments_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.mentions, {
as: 'mentions_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.notifications, {
as: 'notifications_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.download_jobs, {
as: 'download_jobs_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.ai_embeddings, {
as: 'ai_embeddings_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.face_detections, {
as: 'face_detections_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.ai_captions, {
as: 'ai_captions_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.moderation_flags, {
as: 'moderation_flags_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.story_items, {
as: 'story_items_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_items.hasMany(db.analytics_events, {
as: 'analytics_events_media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
//end loop
db.media_items.belongsTo(db.albums, {
as: 'album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.media_items.belongsTo(db.users, {
as: 'uploader',
foreignKey: {
name: 'uploaderId',
},
constraints: false,
});
db.media_items.belongsTo(db.storage_objects, {
as: 'storage_object',
foreignKey: {
name: 'storage_objectId',
},
constraints: false,
});
db.media_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.media_items.belongsTo(db.users, {
as: 'createdBy',
});
db.media_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return media_items;
};

View File

@ -0,0 +1,128 @@
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 media_user_tags = sequelize.define(
'media_user_tags',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
media_user_tags.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.media_user_tags.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.media_user_tags.belongsTo(db.tags, {
as: 'tag',
foreignKey: {
name: 'tagId',
},
constraints: false,
});
db.media_user_tags.belongsTo(db.users, {
as: 'tagged_by',
foreignKey: {
name: 'tagged_byId',
},
constraints: false,
});
db.media_user_tags.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.media_user_tags.belongsTo(db.users, {
as: 'createdBy',
});
db.media_user_tags.belongsTo(db.users, {
as: 'updatedBy',
});
};
return media_user_tags;
};

View File

@ -0,0 +1,157 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const memberships = sequelize.define(
'memberships',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"pending",
"invited",
"removed"
],
},
joined_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
memberships.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.memberships.hasMany(db.access_rules, {
as: 'access_rules_membership',
foreignKey: {
name: 'membershipId',
},
constraints: false,
});
//end loop
db.memberships.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.memberships.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.memberships.belongsTo(db.roles, {
as: 'role',
foreignKey: {
name: 'roleId',
},
constraints: false,
});
db.memberships.belongsTo(db.users, {
as: 'createdBy',
});
db.memberships.belongsTo(db.users, {
as: 'updatedBy',
});
};
return memberships;
};

View File

@ -0,0 +1,128 @@
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 mentions = sequelize.define(
'mentions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
mentions.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.mentions.belongsTo(db.comments, {
as: 'comment',
foreignKey: {
name: 'commentId',
},
constraints: false,
});
db.mentions.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.mentions.belongsTo(db.users, {
as: 'mentioned_user',
foreignKey: {
name: 'mentioned_userId',
},
constraints: false,
});
db.mentions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.mentions.belongsTo(db.users, {
as: 'createdBy',
});
db.mentions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return mentions;
};

View File

@ -0,0 +1,199 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const moderation_flags = sequelize.define(
'moderation_flags',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
reason: {
type: DataTypes.ENUM,
values: [
"nudity",
"violence",
"hate",
"spam",
"copyright",
"other"
],
},
details: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"in_review",
"resolved",
"dismissed"
],
},
reported_at: {
type: DataTypes.DATE,
},
resolved_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
moderation_flags.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.moderation_flags.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.moderation_flags.belongsTo(db.users, {
as: 'reported_by',
foreignKey: {
name: 'reported_byId',
},
constraints: false,
});
db.moderation_flags.belongsTo(db.users, {
as: 'reviewed_by',
foreignKey: {
name: 'reviewed_byId',
},
constraints: false,
});
db.moderation_flags.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.moderation_flags.belongsTo(db.users, {
as: 'createdBy',
});
db.moderation_flags.belongsTo(db.users, {
as: 'updatedBy',
});
};
return moderation_flags;
};

View File

@ -0,0 +1,191 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const notification_preferences = sequelize.define(
'notification_preferences',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
channel: {
type: DataTypes.ENUM,
values: [
"in_app",
"email",
"push"
],
},
likes_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
comments_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
tags_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
mentions_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
shares_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
uploads_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notification_preferences.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.notification_preferences.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.notification_preferences.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.notification_preferences.belongsTo(db.users, {
as: 'createdBy',
});
db.notification_preferences.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notification_preferences;
};

View File

@ -0,0 +1,217 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const notifications = sequelize.define(
'notifications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
type: {
type: DataTypes.ENUM,
values: [
"like",
"comment",
"reply",
"tag",
"mention",
"share",
"upload_complete",
"album_update",
"event_update",
"moderation",
"system"
],
},
title: {
type: DataTypes.TEXT,
},
body: {
type: DataTypes.TEXT,
},
is_read: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
read_at: {
type: DataTypes.DATE,
},
sent_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notifications.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.notifications.belongsTo(db.users, {
as: 'recipient',
foreignKey: {
name: 'recipientId',
},
constraints: false,
});
db.notifications.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.notifications.belongsTo(db.events, {
as: 'event',
foreignKey: {
name: 'eventId',
},
constraints: false,
});
db.notifications.belongsTo(db.albums, {
as: 'album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.notifications.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.notifications.belongsTo(db.users, {
as: 'createdBy',
});
db.notifications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notifications;
};

View File

@ -0,0 +1,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 oauth_accounts = sequelize.define(
'oauth_accounts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
provider: {
type: DataTypes.ENUM,
values: [
"google",
"apple",
"github",
"facebook"
],
},
provider_user_key: {
type: DataTypes.TEXT,
},
access_token: {
type: DataTypes.TEXT,
},
refresh_token: {
type: DataTypes.TEXT,
},
token_expires_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
oauth_accounts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.oauth_accounts.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.oauth_accounts.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.oauth_accounts.belongsTo(db.users, {
as: 'createdBy',
});
db.oauth_accounts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return oauth_accounts;
};

View File

@ -0,0 +1,383 @@
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.role_permissions, {
as: 'role_permissions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.memberships, {
as: 'memberships_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.events, {
as: 'events_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.albums, {
as: 'albums_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.album_collaborators, {
as: 'album_collaborators_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.access_rules, {
as: 'access_rules_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.media_items, {
as: 'media_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.storage_buckets, {
as: 'storage_buckets_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.storage_objects, {
as: 'storage_objects_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.upload_sessions, {
as: 'upload_sessions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.upload_files, {
as: 'upload_files_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.tags, {
as: 'tags_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.media_ai_tags, {
as: 'media_ai_tags_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.media_user_tags, {
as: 'media_user_tags_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.likes, {
as: 'likes_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.favourites, {
as: 'favourites_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.comments, {
as: 'comments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.mentions, {
as: 'mentions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.notifications, {
as: 'notifications_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.notification_preferences, {
as: 'notification_preferences_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.shares, {
as: 'shares_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.download_jobs, {
as: 'download_jobs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.watermark_profiles, {
as: 'watermark_profiles_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.ai_models, {
as: 'ai_models_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.ai_embeddings, {
as: 'ai_embeddings_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.face_detections, {
as: 'face_detections_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.selfie_references, {
as: 'selfie_references_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.face_matches, {
as: 'face_matches_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.ai_captions, {
as: 'ai_captions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.moderation_flags, {
as: 'moderation_flags_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.stories, {
as: 'stories_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.story_items, {
as: 'story_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.analytics_events, {
as: 'analytics_events_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.oauth_accounts, {
as: 'oauth_accounts_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,103 @@
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,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 role_permissions = sequelize.define(
'role_permissions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
resource: {
type: DataTypes.ENUM,
values: [
"users",
"organizations",
"events",
"albums",
"media",
"comments",
"likes",
"tags",
"shares",
"storage",
"ai_search",
"moderation",
"analytics",
"notifications"
],
},
action: {
type: DataTypes.ENUM,
values: [
"create",
"read",
"update",
"delete",
"manage",
"moderate",
"download",
"share"
],
},
allowed: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
role_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.role_permissions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.role_permissions.belongsTo(db.users, {
as: 'createdBy',
});
db.role_permissions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return role_permissions;
};

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 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,
});
db.roles.hasMany(db.memberships, {
as: 'memberships_role',
foreignKey: {
name: 'roleId',
},
constraints: false,
});
db.roles.hasMany(db.access_rules, {
as: 'access_rules_role',
foreignKey: {
name: '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,172 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const selfie_references = sequelize.define(
'selfie_references',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"ready",
"failed"
],
},
uploaded_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
selfie_references.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.selfie_references.hasMany(db.face_matches, {
as: 'face_matches_selfie_reference',
foreignKey: {
name: 'selfie_referenceId',
},
constraints: false,
});
//end loop
db.selfie_references.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.selfie_references.belongsTo(db.ai_models, {
as: 'ai_model',
foreignKey: {
name: 'ai_modelId',
},
constraints: false,
});
db.selfie_references.belongsTo(db.ai_embeddings, {
as: 'selfie_embedding',
foreignKey: {
name: 'selfie_embeddingId',
},
constraints: false,
});
db.selfie_references.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.selfie_references.hasMany(db.file, {
as: 'selfie_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.selfie_references.getTableName(),
belongsToColumn: 'selfie_image',
},
});
db.selfie_references.belongsTo(db.users, {
as: 'createdBy',
});
db.selfie_references.belongsTo(db.users, {
as: 'updatedBy',
});
};
return selfie_references;
};

View File

@ -0,0 +1,206 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const shares = sequelize.define(
'shares',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
share_type: {
type: DataTypes.ENUM,
values: [
"public_link",
"private_link",
"qr"
],
},
token: {
type: DataTypes.TEXT,
},
access_level: {
type: DataTypes.ENUM,
values: [
"view",
"upload",
"comment",
"download"
],
},
expires_at: {
type: DataTypes.DATE,
},
max_uses: {
type: DataTypes.INTEGER,
},
uses_count: {
type: DataTypes.INTEGER,
},
revoked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
revoked_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
shares.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.shares.belongsTo(db.albums, {
as: 'album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.shares.belongsTo(db.users, {
as: 'created_by',
foreignKey: {
name: 'created_byId',
},
constraints: false,
});
db.shares.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.shares.belongsTo(db.users, {
as: 'createdBy',
});
db.shares.belongsTo(db.users, {
as: 'updatedBy',
});
};
return shares;
};

View File

@ -0,0 +1,184 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const storage_buckets = sequelize.define(
'storage_buckets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
provider: {
type: DataTypes.TEXT,
},
bucket_name: {
type: DataTypes.TEXT,
},
region: {
type: DataTypes.TEXT,
},
cdn_domain: {
type: DataTypes.TEXT,
},
default_bucket: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"disabled"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
storage_buckets.associate = (db) => {
db.storage_buckets.belongsToMany(db.storage_objects, {
as: 'storage_objects',
foreignKey: {
name: 'storage_buckets_storage_objectsId',
},
constraints: false,
through: 'storage_bucketsStorage_objectsStorage_objects',
});
db.storage_buckets.belongsToMany(db.storage_objects, {
as: 'storage_objects_filter',
foreignKey: {
name: 'storage_buckets_storage_objectsId',
},
constraints: false,
through: 'storage_bucketsStorage_objectsStorage_objects',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.storage_buckets.hasMany(db.storage_objects, {
as: 'storage_objects_bucket',
foreignKey: {
name: 'bucketId',
},
constraints: false,
});
//end loop
db.storage_buckets.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.storage_buckets.belongsTo(db.users, {
as: 'createdBy',
});
db.storage_buckets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return storage_buckets;
};

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 storage_objects = sequelize.define(
'storage_objects',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
object_key: {
type: DataTypes.TEXT,
},
content_type: {
type: DataTypes.TEXT,
},
size_bytes: {
type: DataTypes.INTEGER,
},
etag: {
type: DataTypes.TEXT,
},
sha256: {
type: DataTypes.TEXT,
},
compression_ratio: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"uploading",
"ready",
"processing",
"failed",
"deleted",
"trashed"
],
},
trashed_at: {
type: DataTypes.DATE,
},
purge_after: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
storage_objects.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.storage_objects.hasMany(db.media_items, {
as: 'media_items_storage_object',
foreignKey: {
name: 'storage_objectId',
},
constraints: false,
});
//end loop
db.storage_objects.belongsTo(db.storage_buckets, {
as: 'bucket',
foreignKey: {
name: 'bucketId',
},
constraints: false,
});
db.storage_objects.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.storage_objects.hasMany(db.file, {
as: 'thumbnail_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'thumbnail_image',
},
});
db.storage_objects.hasMany(db.file, {
as: 'preview_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'preview_file',
},
});
db.storage_objects.hasMany(db.file, {
as: 'original_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.storage_objects.getTableName(),
belongsToColumn: 'original_file',
},
});
db.storage_objects.belongsTo(db.users, {
as: 'createdBy',
});
db.storage_objects.belongsTo(db.users, {
as: 'updatedBy',
});
};
return storage_objects;
};

View File

@ -0,0 +1,193 @@
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 stories = sequelize.define(
'stories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"archived"
],
},
starts_at: {
type: DataTypes.DATE,
},
ends_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
stories.associate = (db) => {
db.stories.belongsToMany(db.story_items, {
as: 'story_items',
foreignKey: {
name: 'stories_story_itemsId',
},
constraints: false,
through: 'storiesStory_itemsStory_items',
});
db.stories.belongsToMany(db.story_items, {
as: 'story_items_filter',
foreignKey: {
name: 'stories_story_itemsId',
},
constraints: false,
through: 'storiesStory_itemsStory_items',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.stories.hasMany(db.story_items, {
as: 'story_items_story',
foreignKey: {
name: 'storyId',
},
constraints: false,
});
//end loop
db.stories.belongsTo(db.albums, {
as: 'album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.stories.belongsTo(db.users, {
as: 'created_by',
foreignKey: {
name: 'created_byId',
},
constraints: false,
});
db.stories.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.stories.belongsTo(db.users, {
as: 'createdBy',
});
db.stories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return stories;
};

View File

@ -0,0 +1,153 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const story_items = sequelize.define(
'story_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
sort_order: {
type: DataTypes.INTEGER,
},
layout: {
type: DataTypes.ENUM,
values: [
"full",
"split",
"grid"
],
},
overlay_text: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
story_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.story_items.belongsTo(db.stories, {
as: 'story',
foreignKey: {
name: 'storyId',
},
constraints: false,
});
db.story_items.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.story_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.story_items.belongsTo(db.users, {
as: 'createdBy',
});
db.story_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return story_items;
};

View File

@ -0,0 +1,146 @@
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 tags = sequelize.define(
'tags',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
tag_type: {
type: DataTypes.ENUM,
values: [
"ai",
"user",
"system"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tags.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.tags.hasMany(db.media_ai_tags, {
as: 'media_ai_tags_tag',
foreignKey: {
name: 'tagId',
},
constraints: false,
});
db.tags.hasMany(db.media_user_tags, {
as: 'media_user_tags_tag',
foreignKey: {
name: 'tagId',
},
constraints: false,
});
//end loop
db.tags.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.tags.belongsTo(db.users, {
as: 'createdBy',
});
db.tags.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tags;
};

View File

@ -0,0 +1,180 @@
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 upload_files = sequelize.define(
'upload_files',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
file_name: {
type: DataTypes.TEXT,
},
content_type: {
type: DataTypes.TEXT,
},
size_bytes: {
type: DataTypes.INTEGER,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"uploading",
"processing",
"done",
"failed"
],
},
progress_percent: {
type: DataTypes.INTEGER,
},
error_message: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
upload_files.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.upload_files.belongsTo(db.upload_sessions, {
as: 'upload_session',
foreignKey: {
name: 'upload_sessionId',
},
constraints: false,
});
db.upload_files.belongsTo(db.media_items, {
as: 'media_item',
foreignKey: {
name: 'media_itemId',
},
constraints: false,
});
db.upload_files.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.upload_files.belongsTo(db.users, {
as: 'createdBy',
});
db.upload_files.belongsTo(db.users, {
as: 'updatedBy',
});
};
return upload_files;
};

View File

@ -0,0 +1,209 @@
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 upload_sessions = sequelize.define(
'upload_sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"in_progress",
"paused",
"completed",
"failed",
"cancelled"
],
},
total_files: {
type: DataTypes.INTEGER,
},
completed_files: {
type: DataTypes.INTEGER,
},
failed_files: {
type: DataTypes.INTEGER,
},
started_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
upload_sessions.associate = (db) => {
db.upload_sessions.belongsToMany(db.upload_files, {
as: 'upload_files',
foreignKey: {
name: 'upload_sessions_upload_filesId',
},
constraints: false,
through: 'upload_sessionsUpload_filesUpload_files',
});
db.upload_sessions.belongsToMany(db.upload_files, {
as: 'upload_files_filter',
foreignKey: {
name: 'upload_sessions_upload_filesId',
},
constraints: false,
through: 'upload_sessionsUpload_filesUpload_files',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.upload_sessions.hasMany(db.upload_files, {
as: 'upload_files_upload_session',
foreignKey: {
name: 'upload_sessionId',
},
constraints: false,
});
//end loop
db.upload_sessions.belongsTo(db.albums, {
as: 'album',
foreignKey: {
name: 'albumId',
},
constraints: false,
});
db.upload_sessions.belongsTo(db.users, {
as: 'initiator',
foreignKey: {
name: 'initiatorId',
},
constraints: false,
});
db.upload_sessions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.upload_sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.upload_sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return upload_sessions;
};

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