Initial version

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

14
backend/.env Normal file
View File

@ -0,0 +1,14 @@
DB_NAME=app_38884
DB_USER=app_38884
DB_PASS=a36f1000-fa6e-44f7-b44b-32d6c08c8e24
DB_HOST=127.0.0.1
DB_PORT=5432
PORT=3000
GOOGLE_CLIENT_ID=671001533244-kf1k1gmp6mnl0r030qmvdu6v36ghmim6.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=Yo4qbKZniqvojzUQ60iKlxqR
MS_CLIENT_ID=4696f457-31af-40de-897c-e00d7d4cff73
MS_CLIENT_SECRET=m8jzZ.5UpHF3=-dXzyxiZ4e[F8OF54@p
EMAIL_USER=AKIAVEW7G4PQUBGM52OF
EMAIL_PASS=BLnD4hKGb6YkSz3gaQrf8fnyLi3C3/EdjOOsLEDTDPTz
SECRET_KEY=HUEyqESqgQ1yTwzVlO6wprC9Kf1J1xuA
PEXELS_KEY=Vc99rnmOhHhJAbgGQoKLZtsaIVfkeownoQNbTj78VemUjKh08ZYRbf18

4
backend/.eslintignore Normal file
View File

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

15
backend/.eslintrc.cjs Normal file
View File

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

11
backend/.prettierrc Normal file
View File

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

7
backend/.sequelizerc Normal file
View File

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

23
backend/Dockerfile Normal file
View File

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

56
backend/README.md Normal file
View File

@ -0,0 +1,56 @@
#MentorHub Demo - 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_mentorhub_demo;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_mentorhub_demo 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": "mentorhubdemo",
"description": "MentorHub Demo - 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});
});
}

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

@ -0,0 +1,79 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "a36f1000",
user_pass: "32d6c08c8e24",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'a36f1000-fa6e-44f7-b44b-32d6c08c8e24',
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: 'MentorHub Demo <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: {
admin: 'Administrator',
user: 'Learner',
},
project_uuid: 'a36f1000-fa6e-44f7-b44b-32d6c08c8e24',
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 = 'River delta sunrise over boats';
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,509 @@
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 Admin_audit_logsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const admin_audit_logs = await db.admin_audit_logs.create(
{
id: data.id || undefined,
action: data.action
||
null
,
target_entity: data.target_entity
||
null
,
target_id: data.target_id
||
null
,
details: data.details
||
null
,
occurred_at: data.occurred_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await admin_audit_logs.setAdmin_user( data.admin_user || null, {
transaction,
});
return admin_audit_logs;
}
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 admin_audit_logsData = data.map((item, index) => ({
id: item.id || undefined,
action: item.action
||
null
,
target_entity: item.target_entity
||
null
,
target_id: item.target_id
||
null
,
details: item.details
||
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 admin_audit_logs = await db.admin_audit_logs.bulkCreate(admin_audit_logsData, { transaction });
// For each item created, replace relation files
return admin_audit_logs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const admin_audit_logs = await db.admin_audit_logs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.action !== undefined) updatePayload.action = data.action;
if (data.target_entity !== undefined) updatePayload.target_entity = data.target_entity;
if (data.target_id !== undefined) updatePayload.target_id = data.target_id;
if (data.details !== undefined) updatePayload.details = data.details;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
updatePayload.updatedById = currentUser.id;
await admin_audit_logs.update(updatePayload, {transaction});
if (data.admin_user !== undefined) {
await admin_audit_logs.setAdmin_user(
data.admin_user,
{ transaction }
);
}
return admin_audit_logs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const admin_audit_logs = await db.admin_audit_logs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of admin_audit_logs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of admin_audit_logs) {
await record.destroy({transaction});
}
});
return admin_audit_logs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const admin_audit_logs = await db.admin_audit_logs.findByPk(id, options);
await admin_audit_logs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await admin_audit_logs.destroy({
transaction
});
return admin_audit_logs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const admin_audit_logs = await db.admin_audit_logs.findOne(
{ where },
{ transaction },
);
if (!admin_audit_logs) {
return admin_audit_logs;
}
const output = admin_audit_logs.get({plain: true});
output.admin_user = await admin_audit_logs.getAdmin_user({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'admin_user',
where: filter.admin_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.admin_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.admin_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.target_entity) {
where = {
...where,
[Op.and]: Utils.ilike(
'admin_audit_logs',
'target_entity',
filter.target_entity,
),
};
}
if (filter.target_id) {
where = {
...where,
[Op.and]: Utils.ilike(
'admin_audit_logs',
'target_id',
filter.target_id,
),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'admin_audit_logs',
'details',
filter.details,
),
};
}
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.action) {
where = {
...where,
action: filter.action,
};
}
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.admin_audit_logs.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(
'admin_audit_logs',
'action',
query,
),
],
};
}
const records = await db.admin_audit_logs.findAll({
attributes: [ 'id', 'action' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['action', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.action,
}));
}
};

View File

@ -0,0 +1,443 @@
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 BadgesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const badges = await db.badges.create(
{
id: data.id || undefined,
badge_key: data.badge_key
||
null
,
name_bn: data.name_bn
||
null
,
name_en: data.name_en
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return badges;
}
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 badgesData = data.map((item, index) => ({
id: item.id || undefined,
badge_key: item.badge_key
||
null
,
name_bn: item.name_bn
||
null
,
name_en: item.name_en
||
null
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const badges = await db.badges.bulkCreate(badgesData, { transaction });
// For each item created, replace relation files
return badges;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const badges = await db.badges.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.badge_key !== undefined) updatePayload.badge_key = data.badge_key;
if (data.name_bn !== undefined) updatePayload.name_bn = data.name_bn;
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await badges.update(updatePayload, {transaction});
return badges;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const badges = await db.badges.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of badges) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of badges) {
await record.destroy({transaction});
}
});
return badges;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const badges = await db.badges.findByPk(id, options);
await badges.update({
deletedBy: currentUser.id
}, {
transaction,
});
await badges.destroy({
transaction
});
return badges;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const badges = await db.badges.findOne(
{ where },
{ transaction },
);
if (!badges) {
return badges;
}
const output = badges.get({plain: true});
output.user_badges_badge = await badges.getUser_badges_badge({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.badge_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'badges',
'badge_key',
filter.badge_key,
),
};
}
if (filter.name_bn) {
where = {
...where,
[Op.and]: Utils.ilike(
'badges',
'name_bn',
filter.name_bn,
),
};
}
if (filter.name_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'badges',
'name_en',
filter.name_en,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'badges',
'description',
filter.description,
),
};
}
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.badges.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(
'badges',
'name_en',
query,
),
],
};
}
const records = await db.badges.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,563 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class CertificatesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const certificates = await db.certificates.create(
{
id: data.id || undefined,
subject_label: data.subject_label
||
null
,
level_label: data.level_label
||
null
,
issued_at: data.issued_at
||
null
,
certificate_html: data.certificate_html
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await certificates.setBooking( data.booking || null, {
transaction,
});
await certificates.setLearner( data.learner || null, {
transaction,
});
await certificates.setTutor( data.tutor || null, {
transaction,
});
return certificates;
}
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 certificatesData = data.map((item, index) => ({
id: item.id || undefined,
subject_label: item.subject_label
||
null
,
level_label: item.level_label
||
null
,
issued_at: item.issued_at
||
null
,
certificate_html: item.certificate_html
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const certificates = await db.certificates.bulkCreate(certificatesData, { transaction });
// For each item created, replace relation files
return certificates;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const certificates = await db.certificates.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.subject_label !== undefined) updatePayload.subject_label = data.subject_label;
if (data.level_label !== undefined) updatePayload.level_label = data.level_label;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.certificate_html !== undefined) updatePayload.certificate_html = data.certificate_html;
updatePayload.updatedById = currentUser.id;
await certificates.update(updatePayload, {transaction});
if (data.booking !== undefined) {
await certificates.setBooking(
data.booking,
{ transaction }
);
}
if (data.learner !== undefined) {
await certificates.setLearner(
data.learner,
{ transaction }
);
}
if (data.tutor !== undefined) {
await certificates.setTutor(
data.tutor,
{ transaction }
);
}
return certificates;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const certificates = await db.certificates.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of certificates) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of certificates) {
await record.destroy({transaction});
}
});
return certificates;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const certificates = await db.certificates.findByPk(id, options);
await certificates.update({
deletedBy: currentUser.id
}, {
transaction,
});
await certificates.destroy({
transaction
});
return certificates;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const certificates = await db.certificates.findOne(
{ where },
{ transaction },
);
if (!certificates) {
return certificates;
}
const output = certificates.get({plain: true});
output.booking = await certificates.getBooking({
transaction
});
output.learner = await certificates.getLearner({
transaction
});
output.tutor = await certificates.getTutor({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.bookings,
as: 'booking',
where: filter.booking ? {
[Op.or]: [
{ id: { [Op.in]: filter.booking.split('|').map(term => Utils.uuid(term)) } },
{
level_name: {
[Op.or]: filter.booking.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'learner',
where: filter.learner ? {
[Op.or]: [
{ id: { [Op.in]: filter.learner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.learner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'tutor',
where: filter.tutor ? {
[Op.or]: [
{ id: { [Op.in]: filter.tutor.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.tutor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.subject_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'certificates',
'subject_label',
filter.subject_label,
),
};
}
if (filter.level_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'certificates',
'level_label',
filter.level_label,
),
};
}
if (filter.certificate_html) {
where = {
...where,
[Op.and]: Utils.ilike(
'certificates',
'certificate_html',
filter.certificate_html,
),
};
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.certificates.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(
'certificates',
'subject_label',
query,
),
],
};
}
const records = await db.certificates.findAll({
attributes: [ 'id', 'subject_label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['subject_label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.subject_label,
}));
}
};

View File

@ -0,0 +1,550 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Challenge_participationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const challenge_participations = await db.challenge_participations.create(
{
id: data.id || undefined,
progress_value: data.progress_value
||
null
,
target_value: data.target_value
||
null
,
is_completed: data.is_completed
||
false
,
completed_at: data.completed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await challenge_participations.setChallenge( data.challenge || null, {
transaction,
});
await challenge_participations.setUser( data.user || null, {
transaction,
});
return challenge_participations;
}
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 challenge_participationsData = data.map((item, index) => ({
id: item.id || undefined,
progress_value: item.progress_value
||
null
,
target_value: item.target_value
||
null
,
is_completed: item.is_completed
||
false
,
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 challenge_participations = await db.challenge_participations.bulkCreate(challenge_participationsData, { transaction });
// For each item created, replace relation files
return challenge_participations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const challenge_participations = await db.challenge_participations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.progress_value !== undefined) updatePayload.progress_value = data.progress_value;
if (data.target_value !== undefined) updatePayload.target_value = data.target_value;
if (data.is_completed !== undefined) updatePayload.is_completed = data.is_completed;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
updatePayload.updatedById = currentUser.id;
await challenge_participations.update(updatePayload, {transaction});
if (data.challenge !== undefined) {
await challenge_participations.setChallenge(
data.challenge,
{ transaction }
);
}
if (data.user !== undefined) {
await challenge_participations.setUser(
data.user,
{ transaction }
);
}
return challenge_participations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const challenge_participations = await db.challenge_participations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of challenge_participations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of challenge_participations) {
await record.destroy({transaction});
}
});
return challenge_participations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const challenge_participations = await db.challenge_participations.findByPk(id, options);
await challenge_participations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await challenge_participations.destroy({
transaction
});
return challenge_participations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const challenge_participations = await db.challenge_participations.findOne(
{ where },
{ transaction },
);
if (!challenge_participations) {
return challenge_participations;
}
const output = challenge_participations.get({plain: true});
output.challenge = await challenge_participations.getChallenge({
transaction
});
output.user = await challenge_participations.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.weekly_challenges,
as: 'challenge',
where: filter.challenge ? {
[Op.or]: [
{ id: { [Op.in]: filter.challenge.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.challenge.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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.progress_valueRange) {
const [start, end] = filter.progress_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
progress_value: {
...where.progress_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
progress_value: {
...where.progress_value,
[Op.lte]: end,
},
};
}
}
if (filter.target_valueRange) {
const [start, end] = filter.target_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
target_value: {
...where.target_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
target_value: {
...where.target_value,
[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.is_completed) {
where = {
...where,
is_completed: filter.is_completed,
};
}
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.challenge_participations.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(
'challenge_participations',
'is_completed',
query,
),
],
};
}
const records = await db.challenge_participations.findAll({
attributes: [ 'id', 'is_completed' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['is_completed', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.is_completed,
}));
}
};

View File

@ -0,0 +1,576 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Community_commentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const community_comments = await db.community_comments.create(
{
id: data.id || undefined,
body: data.body
||
null
,
visibility: data.visibility
||
null
,
like_count: data.like_count
||
null
,
published_at: data.published_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await community_comments.setPost( data.post || null, {
transaction,
});
await community_comments.setAuthor( data.author || null, {
transaction,
});
await community_comments.setParent_comment( data.parent_comment || null, {
transaction,
});
return community_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 community_commentsData = data.map((item, index) => ({
id: item.id || undefined,
body: item.body
||
null
,
visibility: item.visibility
||
null
,
like_count: item.like_count
||
null
,
published_at: item.published_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const community_comments = await db.community_comments.bulkCreate(community_commentsData, { transaction });
// For each item created, replace relation files
return community_comments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const community_comments = await db.community_comments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.body !== undefined) updatePayload.body = data.body;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.like_count !== undefined) updatePayload.like_count = data.like_count;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
updatePayload.updatedById = currentUser.id;
await community_comments.update(updatePayload, {transaction});
if (data.post !== undefined) {
await community_comments.setPost(
data.post,
{ transaction }
);
}
if (data.author !== undefined) {
await community_comments.setAuthor(
data.author,
{ transaction }
);
}
if (data.parent_comment !== undefined) {
await community_comments.setParent_comment(
data.parent_comment,
{ transaction }
);
}
return community_comments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const community_comments = await db.community_comments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of community_comments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of community_comments) {
await record.destroy({transaction});
}
});
return community_comments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const community_comments = await db.community_comments.findByPk(id, options);
await community_comments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await community_comments.destroy({
transaction
});
return community_comments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const community_comments = await db.community_comments.findOne(
{ where },
{ transaction },
);
if (!community_comments) {
return community_comments;
}
const output = community_comments.get({plain: true});
output.community_reactions_comment = await community_comments.getCommunity_reactions_comment({
transaction
});
output.post = await community_comments.getPost({
transaction
});
output.author = await community_comments.getAuthor({
transaction
});
output.parent_comment = await community_comments.getParent_comment({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.community_posts,
as: 'post',
where: filter.post ? {
[Op.or]: [
{ id: { [Op.in]: filter.post.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.post.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.community_comments,
as: 'parent_comment',
where: filter.parent_comment ? {
[Op.or]: [
{ id: { [Op.in]: filter.parent_comment.split('|').map(term => Utils.uuid(term)) } },
{
body: {
[Op.or]: filter.parent_comment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'community_comments',
'body',
filter.body,
),
};
}
if (filter.like_countRange) {
const [start, end] = filter.like_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
like_count: {
...where.like_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
like_count: {
...where.like_count,
[Op.lte]: end,
},
};
}
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
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.community_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'community_comments',
'body',
query,
),
],
};
}
const records = await db.community_comments.findAll({
attributes: [ 'id', 'body' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['body', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.body,
}));
}
};

View File

@ -0,0 +1,792 @@
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 Community_postsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const community_posts = await db.community_posts.create(
{
id: data.id || undefined,
post_type: data.post_type
||
null
,
title: data.title
||
null
,
body: data.body
||
null
,
image_url: data.image_url
||
null
,
resource_url: data.resource_url
||
null
,
poll_options_json: data.poll_options_json
||
null
,
is_pinned: data.is_pinned
||
false
,
visibility: data.visibility
||
null
,
like_count: data.like_count
||
null
,
love_count: data.love_count
||
null
,
insightful_count: data.insightful_count
||
null
,
comment_count: data.comment_count
||
null
,
published_at: data.published_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await community_posts.setSpace( data.space || null, {
transaction,
});
await community_posts.setAuthor( data.author || null, {
transaction,
});
return community_posts;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const community_postsData = data.map((item, index) => ({
id: item.id || undefined,
post_type: item.post_type
||
null
,
title: item.title
||
null
,
body: item.body
||
null
,
image_url: item.image_url
||
null
,
resource_url: item.resource_url
||
null
,
poll_options_json: item.poll_options_json
||
null
,
is_pinned: item.is_pinned
||
false
,
visibility: item.visibility
||
null
,
like_count: item.like_count
||
null
,
love_count: item.love_count
||
null
,
insightful_count: item.insightful_count
||
null
,
comment_count: item.comment_count
||
null
,
published_at: item.published_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const community_posts = await db.community_posts.bulkCreate(community_postsData, { transaction });
// For each item created, replace relation files
return community_posts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const community_posts = await db.community_posts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.post_type !== undefined) updatePayload.post_type = data.post_type;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.image_url !== undefined) updatePayload.image_url = data.image_url;
if (data.resource_url !== undefined) updatePayload.resource_url = data.resource_url;
if (data.poll_options_json !== undefined) updatePayload.poll_options_json = data.poll_options_json;
if (data.is_pinned !== undefined) updatePayload.is_pinned = data.is_pinned;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.like_count !== undefined) updatePayload.like_count = data.like_count;
if (data.love_count !== undefined) updatePayload.love_count = data.love_count;
if (data.insightful_count !== undefined) updatePayload.insightful_count = data.insightful_count;
if (data.comment_count !== undefined) updatePayload.comment_count = data.comment_count;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
updatePayload.updatedById = currentUser.id;
await community_posts.update(updatePayload, {transaction});
if (data.space !== undefined) {
await community_posts.setSpace(
data.space,
{ transaction }
);
}
if (data.author !== undefined) {
await community_posts.setAuthor(
data.author,
{ transaction }
);
}
return community_posts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const community_posts = await db.community_posts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of community_posts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of community_posts) {
await record.destroy({transaction});
}
});
return community_posts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const community_posts = await db.community_posts.findByPk(id, options);
await community_posts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await community_posts.destroy({
transaction
});
return community_posts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const community_posts = await db.community_posts.findOne(
{ where },
{ transaction },
);
if (!community_posts) {
return community_posts;
}
const output = community_posts.get({plain: true});
output.community_comments_post = await community_posts.getCommunity_comments_post({
transaction
});
output.community_reactions_post = await community_posts.getCommunity_reactions_post({
transaction
});
output.space = await community_posts.getSpace({
transaction
});
output.author = await community_posts.getAuthor({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.spaces,
as: 'space',
where: filter.space ? {
[Op.or]: [
{ id: { [Op.in]: filter.space.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.space.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'author',
where: filter.author ? {
[Op.or]: [
{ id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'community_posts',
'title',
filter.title,
),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'community_posts',
'body',
filter.body,
),
};
}
if (filter.image_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'community_posts',
'image_url',
filter.image_url,
),
};
}
if (filter.resource_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'community_posts',
'resource_url',
filter.resource_url,
),
};
}
if (filter.poll_options_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'community_posts',
'poll_options_json',
filter.poll_options_json,
),
};
}
if (filter.like_countRange) {
const [start, end] = filter.like_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
like_count: {
...where.like_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
like_count: {
...where.like_count,
[Op.lte]: end,
},
};
}
}
if (filter.love_countRange) {
const [start, end] = filter.love_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
love_count: {
...where.love_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
love_count: {
...where.love_count,
[Op.lte]: end,
},
};
}
}
if (filter.insightful_countRange) {
const [start, end] = filter.insightful_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
insightful_count: {
...where.insightful_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
insightful_count: {
...where.insightful_count,
[Op.lte]: end,
},
};
}
}
if (filter.comment_countRange) {
const [start, end] = filter.comment_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
comment_count: {
...where.comment_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
comment_count: {
...where.comment_count,
[Op.lte]: end,
},
};
}
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.post_type) {
where = {
...where,
post_type: filter.post_type,
};
}
if (filter.is_pinned) {
where = {
...where,
is_pinned: filter.is_pinned,
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
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.community_posts.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'community_posts',
'title',
query,
),
],
};
}
const records = await db.community_posts.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,511 @@
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 Community_reactionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const community_reactions = await db.community_reactions.create(
{
id: data.id || undefined,
reaction_type: data.reaction_type
||
null
,
reacted_at: data.reacted_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await community_reactions.setUser( data.user || null, {
transaction,
});
await community_reactions.setPost( data.post || null, {
transaction,
});
await community_reactions.setComment( data.comment || null, {
transaction,
});
return community_reactions;
}
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 community_reactionsData = data.map((item, index) => ({
id: item.id || undefined,
reaction_type: item.reaction_type
||
null
,
reacted_at: item.reacted_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const community_reactions = await db.community_reactions.bulkCreate(community_reactionsData, { transaction });
// For each item created, replace relation files
return community_reactions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const community_reactions = await db.community_reactions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.reaction_type !== undefined) updatePayload.reaction_type = data.reaction_type;
if (data.reacted_at !== undefined) updatePayload.reacted_at = data.reacted_at;
updatePayload.updatedById = currentUser.id;
await community_reactions.update(updatePayload, {transaction});
if (data.user !== undefined) {
await community_reactions.setUser(
data.user,
{ transaction }
);
}
if (data.post !== undefined) {
await community_reactions.setPost(
data.post,
{ transaction }
);
}
if (data.comment !== undefined) {
await community_reactions.setComment(
data.comment,
{ transaction }
);
}
return community_reactions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const community_reactions = await db.community_reactions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of community_reactions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of community_reactions) {
await record.destroy({transaction});
}
});
return community_reactions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const community_reactions = await db.community_reactions.findByPk(id, options);
await community_reactions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await community_reactions.destroy({
transaction
});
return community_reactions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const community_reactions = await db.community_reactions.findOne(
{ where },
{ transaction },
);
if (!community_reactions) {
return community_reactions;
}
const output = community_reactions.get({plain: true});
output.user = await community_reactions.getUser({
transaction
});
output.post = await community_reactions.getPost({
transaction
});
output.comment = await community_reactions.getComment({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.community_posts,
as: 'post',
where: filter.post ? {
[Op.or]: [
{ id: { [Op.in]: filter.post.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.post.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.community_comments,
as: 'comment',
where: filter.comment ? {
[Op.or]: [
{ id: { [Op.in]: filter.comment.split('|').map(term => Utils.uuid(term)) } },
{
body: {
[Op.or]: filter.comment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reacted_atRange) {
const [start, end] = filter.reacted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reacted_at: {
...where.reacted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reacted_at: {
...where.reacted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.reaction_type) {
where = {
...where,
reaction_type: filter.reaction_type,
};
}
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.community_reactions.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(
'community_reactions',
'reaction_type',
query,
),
],
};
}
const records = await db.community_reactions.findAll({
attributes: [ 'id', 'reaction_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reaction_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reaction_type,
}));
}
};

View File

@ -0,0 +1,566 @@
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 Community_reportsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const community_reports = await db.community_reports.create(
{
id: data.id || undefined,
content_type: data.content_type
||
null
,
content_id: data.content_id
||
null
,
reason: data.reason
||
null
,
details: data.details
||
null
,
status: data.status
||
null
,
resolved_at: data.resolved_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await community_reports.setReporter( data.reporter || null, {
transaction,
});
await community_reports.setResolved_by( data.resolved_by || null, {
transaction,
});
return community_reports;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const community_reportsData = data.map((item, index) => ({
id: item.id || undefined,
content_type: item.content_type
||
null
,
content_id: item.content_id
||
null
,
reason: item.reason
||
null
,
details: item.details
||
null
,
status: item.status
||
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 community_reports = await db.community_reports.bulkCreate(community_reportsData, { transaction });
// For each item created, replace relation files
return community_reports;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const community_reports = await db.community_reports.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
if (data.content_id !== undefined) updatePayload.content_id = data.content_id;
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.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
updatePayload.updatedById = currentUser.id;
await community_reports.update(updatePayload, {transaction});
if (data.reporter !== undefined) {
await community_reports.setReporter(
data.reporter,
{ transaction }
);
}
if (data.resolved_by !== undefined) {
await community_reports.setResolved_by(
data.resolved_by,
{ transaction }
);
}
return community_reports;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const community_reports = await db.community_reports.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of community_reports) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of community_reports) {
await record.destroy({transaction});
}
});
return community_reports;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const community_reports = await db.community_reports.findByPk(id, options);
await community_reports.update({
deletedBy: currentUser.id
}, {
transaction,
});
await community_reports.destroy({
transaction
});
return community_reports;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const community_reports = await db.community_reports.findOne(
{ where },
{ transaction },
);
if (!community_reports) {
return community_reports;
}
const output = community_reports.get({plain: true});
output.reporter = await community_reports.getReporter({
transaction
});
output.resolved_by = await community_reports.getResolved_by({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'reporter',
where: filter.reporter ? {
[Op.or]: [
{ id: { [Op.in]: filter.reporter.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.reporter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'resolved_by',
where: filter.resolved_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.resolved_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.resolved_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.content_id) {
where = {
...where,
[Op.and]: Utils.ilike(
'community_reports',
'content_id',
filter.content_id,
),
};
}
if (filter.reason) {
where = {
...where,
[Op.and]: Utils.ilike(
'community_reports',
'reason',
filter.reason,
),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'community_reports',
'details',
filter.details,
),
};
}
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.content_type) {
where = {
...where,
content_type: filter.content_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
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.community_reports.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'community_reports',
'reason',
query,
),
],
};
}
const records = await db.community_reports.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,556 @@
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 ConversationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const conversations = await db.conversations.create(
{
id: data.id || undefined,
last_message: data.last_message
||
null
,
last_message_at: data.last_message_at
||
null
,
tutor_unread_count: data.tutor_unread_count
||
null
,
learner_unread_count: data.learner_unread_count
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await conversations.setTutor( data.tutor || null, {
transaction,
});
await conversations.setLearner( data.learner || null, {
transaction,
});
return conversations;
}
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 conversationsData = data.map((item, index) => ({
id: item.id || undefined,
last_message: item.last_message
||
null
,
last_message_at: item.last_message_at
||
null
,
tutor_unread_count: item.tutor_unread_count
||
null
,
learner_unread_count: item.learner_unread_count
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const conversations = await db.conversations.bulkCreate(conversationsData, { transaction });
// For each item created, replace relation files
return conversations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const conversations = await db.conversations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.last_message !== undefined) updatePayload.last_message = data.last_message;
if (data.last_message_at !== undefined) updatePayload.last_message_at = data.last_message_at;
if (data.tutor_unread_count !== undefined) updatePayload.tutor_unread_count = data.tutor_unread_count;
if (data.learner_unread_count !== undefined) updatePayload.learner_unread_count = data.learner_unread_count;
updatePayload.updatedById = currentUser.id;
await conversations.update(updatePayload, {transaction});
if (data.tutor !== undefined) {
await conversations.setTutor(
data.tutor,
{ transaction }
);
}
if (data.learner !== undefined) {
await conversations.setLearner(
data.learner,
{ transaction }
);
}
return conversations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const conversations = await db.conversations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of conversations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of conversations) {
await record.destroy({transaction});
}
});
return conversations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const conversations = await db.conversations.findByPk(id, options);
await conversations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await conversations.destroy({
transaction
});
return conversations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const conversations = await db.conversations.findOne(
{ where },
{ transaction },
);
if (!conversations) {
return conversations;
}
const output = conversations.get({plain: true});
output.messages_conversation = await conversations.getMessages_conversation({
transaction
});
output.tutor = await conversations.getTutor({
transaction
});
output.learner = await conversations.getLearner({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'tutor',
where: filter.tutor ? {
[Op.or]: [
{ id: { [Op.in]: filter.tutor.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.tutor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'learner',
where: filter.learner ? {
[Op.or]: [
{ id: { [Op.in]: filter.learner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.learner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.last_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'conversations',
'last_message',
filter.last_message,
),
};
}
if (filter.last_message_atRange) {
const [start, end] = filter.last_message_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_message_at: {
...where.last_message_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_message_at: {
...where.last_message_at,
[Op.lte]: end,
},
};
}
}
if (filter.tutor_unread_countRange) {
const [start, end] = filter.tutor_unread_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tutor_unread_count: {
...where.tutor_unread_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tutor_unread_count: {
...where.tutor_unread_count,
[Op.lte]: end,
},
};
}
}
if (filter.learner_unread_countRange) {
const [start, end] = filter.learner_unread_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
learner_unread_count: {
...where.learner_unread_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
learner_unread_count: {
...where.learner_unread_count,
[Op.lte]: end,
},
};
}
}
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.conversations.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(
'conversations',
'last_message',
query,
),
],
};
}
const records = await db.conversations.findAll({
attributes: [ 'id', 'last_message' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['last_message', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.last_message,
}));
}
};

View File

@ -0,0 +1,687 @@
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 DisputesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.create(
{
id: data.id || undefined,
reason: data.reason
||
null
,
description: data.description
||
null
,
status: data.status
||
null
,
resolution: data.resolution
||
null
,
admin_notes: data.admin_notes
||
null
,
resolved_at: data.resolved_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await disputes.setBooking( data.booking || null, {
transaction,
});
await disputes.setOpened_by( data.opened_by || null, {
transaction,
});
await disputes.setResolved_by( data.resolved_by || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'tutor_evidence',
belongsToId: disputes.id,
},
data.tutor_evidence,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'learner_evidence',
belongsToId: disputes.id,
},
data.learner_evidence,
options,
);
return disputes;
}
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 disputesData = data.map((item, index) => ({
id: item.id || undefined,
reason: item.reason
||
null
,
description: item.description
||
null
,
status: item.status
||
null
,
resolution: item.resolution
||
null
,
admin_notes: item.admin_notes
||
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 disputes = await db.disputes.bulkCreate(disputesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < disputes.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'tutor_evidence',
belongsToId: disputes[i].id,
},
data[i].tutor_evidence,
options,
);
}
for (let i = 0; i < disputes.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'learner_evidence',
belongsToId: disputes[i].id,
},
data[i].learner_evidence,
options,
);
}
return disputes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.reason !== undefined) updatePayload.reason = data.reason;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.resolution !== undefined) updatePayload.resolution = data.resolution;
if (data.admin_notes !== undefined) updatePayload.admin_notes = data.admin_notes;
if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
updatePayload.updatedById = currentUser.id;
await disputes.update(updatePayload, {transaction});
if (data.booking !== undefined) {
await disputes.setBooking(
data.booking,
{ transaction }
);
}
if (data.opened_by !== undefined) {
await disputes.setOpened_by(
data.opened_by,
{ transaction }
);
}
if (data.resolved_by !== undefined) {
await disputes.setResolved_by(
data.resolved_by,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'tutor_evidence',
belongsToId: disputes.id,
},
data.tutor_evidence,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'learner_evidence',
belongsToId: disputes.id,
},
data.learner_evidence,
options,
);
return disputes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of disputes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of disputes) {
await record.destroy({transaction});
}
});
return disputes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findByPk(id, options);
await disputes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await disputes.destroy({
transaction
});
return disputes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findOne(
{ where },
{ transaction },
);
if (!disputes) {
return disputes;
}
const output = disputes.get({plain: true});
output.booking = await disputes.getBooking({
transaction
});
output.opened_by = await disputes.getOpened_by({
transaction
});
output.tutor_evidence = await disputes.getTutor_evidence({
transaction
});
output.learner_evidence = await disputes.getLearner_evidence({
transaction
});
output.resolved_by = await disputes.getResolved_by({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.bookings,
as: 'booking',
where: filter.booking ? {
[Op.or]: [
{ id: { [Op.in]: filter.booking.split('|').map(term => Utils.uuid(term)) } },
{
level_name: {
[Op.or]: filter.booking.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'opened_by',
where: filter.opened_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.opened_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.opened_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'resolved_by',
where: filter.resolved_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.resolved_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.resolved_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'tutor_evidence',
},
{
model: db.file,
as: 'learner_evidence',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reason) {
where = {
...where,
[Op.and]: Utils.ilike(
'disputes',
'reason',
filter.reason,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'disputes',
'description',
filter.description,
),
};
}
if (filter.admin_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'disputes',
'admin_notes',
filter.admin_notes,
),
};
}
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.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.resolution) {
where = {
...where,
resolution: filter.resolution,
};
}
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.disputes.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(
'disputes',
'reason',
query,
),
],
};
}
const records = await db.disputes.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,474 @@
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 Event_rsvpsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const event_rsvps = await db.event_rsvps.create(
{
id: data.id || undefined,
status: data.status
||
null
,
rsvped_at: data.rsvped_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await event_rsvps.setEvent( data.event || null, {
transaction,
});
await event_rsvps.setUser( data.user || null, {
transaction,
});
return event_rsvps;
}
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 event_rsvpsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
rsvped_at: item.rsvped_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const event_rsvps = await db.event_rsvps.bulkCreate(event_rsvpsData, { transaction });
// For each item created, replace relation files
return event_rsvps;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const event_rsvps = await db.event_rsvps.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.rsvped_at !== undefined) updatePayload.rsvped_at = data.rsvped_at;
updatePayload.updatedById = currentUser.id;
await event_rsvps.update(updatePayload, {transaction});
if (data.event !== undefined) {
await event_rsvps.setEvent(
data.event,
{ transaction }
);
}
if (data.user !== undefined) {
await event_rsvps.setUser(
data.user,
{ transaction }
);
}
return event_rsvps;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const event_rsvps = await db.event_rsvps.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of event_rsvps) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of event_rsvps) {
await record.destroy({transaction});
}
});
return event_rsvps;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const event_rsvps = await db.event_rsvps.findByPk(id, options);
await event_rsvps.update({
deletedBy: currentUser.id
}, {
transaction,
});
await event_rsvps.destroy({
transaction
});
return event_rsvps;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const event_rsvps = await db.event_rsvps.findOne(
{ where },
{ transaction },
);
if (!event_rsvps) {
return event_rsvps;
}
const output = event_rsvps.get({plain: true});
output.event = await event_rsvps.getEvent({
transaction
});
output.user = await event_rsvps.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.live_events,
as: 'event',
where: filter.event ? {
[Op.or]: [
{ id: { [Op.in]: filter.event.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.event.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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.rsvped_atRange) {
const [start, end] = filter.rsvped_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rsvped_at: {
...where.rsvped_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rsvped_at: {
...where.rsvped_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.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.event_rsvps.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(
'event_rsvps',
'status',
query,
),
],
};
}
const records = await db.event_rsvps.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,87 @@
const db = require('../models');
const assert = require('assert');
const services = require('../../services/file');
module.exports = class FileDBApi {
static async replaceRelationFiles(
relation,
rawFiles,
options,
) {
assert(relation.belongsTo, 'belongsTo is required');
assert(
relation.belongsToColumn,
'belongsToColumn is required',
);
assert(relation.belongsToId, 'belongsToId is required');
let files = [];
if (Array.isArray(rawFiles)) {
files = rawFiles;
} else {
files = rawFiles ? [rawFiles] : [];
}
await this._removeLegacyFiles(relation, files, options);
await this._addFiles(relation, files, options);
}
static async _addFiles(relation, files, options) {
const transaction = (options && options.transaction) || undefined;
const currentUser = (options && options.currentUser) || {id: null};
const inexistentFiles = files.filter(
(file) => !!file.new,
);
for (const file of inexistentFiles) {
await db.file.create(
{
belongsTo: relation.belongsTo,
belongsToColumn: relation.belongsToColumn,
belongsToId: relation.belongsToId,
name: file.name,
sizeInBytes: file.sizeInBytes,
privateUrl: file.privateUrl,
publicUrl: file.publicUrl,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{
transaction,
},
);
}
}
static async _removeLegacyFiles(
relation,
files,
options,
) {
const transaction = (options && options.transaction) || undefined;
const filesToDelete = await db.file.findAll({
where: {
belongsTo: relation.belongsTo,
belongsToId: relation.belongsToId,
belongsToColumn: relation.belongsToColumn,
id: {
[db.Sequelize.Op
.notIn]: files
.filter((file) => !file.new)
.map((file) => file.id)
},
},
transaction,
});
for (let file of filesToDelete) {
await services.deleteGCloud(file.privateUrl);
await file.destroy({
transaction,
});
}
}
};

View File

@ -0,0 +1,567 @@
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 Gig_levelsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const gig_levels = await db.gig_levels.create(
{
id: data.id || undefined,
level_number: data.level_number
||
null
,
name: data.name
||
null
,
description: data.description
||
null
,
deliverables_json: data.deliverables_json
||
null
,
price: data.price
||
null
,
duration_minutes: data.duration_minutes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await gig_levels.setGig( data.gig || null, {
transaction,
});
return gig_levels;
}
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 gig_levelsData = data.map((item, index) => ({
id: item.id || undefined,
level_number: item.level_number
||
null
,
name: item.name
||
null
,
description: item.description
||
null
,
deliverables_json: item.deliverables_json
||
null
,
price: item.price
||
null
,
duration_minutes: item.duration_minutes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const gig_levels = await db.gig_levels.bulkCreate(gig_levelsData, { transaction });
// For each item created, replace relation files
return gig_levels;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const gig_levels = await db.gig_levels.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.level_number !== undefined) updatePayload.level_number = data.level_number;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.deliverables_json !== undefined) updatePayload.deliverables_json = data.deliverables_json;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.duration_minutes !== undefined) updatePayload.duration_minutes = data.duration_minutes;
updatePayload.updatedById = currentUser.id;
await gig_levels.update(updatePayload, {transaction});
if (data.gig !== undefined) {
await gig_levels.setGig(
data.gig,
{ transaction }
);
}
return gig_levels;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const gig_levels = await db.gig_levels.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of gig_levels) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of gig_levels) {
await record.destroy({transaction});
}
});
return gig_levels;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const gig_levels = await db.gig_levels.findByPk(id, options);
await gig_levels.update({
deletedBy: currentUser.id
}, {
transaction,
});
await gig_levels.destroy({
transaction
});
return gig_levels;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const gig_levels = await db.gig_levels.findOne(
{ where },
{ transaction },
);
if (!gig_levels) {
return gig_levels;
}
const output = gig_levels.get({plain: true});
output.bookings_gig_level = await gig_levels.getBookings_gig_level({
transaction
});
output.gig = await gig_levels.getGig({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.gigs,
as: 'gig',
where: filter.gig ? {
[Op.or]: [
{ id: { [Op.in]: filter.gig.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.gig.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'gig_levels',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'gig_levels',
'description',
filter.description,
),
};
}
if (filter.deliverables_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'gig_levels',
'deliverables_json',
filter.deliverables_json,
),
};
}
if (filter.level_numberRange) {
const [start, end] = filter.level_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
level_number: {
...where.level_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
level_number: {
...where.level_number,
[Op.lte]: end,
},
};
}
}
if (filter.priceRange) {
const [start, end] = filter.priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price: {
...where.price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price: {
...where.price,
[Op.lte]: end,
},
};
}
}
if (filter.duration_minutesRange) {
const [start, end] = filter.duration_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_minutes: {
...where.duration_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_minutes: {
...where.duration_minutes,
[Op.lte]: end,
},
};
}
}
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.gig_levels.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(
'gig_levels',
'name',
query,
),
],
};
}
const records = await db.gig_levels.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,
}));
}
};

650
backend/src/db/api/gigs.js Normal file
View File

@ -0,0 +1,650 @@
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 GigsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const gigs = await db.gigs.create(
{
id: data.id || undefined,
title: data.title
||
null
,
description: data.description
||
null
,
status: data.status
||
null
,
impressions: data.impressions
||
null
,
total_orders: data.total_orders
||
null
,
rating: data.rating
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await gigs.setTutor_profile( data.tutor_profile || null, {
transaction,
});
await gigs.setCategory( data.category || null, {
transaction,
});
await gigs.setTags(data.tags || [], {
transaction,
});
return gigs;
}
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 gigsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
description: item.description
||
null
,
status: item.status
||
null
,
impressions: item.impressions
||
null
,
total_orders: item.total_orders
||
null
,
rating: item.rating
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const gigs = await db.gigs.bulkCreate(gigsData, { transaction });
// For each item created, replace relation files
return gigs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const gigs = await db.gigs.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.impressions !== undefined) updatePayload.impressions = data.impressions;
if (data.total_orders !== undefined) updatePayload.total_orders = data.total_orders;
if (data.rating !== undefined) updatePayload.rating = data.rating;
updatePayload.updatedById = currentUser.id;
await gigs.update(updatePayload, {transaction});
if (data.tutor_profile !== undefined) {
await gigs.setTutor_profile(
data.tutor_profile,
{ transaction }
);
}
if (data.category !== undefined) {
await gigs.setCategory(
data.category,
{ transaction }
);
}
if (data.tags !== undefined) {
await gigs.setTags(data.tags, { transaction });
}
return gigs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const gigs = await db.gigs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of gigs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of gigs) {
await record.destroy({transaction});
}
});
return gigs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const gigs = await db.gigs.findByPk(id, options);
await gigs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await gigs.destroy({
transaction
});
return gigs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const gigs = await db.gigs.findOne(
{ where },
{ transaction },
);
if (!gigs) {
return gigs;
}
const output = gigs.get({plain: true});
output.gig_levels_gig = await gigs.getGig_levels_gig({
transaction
});
output.bookings_gig = await gigs.getBookings_gig({
transaction
});
output.invites_gig = await gigs.getInvites_gig({
transaction
});
output.tutor_profile = await gigs.getTutor_profile({
transaction
});
output.category = await gigs.getCategory({
transaction
});
output.tags = await gigs.getTags({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tutor_profiles,
as: 'tutor_profile',
where: filter.tutor_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.tutor_profile.split('|').map(term => Utils.uuid(term)) } },
{
headline: {
[Op.or]: filter.tutor_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.subject_categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
name_en: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.tags,
as: 'tags',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'gigs',
'title',
filter.title,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'gigs',
'description',
filter.description,
),
};
}
if (filter.impressionsRange) {
const [start, end] = filter.impressionsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
impressions: {
...where.impressions,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
impressions: {
...where.impressions,
[Op.lte]: end,
},
};
}
}
if (filter.total_ordersRange) {
const [start, end] = filter.total_ordersRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_orders: {
...where.total_orders,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_orders: {
...where.total_orders,
[Op.lte]: end,
},
};
}
}
if (filter.ratingRange) {
const [start, end] = filter.ratingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rating: {
...where.rating,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rating: {
...where.rating,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.tags) {
const searchTerms = filter.tags.split('|');
include = [
{
model: db.tags,
as: 'tags_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
label: {
[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,
},
};
}
}
}
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.gigs.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(
'gigs',
'title',
query,
),
],
};
}
const records = await db.gigs.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,572 @@
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 InvitesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invites = await db.invites.create(
{
id: data.id || undefined,
message: data.message
||
null
,
status: data.status
||
null
,
sent_at: data.sent_at
||
null
,
responded_at: data.responded_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await invites.setSender( data.sender || null, {
transaction,
});
await invites.setReceiver( data.receiver || null, {
transaction,
});
await invites.setGig( data.gig || null, {
transaction,
});
return invites;
}
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 invitesData = data.map((item, index) => ({
id: item.id || undefined,
message: item.message
||
null
,
status: item.status
||
null
,
sent_at: item.sent_at
||
null
,
responded_at: item.responded_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const invites = await db.invites.bulkCreate(invitesData, { transaction });
// For each item created, replace relation files
return invites;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const invites = await db.invites.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.message !== undefined) updatePayload.message = data.message;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.responded_at !== undefined) updatePayload.responded_at = data.responded_at;
updatePayload.updatedById = currentUser.id;
await invites.update(updatePayload, {transaction});
if (data.sender !== undefined) {
await invites.setSender(
data.sender,
{ transaction }
);
}
if (data.receiver !== undefined) {
await invites.setReceiver(
data.receiver,
{ transaction }
);
}
if (data.gig !== undefined) {
await invites.setGig(
data.gig,
{ transaction }
);
}
return invites;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invites = await db.invites.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of invites) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of invites) {
await record.destroy({transaction});
}
});
return invites;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const invites = await db.invites.findByPk(id, options);
await invites.update({
deletedBy: currentUser.id
}, {
transaction,
});
await invites.destroy({
transaction
});
return invites;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const invites = await db.invites.findOne(
{ where },
{ transaction },
);
if (!invites) {
return invites;
}
const output = invites.get({plain: true});
output.sender = await invites.getSender({
transaction
});
output.receiver = await invites.getReceiver({
transaction
});
output.gig = await invites.getGig({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'sender',
where: filter.sender ? {
[Op.or]: [
{ id: { [Op.in]: filter.sender.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.sender.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'receiver',
where: filter.receiver ? {
[Op.or]: [
{ id: { [Op.in]: filter.receiver.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.receiver.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.gigs,
as: 'gig',
where: filter.gig ? {
[Op.or]: [
{ id: { [Op.in]: filter.gig.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.gig.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'invites',
'message',
filter.message,
),
};
}
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.responded_atRange) {
const [start, end] = filter.responded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
responded_at: {
...where.responded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
responded_at: {
...where.responded_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.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.invites.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(
'invites',
'message',
query,
),
],
};
}
const records = await db.invites.findAll({
attributes: [ 'id', 'message' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['message', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.message,
}));
}
};

View File

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

View File

@ -0,0 +1,484 @@
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 Learner_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const learner_profiles = await db.learner_profiles.create(
{
id: data.id || undefined,
main_goal: data.main_goal
||
null
,
preferred_session_format: data.preferred_session_format
||
null
,
session_language_preference: data.session_language_preference
||
null
,
budget_range: data.budget_range
||
null
,
availability_json: data.availability_json
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await learner_profiles.setUser( data.user || null, {
transaction,
});
return learner_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 learner_profilesData = data.map((item, index) => ({
id: item.id || undefined,
main_goal: item.main_goal
||
null
,
preferred_session_format: item.preferred_session_format
||
null
,
session_language_preference: item.session_language_preference
||
null
,
budget_range: item.budget_range
||
null
,
availability_json: item.availability_json
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const learner_profiles = await db.learner_profiles.bulkCreate(learner_profilesData, { transaction });
// For each item created, replace relation files
return learner_profiles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const learner_profiles = await db.learner_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.main_goal !== undefined) updatePayload.main_goal = data.main_goal;
if (data.preferred_session_format !== undefined) updatePayload.preferred_session_format = data.preferred_session_format;
if (data.session_language_preference !== undefined) updatePayload.session_language_preference = data.session_language_preference;
if (data.budget_range !== undefined) updatePayload.budget_range = data.budget_range;
if (data.availability_json !== undefined) updatePayload.availability_json = data.availability_json;
updatePayload.updatedById = currentUser.id;
await learner_profiles.update(updatePayload, {transaction});
if (data.user !== undefined) {
await learner_profiles.setUser(
data.user,
{ transaction }
);
}
return learner_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const learner_profiles = await db.learner_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of learner_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of learner_profiles) {
await record.destroy({transaction});
}
});
return learner_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const learner_profiles = await db.learner_profiles.findByPk(id, options);
await learner_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await learner_profiles.destroy({
transaction
});
return learner_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const learner_profiles = await db.learner_profiles.findOne(
{ where },
{ transaction },
);
if (!learner_profiles) {
return learner_profiles;
}
const output = learner_profiles.get({plain: true});
output.user = await learner_profiles.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.availability_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'learner_profiles',
'availability_json',
filter.availability_json,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.main_goal) {
where = {
...where,
main_goal: filter.main_goal,
};
}
if (filter.preferred_session_format) {
where = {
...where,
preferred_session_format: filter.preferred_session_format,
};
}
if (filter.session_language_preference) {
where = {
...where,
session_language_preference: filter.session_language_preference,
};
}
if (filter.budget_range) {
where = {
...where,
budget_range: filter.budget_range,
};
}
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.learner_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'learner_profiles',
'main_goal',
query,
),
],
};
}
const records = await db.learner_profiles.findAll({
attributes: [ 'id', 'main_goal' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['main_goal', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.main_goal,
}));
}
};

View File

@ -0,0 +1,765 @@
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 Live_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const live_events = await db.live_events.create(
{
id: data.id || undefined,
title: data.title
||
null
,
description: data.description
||
null
,
event_type: data.event_type
||
null
,
meeting_provider: data.meeting_provider
||
null
,
meeting_link: data.meeting_link
||
null
,
recording_link: data.recording_link
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
capacity: data.capacity
||
null
,
price_amount: data.price_amount
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await live_events.setHost( data.host || null, {
transaction,
});
await live_events.setSpace( data.space || null, {
transaction,
});
await live_events.setTags(data.tags || [], {
transaction,
});
return live_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 live_eventsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
description: item.description
||
null
,
event_type: item.event_type
||
null
,
meeting_provider: item.meeting_provider
||
null
,
meeting_link: item.meeting_link
||
null
,
recording_link: item.recording_link
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
capacity: item.capacity
||
null
,
price_amount: item.price_amount
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const live_events = await db.live_events.bulkCreate(live_eventsData, { transaction });
// For each item created, replace relation files
return live_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const live_events = await db.live_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
if (data.meeting_provider !== undefined) updatePayload.meeting_provider = data.meeting_provider;
if (data.meeting_link !== undefined) updatePayload.meeting_link = data.meeting_link;
if (data.recording_link !== undefined) updatePayload.recording_link = data.recording_link;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.capacity !== undefined) updatePayload.capacity = data.capacity;
if (data.price_amount !== undefined) updatePayload.price_amount = data.price_amount;
updatePayload.updatedById = currentUser.id;
await live_events.update(updatePayload, {transaction});
if (data.host !== undefined) {
await live_events.setHost(
data.host,
{ transaction }
);
}
if (data.space !== undefined) {
await live_events.setSpace(
data.space,
{ transaction }
);
}
if (data.tags !== undefined) {
await live_events.setTags(data.tags, { transaction });
}
return live_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const live_events = await db.live_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of live_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of live_events) {
await record.destroy({transaction});
}
});
return live_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const live_events = await db.live_events.findByPk(id, options);
await live_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await live_events.destroy({
transaction
});
return live_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const live_events = await db.live_events.findOne(
{ where },
{ transaction },
);
if (!live_events) {
return live_events;
}
const output = live_events.get({plain: true});
output.event_rsvps_event = await live_events.getEvent_rsvps_event({
transaction
});
output.host = await live_events.getHost({
transaction
});
output.space = await live_events.getSpace({
transaction
});
output.tags = await live_events.getTags({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'host',
where: filter.host ? {
[Op.or]: [
{ id: { [Op.in]: filter.host.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.host.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.spaces,
as: 'space',
where: filter.space ? {
[Op.or]: [
{ id: { [Op.in]: filter.space.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.space.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.tags,
as: 'tags',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'live_events',
'title',
filter.title,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'live_events',
'description',
filter.description,
),
};
}
if (filter.meeting_link) {
where = {
...where,
[Op.and]: Utils.ilike(
'live_events',
'meeting_link',
filter.meeting_link,
),
};
}
if (filter.recording_link) {
where = {
...where,
[Op.and]: Utils.ilike(
'live_events',
'recording_link',
filter.recording_link,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_atRange) {
const [start, end] = filter.start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.lte]: end,
},
};
}
}
if (filter.end_atRange) {
const [start, end] = filter.end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.lte]: end,
},
};
}
}
if (filter.capacityRange) {
const [start, end] = filter.capacityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
capacity: {
...where.capacity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
capacity: {
...where.capacity,
[Op.lte]: end,
},
};
}
}
if (filter.price_amountRange) {
const [start, end] = filter.price_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_amount: {
...where.price_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_amount: {
...where.price_amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.event_type) {
where = {
...where,
event_type: filter.event_type,
};
}
if (filter.meeting_provider) {
where = {
...where,
meeting_provider: filter.meeting_provider,
};
}
if (filter.tags) {
const searchTerms = filter.tags.split('|');
include = [
{
model: db.tags,
as: 'tags_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
label: {
[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,
},
};
}
}
}
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.live_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'live_events',
'title',
query,
),
],
};
}
const records = await db.live_events.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,627 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class MessagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.create(
{
id: data.id || undefined,
type: data.type
||
null
,
content: data.content
||
null
,
file_url: data.file_url
||
null
,
file_name: data.file_name
||
null
,
is_pii_masked: data.is_pii_masked
||
false
,
is_read: data.is_read
||
false
,
sent_at: data.sent_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await messages.setConversation( data.conversation || null, {
transaction,
});
await messages.setSender( data.sender || null, {
transaction,
});
await messages.setReceiver( data.receiver || null, {
transaction,
});
return messages;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const messagesData = data.map((item, index) => ({
id: item.id || undefined,
type: item.type
||
null
,
content: item.content
||
null
,
file_url: item.file_url
||
null
,
file_name: item.file_name
||
null
,
is_pii_masked: item.is_pii_masked
||
false
,
is_read: item.is_read
||
false
,
sent_at: item.sent_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const messages = await db.messages.bulkCreate(messagesData, { transaction });
// For each item created, replace relation files
return messages;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.type !== undefined) updatePayload.type = data.type;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.file_url !== undefined) updatePayload.file_url = data.file_url;
if (data.file_name !== undefined) updatePayload.file_name = data.file_name;
if (data.is_pii_masked !== undefined) updatePayload.is_pii_masked = data.is_pii_masked;
if (data.is_read !== undefined) updatePayload.is_read = data.is_read;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
updatePayload.updatedById = currentUser.id;
await messages.update(updatePayload, {transaction});
if (data.conversation !== undefined) {
await messages.setConversation(
data.conversation,
{ transaction }
);
}
if (data.sender !== undefined) {
await messages.setSender(
data.sender,
{ transaction }
);
}
if (data.receiver !== undefined) {
await messages.setReceiver(
data.receiver,
{ transaction }
);
}
return messages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of messages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of messages) {
await record.destroy({transaction});
}
});
return messages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findByPk(id, options);
await messages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await messages.destroy({
transaction
});
return messages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findOne(
{ where },
{ transaction },
);
if (!messages) {
return messages;
}
const output = messages.get({plain: true});
output.conversation = await messages.getConversation({
transaction
});
output.sender = await messages.getSender({
transaction
});
output.receiver = await messages.getReceiver({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.conversations,
as: 'conversation',
where: filter.conversation ? {
[Op.or]: [
{ id: { [Op.in]: filter.conversation.split('|').map(term => Utils.uuid(term)) } },
{
last_message: {
[Op.or]: filter.conversation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'sender',
where: filter.sender ? {
[Op.or]: [
{ id: { [Op.in]: filter.sender.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.sender.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'receiver',
where: filter.receiver ? {
[Op.or]: [
{ id: { [Op.in]: filter.receiver.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.receiver.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'messages',
'content',
filter.content,
),
};
}
if (filter.file_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'messages',
'file_url',
filter.file_url,
),
};
}
if (filter.file_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'messages',
'file_name',
filter.file_name,
),
};
}
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_pii_masked) {
where = {
...where,
is_pii_masked: filter.is_pii_masked,
};
}
if (filter.is_read) {
where = {
...where,
is_read: filter.is_read,
};
}
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.messages.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'messages',
'content',
query,
),
],
};
}
const records = await db.messages.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,
}));
}
};

476
backend/src/db/api/notes.js Normal file
View File

@ -0,0 +1,476 @@
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 NotesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notes = await db.notes.create(
{
id: data.id || undefined,
tutor_private_notes: data.tutor_private_notes
||
null
,
learner_private_notes: data.learner_private_notes
||
null
,
shared_notes: data.shared_notes
||
null
,
session_summary: data.session_summary
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notes.setBooking( data.booking || null, {
transaction,
});
return notes;
}
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 notesData = data.map((item, index) => ({
id: item.id || undefined,
tutor_private_notes: item.tutor_private_notes
||
null
,
learner_private_notes: item.learner_private_notes
||
null
,
shared_notes: item.shared_notes
||
null
,
session_summary: item.session_summary
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const notes = await db.notes.bulkCreate(notesData, { transaction });
// For each item created, replace relation files
return notes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notes = await db.notes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.tutor_private_notes !== undefined) updatePayload.tutor_private_notes = data.tutor_private_notes;
if (data.learner_private_notes !== undefined) updatePayload.learner_private_notes = data.learner_private_notes;
if (data.shared_notes !== undefined) updatePayload.shared_notes = data.shared_notes;
if (data.session_summary !== undefined) updatePayload.session_summary = data.session_summary;
updatePayload.updatedById = currentUser.id;
await notes.update(updatePayload, {transaction});
if (data.booking !== undefined) {
await notes.setBooking(
data.booking,
{ transaction }
);
}
return notes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notes = await db.notes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notes) {
await record.destroy({transaction});
}
});
return notes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notes = await db.notes.findByPk(id, options);
await notes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notes.destroy({
transaction
});
return notes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notes = await db.notes.findOne(
{ where },
{ transaction },
);
if (!notes) {
return notes;
}
const output = notes.get({plain: true});
output.booking = await notes.getBooking({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.bookings,
as: 'booking',
where: filter.booking ? {
[Op.or]: [
{ id: { [Op.in]: filter.booking.split('|').map(term => Utils.uuid(term)) } },
{
level_name: {
[Op.or]: filter.booking.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.tutor_private_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'notes',
'tutor_private_notes',
filter.tutor_private_notes,
),
};
}
if (filter.learner_private_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'notes',
'learner_private_notes',
filter.learner_private_notes,
),
};
}
if (filter.shared_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'notes',
'shared_notes',
filter.shared_notes,
),
};
}
if (filter.session_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'notes',
'session_summary',
filter.session_summary,
),
};
}
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.notes.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(
'notes',
'session_summary',
query,
),
],
};
}
const records = await db.notes.findAll({
attributes: [ 'id', 'session_summary' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['session_summary', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.session_summary,
}));
}
};

View File

@ -0,0 +1,494 @@
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
,
link: data.link
||
null
,
is_read: data.is_read
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notifications.setUser( data.user || 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
,
link: item.link
||
null
,
is_read: item.is_read
||
false
,
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 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.link !== undefined) updatePayload.link = data.link;
if (data.is_read !== undefined) updatePayload.is_read = data.is_read;
updatePayload.updatedById = currentUser.id;
await notifications.update(updatePayload, {transaction});
if (data.user !== undefined) {
await notifications.setUser(
data.user,
{ transaction }
);
}
return notifications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notifications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notifications) {
await record.destroy({transaction});
}
});
return notifications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findByPk(id, options);
await notifications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notifications.destroy({
transaction
});
return notifications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findOne(
{ where },
{ transaction },
);
if (!notifications) {
return notifications;
}
const output = notifications.get({plain: true});
output.user = await notifications.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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}%` }))
}
},
]
} : {},
},
];
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.link) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'link',
filter.link,
),
};
}
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.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.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, ) {
let where = {};
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,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 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;
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,675 @@
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 Platform_configDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const platform_config = await db.platform_config.create(
{
id: data.id || undefined,
platform_fee_percent: data.platform_fee_percent
||
null
,
auto_release_days: data.auto_release_days
||
null
,
max_revision_count: data.max_revision_count
||
null
,
min_review_length: data.min_review_length
||
null
,
new_user_verify_email: data.new_user_verify_email
||
false
,
tutor_two_factor_required: data.tutor_two_factor_required
||
false
,
maintenance_mode: data.maintenance_mode
||
false
,
maintenance_message: data.maintenance_message
||
null
,
announcement_banner_enabled: data.announcement_banner_enabled
||
false
,
announcement_banner_text: data.announcement_banner_text
||
null
,
jitsi_sdk_key: data.jitsi_sdk_key
||
null
,
jitsi_sdk_secret: data.jitsi_sdk_secret
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return platform_config;
}
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 platform_configData = data.map((item, index) => ({
id: item.id || undefined,
platform_fee_percent: item.platform_fee_percent
||
null
,
auto_release_days: item.auto_release_days
||
null
,
max_revision_count: item.max_revision_count
||
null
,
min_review_length: item.min_review_length
||
null
,
new_user_verify_email: item.new_user_verify_email
||
false
,
tutor_two_factor_required: item.tutor_two_factor_required
||
false
,
maintenance_mode: item.maintenance_mode
||
false
,
maintenance_message: item.maintenance_message
||
null
,
announcement_banner_enabled: item.announcement_banner_enabled
||
false
,
announcement_banner_text: item.announcement_banner_text
||
null
,
jitsi_sdk_key: item.jitsi_sdk_key
||
null
,
jitsi_sdk_secret: item.jitsi_sdk_secret
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const platform_config = await db.platform_config.bulkCreate(platform_configData, { transaction });
// For each item created, replace relation files
return platform_config;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const platform_config = await db.platform_config.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.platform_fee_percent !== undefined) updatePayload.platform_fee_percent = data.platform_fee_percent;
if (data.auto_release_days !== undefined) updatePayload.auto_release_days = data.auto_release_days;
if (data.max_revision_count !== undefined) updatePayload.max_revision_count = data.max_revision_count;
if (data.min_review_length !== undefined) updatePayload.min_review_length = data.min_review_length;
if (data.new_user_verify_email !== undefined) updatePayload.new_user_verify_email = data.new_user_verify_email;
if (data.tutor_two_factor_required !== undefined) updatePayload.tutor_two_factor_required = data.tutor_two_factor_required;
if (data.maintenance_mode !== undefined) updatePayload.maintenance_mode = data.maintenance_mode;
if (data.maintenance_message !== undefined) updatePayload.maintenance_message = data.maintenance_message;
if (data.announcement_banner_enabled !== undefined) updatePayload.announcement_banner_enabled = data.announcement_banner_enabled;
if (data.announcement_banner_text !== undefined) updatePayload.announcement_banner_text = data.announcement_banner_text;
if (data.jitsi_sdk_key !== undefined) updatePayload.jitsi_sdk_key = data.jitsi_sdk_key;
if (data.jitsi_sdk_secret !== undefined) updatePayload.jitsi_sdk_secret = data.jitsi_sdk_secret;
updatePayload.updatedById = currentUser.id;
await platform_config.update(updatePayload, {transaction});
return platform_config;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const platform_config = await db.platform_config.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of platform_config) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of platform_config) {
await record.destroy({transaction});
}
});
return platform_config;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const platform_config = await db.platform_config.findByPk(id, options);
await platform_config.update({
deletedBy: currentUser.id
}, {
transaction,
});
await platform_config.destroy({
transaction
});
return platform_config;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const platform_config = await db.platform_config.findOne(
{ where },
{ transaction },
);
if (!platform_config) {
return platform_config;
}
const output = platform_config.get({plain: true});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.maintenance_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'platform_config',
'maintenance_message',
filter.maintenance_message,
),
};
}
if (filter.announcement_banner_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'platform_config',
'announcement_banner_text',
filter.announcement_banner_text,
),
};
}
if (filter.jitsi_sdk_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'platform_config',
'jitsi_sdk_key',
filter.jitsi_sdk_key,
),
};
}
if (filter.jitsi_sdk_secret) {
where = {
...where,
[Op.and]: Utils.ilike(
'platform_config',
'jitsi_sdk_secret',
filter.jitsi_sdk_secret,
),
};
}
if (filter.platform_fee_percentRange) {
const [start, end] = filter.platform_fee_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
platform_fee_percent: {
...where.platform_fee_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
platform_fee_percent: {
...where.platform_fee_percent,
[Op.lte]: end,
},
};
}
}
if (filter.auto_release_daysRange) {
const [start, end] = filter.auto_release_daysRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
auto_release_days: {
...where.auto_release_days,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
auto_release_days: {
...where.auto_release_days,
[Op.lte]: end,
},
};
}
}
if (filter.max_revision_countRange) {
const [start, end] = filter.max_revision_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_revision_count: {
...where.max_revision_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_revision_count: {
...where.max_revision_count,
[Op.lte]: end,
},
};
}
}
if (filter.min_review_lengthRange) {
const [start, end] = filter.min_review_lengthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_review_length: {
...where.min_review_length,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_review_length: {
...where.min_review_length,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.new_user_verify_email) {
where = {
...where,
new_user_verify_email: filter.new_user_verify_email,
};
}
if (filter.tutor_two_factor_required) {
where = {
...where,
tutor_two_factor_required: filter.tutor_two_factor_required,
};
}
if (filter.maintenance_mode) {
where = {
...where,
maintenance_mode: filter.maintenance_mode,
};
}
if (filter.announcement_banner_enabled) {
where = {
...where,
announcement_banner_enabled: filter.announcement_banner_enabled,
};
}
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.platform_config.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(
'platform_config',
'announcement_banner_text',
query,
),
],
};
}
const records = await db.platform_config.findAll({
attributes: [ 'id', 'announcement_banner_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['announcement_banner_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.announcement_banner_text,
}));
}
};

View File

@ -0,0 +1,803 @@
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 ReviewsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reviews = await db.reviews.create(
{
id: data.id || undefined,
rating: data.rating
||
null
,
communication_rating: data.communication_rating
||
null
,
knowledge_rating: data.knowledge_rating
||
null
,
punctuality_rating: data.punctuality_rating
||
null
,
value_rating: data.value_rating
||
null
,
review_text: data.review_text
||
null
,
would_recommend: data.would_recommend
||
false
,
tutor_response: data.tutor_response
||
null
,
tutor_response_at: data.tutor_response_at
||
null
,
status: data.status
||
null
,
published_at: data.published_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await reviews.setBooking( data.booking || null, {
transaction,
});
await reviews.setTutor( data.tutor || null, {
transaction,
});
await reviews.setLearner( data.learner || null, {
transaction,
});
return reviews;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const reviewsData = data.map((item, index) => ({
id: item.id || undefined,
rating: item.rating
||
null
,
communication_rating: item.communication_rating
||
null
,
knowledge_rating: item.knowledge_rating
||
null
,
punctuality_rating: item.punctuality_rating
||
null
,
value_rating: item.value_rating
||
null
,
review_text: item.review_text
||
null
,
would_recommend: item.would_recommend
||
false
,
tutor_response: item.tutor_response
||
null
,
tutor_response_at: item.tutor_response_at
||
null
,
status: item.status
||
null
,
published_at: item.published_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const reviews = await db.reviews.bulkCreate(reviewsData, { transaction });
// For each item created, replace relation files
return reviews;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reviews = await db.reviews.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.rating !== undefined) updatePayload.rating = data.rating;
if (data.communication_rating !== undefined) updatePayload.communication_rating = data.communication_rating;
if (data.knowledge_rating !== undefined) updatePayload.knowledge_rating = data.knowledge_rating;
if (data.punctuality_rating !== undefined) updatePayload.punctuality_rating = data.punctuality_rating;
if (data.value_rating !== undefined) updatePayload.value_rating = data.value_rating;
if (data.review_text !== undefined) updatePayload.review_text = data.review_text;
if (data.would_recommend !== undefined) updatePayload.would_recommend = data.would_recommend;
if (data.tutor_response !== undefined) updatePayload.tutor_response = data.tutor_response;
if (data.tutor_response_at !== undefined) updatePayload.tutor_response_at = data.tutor_response_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
updatePayload.updatedById = currentUser.id;
await reviews.update(updatePayload, {transaction});
if (data.booking !== undefined) {
await reviews.setBooking(
data.booking,
{ transaction }
);
}
if (data.tutor !== undefined) {
await reviews.setTutor(
data.tutor,
{ transaction }
);
}
if (data.learner !== undefined) {
await reviews.setLearner(
data.learner,
{ transaction }
);
}
return reviews;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reviews = await db.reviews.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of reviews) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of reviews) {
await record.destroy({transaction});
}
});
return reviews;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reviews = await db.reviews.findByPk(id, options);
await reviews.update({
deletedBy: currentUser.id
}, {
transaction,
});
await reviews.destroy({
transaction
});
return reviews;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const reviews = await db.reviews.findOne(
{ where },
{ transaction },
);
if (!reviews) {
return reviews;
}
const output = reviews.get({plain: true});
output.booking = await reviews.getBooking({
transaction
});
output.tutor = await reviews.getTutor({
transaction
});
output.learner = await reviews.getLearner({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.bookings,
as: 'booking',
where: filter.booking ? {
[Op.or]: [
{ id: { [Op.in]: filter.booking.split('|').map(term => Utils.uuid(term)) } },
{
level_name: {
[Op.or]: filter.booking.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'tutor',
where: filter.tutor ? {
[Op.or]: [
{ id: { [Op.in]: filter.tutor.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.tutor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'learner',
where: filter.learner ? {
[Op.or]: [
{ id: { [Op.in]: filter.learner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.learner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.review_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'reviews',
'review_text',
filter.review_text,
),
};
}
if (filter.tutor_response) {
where = {
...where,
[Op.and]: Utils.ilike(
'reviews',
'tutor_response',
filter.tutor_response,
),
};
}
if (filter.ratingRange) {
const [start, end] = filter.ratingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rating: {
...where.rating,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rating: {
...where.rating,
[Op.lte]: end,
},
};
}
}
if (filter.communication_ratingRange) {
const [start, end] = filter.communication_ratingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
communication_rating: {
...where.communication_rating,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
communication_rating: {
...where.communication_rating,
[Op.lte]: end,
},
};
}
}
if (filter.knowledge_ratingRange) {
const [start, end] = filter.knowledge_ratingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
knowledge_rating: {
...where.knowledge_rating,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
knowledge_rating: {
...where.knowledge_rating,
[Op.lte]: end,
},
};
}
}
if (filter.punctuality_ratingRange) {
const [start, end] = filter.punctuality_ratingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
punctuality_rating: {
...where.punctuality_rating,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
punctuality_rating: {
...where.punctuality_rating,
[Op.lte]: end,
},
};
}
}
if (filter.value_ratingRange) {
const [start, end] = filter.value_ratingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
value_rating: {
...where.value_rating,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
value_rating: {
...where.value_rating,
[Op.lte]: end,
},
};
}
}
if (filter.tutor_response_atRange) {
const [start, end] = filter.tutor_response_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tutor_response_at: {
...where.tutor_response_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tutor_response_at: {
...where.tutor_response_at,
[Op.lte]: end,
},
};
}
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.would_recommend) {
where = {
...where,
would_recommend: filter.would_recommend,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
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.reviews.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'reviews',
'review_text',
query,
),
],
};
}
const records = await db.reviews.findAll({
attributes: [ 'id', 'review_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['review_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.review_text,
}));
}
};

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

@ -0,0 +1,437 @@
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 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
,
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
,
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 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;
updatePayload.updatedById = currentUser.id;
await roles.update(updatePayload, {transaction});
if (data.permissions !== undefined) {
await roles.setPermissions(data.permissions, { transaction });
}
return roles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of roles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of roles) {
await record.destroy({transaction});
}
});
return roles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findByPk(id, options);
await roles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await roles.destroy({
transaction
});
return roles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findOne(
{ where },
{ transaction },
);
if (!roles) {
return roles;
}
const output = roles.get({plain: true});
output.users_app_role = await roles.getUsers_app_role({
transaction
});
output.permissions = await roles.getPermissions({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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,
},
};
}
}
}
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, ) {
let where = {};
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,494 @@
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 Space_membershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const space_memberships = await db.space_memberships.create(
{
id: data.id || undefined,
role: data.role
||
null
,
status: data.status
||
null
,
joined_at: data.joined_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await space_memberships.setSpace( data.space || null, {
transaction,
});
await space_memberships.setUser( data.user || null, {
transaction,
});
return space_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 space_membershipsData = data.map((item, index) => ({
id: item.id || undefined,
role: item.role
||
null
,
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 space_memberships = await db.space_memberships.bulkCreate(space_membershipsData, { transaction });
// For each item created, replace relation files
return space_memberships;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const space_memberships = await db.space_memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.role !== undefined) updatePayload.role = data.role;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
updatePayload.updatedById = currentUser.id;
await space_memberships.update(updatePayload, {transaction});
if (data.space !== undefined) {
await space_memberships.setSpace(
data.space,
{ transaction }
);
}
if (data.user !== undefined) {
await space_memberships.setUser(
data.user,
{ transaction }
);
}
return space_memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const space_memberships = await db.space_memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of space_memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of space_memberships) {
await record.destroy({transaction});
}
});
return space_memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const space_memberships = await db.space_memberships.findByPk(id, options);
await space_memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await space_memberships.destroy({
transaction
});
return space_memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const space_memberships = await db.space_memberships.findOne(
{ where },
{ transaction },
);
if (!space_memberships) {
return space_memberships;
}
const output = space_memberships.get({plain: true});
output.space = await space_memberships.getSpace({
transaction
});
output.user = await space_memberships.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.spaces,
as: 'space',
where: filter.space ? {
[Op.or]: [
{ id: { [Op.in]: filter.space.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.space.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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.joined_atRange) {
const [start, end] = filter.joined_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.role) {
where = {
...where,
role: filter.role,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
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.space_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'space_memberships',
'status',
query,
),
],
};
}
const records = await db.space_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,541 @@
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 SpacesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const spaces = await db.spaces.create(
{
id: data.id || undefined,
name: data.name
||
null
,
name_bn: data.name_bn
||
null
,
visibility: data.visibility
||
null
,
space_kind: data.space_kind
||
null
,
description: data.description
||
null
,
unread_seed_count: data.unread_seed_count
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await spaces.setCategory( data.category || null, {
transaction,
});
return spaces;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const spacesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
name_bn: item.name_bn
||
null
,
visibility: item.visibility
||
null
,
space_kind: item.space_kind
||
null
,
description: item.description
||
null
,
unread_seed_count: item.unread_seed_count
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const spaces = await db.spaces.bulkCreate(spacesData, { transaction });
// For each item created, replace relation files
return spaces;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const spaces = await db.spaces.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.name_bn !== undefined) updatePayload.name_bn = data.name_bn;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.space_kind !== undefined) updatePayload.space_kind = data.space_kind;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.unread_seed_count !== undefined) updatePayload.unread_seed_count = data.unread_seed_count;
updatePayload.updatedById = currentUser.id;
await spaces.update(updatePayload, {transaction});
if (data.category !== undefined) {
await spaces.setCategory(
data.category,
{ transaction }
);
}
return spaces;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const spaces = await db.spaces.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of spaces) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of spaces) {
await record.destroy({transaction});
}
});
return spaces;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const spaces = await db.spaces.findByPk(id, options);
await spaces.update({
deletedBy: currentUser.id
}, {
transaction,
});
await spaces.destroy({
transaction
});
return spaces;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const spaces = await db.spaces.findOne(
{ where },
{ transaction },
);
if (!spaces) {
return spaces;
}
const output = spaces.get({plain: true});
output.space_memberships_space = await spaces.getSpace_memberships_space({
transaction
});
output.community_posts_space = await spaces.getCommunity_posts_space({
transaction
});
output.live_events_space = await spaces.getLive_events_space({
transaction
});
output.category = await spaces.getCategory({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.subject_categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
name_en: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'spaces',
'name',
filter.name,
),
};
}
if (filter.name_bn) {
where = {
...where,
[Op.and]: Utils.ilike(
'spaces',
'name_bn',
filter.name_bn,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'spaces',
'description',
filter.description,
),
};
}
if (filter.unread_seed_countRange) {
const [start, end] = filter.unread_seed_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unread_seed_count: {
...where.unread_seed_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unread_seed_count: {
...where.unread_seed_count,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
if (filter.space_kind) {
where = {
...where,
space_kind: filter.space_kind,
};
}
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.spaces.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'spaces',
'name',
query,
),
],
};
}
const records = await db.spaces.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,474 @@
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 Study_group_membershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const study_group_memberships = await db.study_group_memberships.create(
{
id: data.id || undefined,
role: data.role
||
null
,
joined_at: data.joined_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await study_group_memberships.setStudy_group( data.study_group || null, {
transaction,
});
await study_group_memberships.setUser( data.user || null, {
transaction,
});
return study_group_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 study_group_membershipsData = data.map((item, index) => ({
id: item.id || undefined,
role: item.role
||
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 study_group_memberships = await db.study_group_memberships.bulkCreate(study_group_membershipsData, { transaction });
// For each item created, replace relation files
return study_group_memberships;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const study_group_memberships = await db.study_group_memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.role !== undefined) updatePayload.role = data.role;
if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
updatePayload.updatedById = currentUser.id;
await study_group_memberships.update(updatePayload, {transaction});
if (data.study_group !== undefined) {
await study_group_memberships.setStudy_group(
data.study_group,
{ transaction }
);
}
if (data.user !== undefined) {
await study_group_memberships.setUser(
data.user,
{ transaction }
);
}
return study_group_memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const study_group_memberships = await db.study_group_memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of study_group_memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of study_group_memberships) {
await record.destroy({transaction});
}
});
return study_group_memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const study_group_memberships = await db.study_group_memberships.findByPk(id, options);
await study_group_memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await study_group_memberships.destroy({
transaction
});
return study_group_memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const study_group_memberships = await db.study_group_memberships.findOne(
{ where },
{ transaction },
);
if (!study_group_memberships) {
return study_group_memberships;
}
const output = study_group_memberships.get({plain: true});
output.study_group = await study_group_memberships.getStudy_group({
transaction
});
output.user = await study_group_memberships.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.study_groups,
as: 'study_group',
where: filter.study_group ? {
[Op.or]: [
{ id: { [Op.in]: filter.study_group.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.study_group.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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.joined_atRange) {
const [start, end] = filter.joined_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.role) {
where = {
...where,
role: filter.role,
};
}
if (filter.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.study_group_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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'study_group_memberships',
'role',
query,
),
],
};
}
const records = await db.study_group_memberships.findAll({
attributes: [ 'id', 'role' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['role', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.role,
}));
}
};

View File

@ -0,0 +1,546 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Study_group_messagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const study_group_messages = await db.study_group_messages.create(
{
id: data.id || undefined,
type: data.type
||
null
,
content: data.content
||
null
,
file_name: data.file_name
||
null
,
file_url: data.file_url
||
null
,
sent_at: data.sent_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await study_group_messages.setStudy_group( data.study_group || null, {
transaction,
});
await study_group_messages.setSender( data.sender || null, {
transaction,
});
return study_group_messages;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const study_group_messagesData = data.map((item, index) => ({
id: item.id || undefined,
type: item.type
||
null
,
content: item.content
||
null
,
file_name: item.file_name
||
null
,
file_url: item.file_url
||
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 study_group_messages = await db.study_group_messages.bulkCreate(study_group_messagesData, { transaction });
// For each item created, replace relation files
return study_group_messages;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const study_group_messages = await db.study_group_messages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.type !== undefined) updatePayload.type = data.type;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.file_name !== undefined) updatePayload.file_name = data.file_name;
if (data.file_url !== undefined) updatePayload.file_url = data.file_url;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
updatePayload.updatedById = currentUser.id;
await study_group_messages.update(updatePayload, {transaction});
if (data.study_group !== undefined) {
await study_group_messages.setStudy_group(
data.study_group,
{ transaction }
);
}
if (data.sender !== undefined) {
await study_group_messages.setSender(
data.sender,
{ transaction }
);
}
return study_group_messages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const study_group_messages = await db.study_group_messages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of study_group_messages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of study_group_messages) {
await record.destroy({transaction});
}
});
return study_group_messages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const study_group_messages = await db.study_group_messages.findByPk(id, options);
await study_group_messages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await study_group_messages.destroy({
transaction
});
return study_group_messages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const study_group_messages = await db.study_group_messages.findOne(
{ where },
{ transaction },
);
if (!study_group_messages) {
return study_group_messages;
}
const output = study_group_messages.get({plain: true});
output.study_group = await study_group_messages.getStudy_group({
transaction
});
output.sender = await study_group_messages.getSender({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.study_groups,
as: 'study_group',
where: filter.study_group ? {
[Op.or]: [
{ id: { [Op.in]: filter.study_group.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.study_group.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'sender',
where: filter.sender ? {
[Op.or]: [
{ id: { [Op.in]: filter.sender.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.sender.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'study_group_messages',
'content',
filter.content,
),
};
}
if (filter.file_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'study_group_messages',
'file_name',
filter.file_name,
),
};
}
if (filter.file_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'study_group_messages',
'file_url',
filter.file_url,
),
};
}
if (filter.sent_atRange) {
const [start, end] = filter.sent_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.type) {
where = {
...where,
type: filter.type,
};
}
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.study_group_messages.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'study_group_messages',
'content',
query,
),
],
};
}
const records = await db.study_group_messages.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,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 Study_group_postsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const study_group_posts = await db.study_group_posts.create(
{
id: data.id || undefined,
title: data.title
||
null
,
body: data.body
||
null
,
visibility: data.visibility
||
null
,
published_at: data.published_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await study_group_posts.setStudy_group( data.study_group || null, {
transaction,
});
await study_group_posts.setAuthor( data.author || null, {
transaction,
});
return study_group_posts;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const study_group_postsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
body: item.body
||
null
,
visibility: item.visibility
||
null
,
published_at: item.published_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const study_group_posts = await db.study_group_posts.bulkCreate(study_group_postsData, { transaction });
// For each item created, replace relation files
return study_group_posts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const study_group_posts = await db.study_group_posts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
updatePayload.updatedById = currentUser.id;
await study_group_posts.update(updatePayload, {transaction});
if (data.study_group !== undefined) {
await study_group_posts.setStudy_group(
data.study_group,
{ transaction }
);
}
if (data.author !== undefined) {
await study_group_posts.setAuthor(
data.author,
{ transaction }
);
}
return study_group_posts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const study_group_posts = await db.study_group_posts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of study_group_posts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of study_group_posts) {
await record.destroy({transaction});
}
});
return study_group_posts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const study_group_posts = await db.study_group_posts.findByPk(id, options);
await study_group_posts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await study_group_posts.destroy({
transaction
});
return study_group_posts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const study_group_posts = await db.study_group_posts.findOne(
{ where },
{ transaction },
);
if (!study_group_posts) {
return study_group_posts;
}
const output = study_group_posts.get({plain: true});
output.study_group = await study_group_posts.getStudy_group({
transaction
});
output.author = await study_group_posts.getAuthor({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.study_groups,
as: 'study_group',
where: filter.study_group ? {
[Op.or]: [
{ id: { [Op.in]: filter.study_group.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.study_group.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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'study_group_posts',
'title',
filter.title,
),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'study_group_posts',
'body',
filter.body,
),
};
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
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.study_group_posts.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'study_group_posts',
'title',
query,
),
],
};
}
const records = await db.study_group_posts.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,531 @@
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 Study_group_resourcesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const study_group_resources = await db.study_group_resources.create(
{
id: data.id || undefined,
title: data.title
||
null
,
url: data.url
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await study_group_resources.setStudy_group( data.study_group || null, {
transaction,
});
await study_group_resources.setAdded_by( data.added_by || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.study_group_resources.getTableName(),
belongsToColumn: 'files',
belongsToId: study_group_resources.id,
},
data.files,
options,
);
return study_group_resources;
}
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 study_group_resourcesData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
url: item.url
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const study_group_resources = await db.study_group_resources.bulkCreate(study_group_resourcesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < study_group_resources.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.study_group_resources.getTableName(),
belongsToColumn: 'files',
belongsToId: study_group_resources[i].id,
},
data[i].files,
options,
);
}
return study_group_resources;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const study_group_resources = await db.study_group_resources.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.url !== undefined) updatePayload.url = data.url;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await study_group_resources.update(updatePayload, {transaction});
if (data.study_group !== undefined) {
await study_group_resources.setStudy_group(
data.study_group,
{ transaction }
);
}
if (data.added_by !== undefined) {
await study_group_resources.setAdded_by(
data.added_by,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.study_group_resources.getTableName(),
belongsToColumn: 'files',
belongsToId: study_group_resources.id,
},
data.files,
options,
);
return study_group_resources;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const study_group_resources = await db.study_group_resources.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of study_group_resources) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of study_group_resources) {
await record.destroy({transaction});
}
});
return study_group_resources;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const study_group_resources = await db.study_group_resources.findByPk(id, options);
await study_group_resources.update({
deletedBy: currentUser.id
}, {
transaction,
});
await study_group_resources.destroy({
transaction
});
return study_group_resources;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const study_group_resources = await db.study_group_resources.findOne(
{ where },
{ transaction },
);
if (!study_group_resources) {
return study_group_resources;
}
const output = study_group_resources.get({plain: true});
output.study_group = await study_group_resources.getStudy_group({
transaction
});
output.added_by = await study_group_resources.getAdded_by({
transaction
});
output.files = await study_group_resources.getFiles({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.study_groups,
as: 'study_group',
where: filter.study_group ? {
[Op.or]: [
{ id: { [Op.in]: filter.study_group.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.study_group.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'added_by',
where: filter.added_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.added_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.added_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'study_group_resources',
'title',
filter.title,
),
};
}
if (filter.url) {
where = {
...where,
[Op.and]: Utils.ilike(
'study_group_resources',
'url',
filter.url,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'study_group_resources',
'notes',
filter.notes,
),
};
}
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.study_group_resources.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(
'study_group_resources',
'title',
query,
),
],
};
}
const records = await db.study_group_resources.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,538 @@
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 Study_groupsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const study_groups = await db.study_groups.create(
{
id: data.id || undefined,
name: data.name
||
null
,
visibility: data.visibility
||
null
,
member_limit: data.member_limit
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await study_groups.setSubject( data.subject || null, {
transaction,
});
await study_groups.setOwner( data.owner || null, {
transaction,
});
return study_groups;
}
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 study_groupsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
visibility: item.visibility
||
null
,
member_limit: item.member_limit
||
null
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const study_groups = await db.study_groups.bulkCreate(study_groupsData, { transaction });
// For each item created, replace relation files
return study_groups;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const study_groups = await db.study_groups.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.member_limit !== undefined) updatePayload.member_limit = data.member_limit;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await study_groups.update(updatePayload, {transaction});
if (data.subject !== undefined) {
await study_groups.setSubject(
data.subject,
{ transaction }
);
}
if (data.owner !== undefined) {
await study_groups.setOwner(
data.owner,
{ transaction }
);
}
return study_groups;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const study_groups = await db.study_groups.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of study_groups) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of study_groups) {
await record.destroy({transaction});
}
});
return study_groups;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const study_groups = await db.study_groups.findByPk(id, options);
await study_groups.update({
deletedBy: currentUser.id
}, {
transaction,
});
await study_groups.destroy({
transaction
});
return study_groups;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const study_groups = await db.study_groups.findOne(
{ where },
{ transaction },
);
if (!study_groups) {
return study_groups;
}
const output = study_groups.get({plain: true});
output.study_group_memberships_study_group = await study_groups.getStudy_group_memberships_study_group({
transaction
});
output.study_group_posts_study_group = await study_groups.getStudy_group_posts_study_group({
transaction
});
output.study_group_messages_study_group = await study_groups.getStudy_group_messages_study_group({
transaction
});
output.study_group_resources_study_group = await study_groups.getStudy_group_resources_study_group({
transaction
});
output.subject = await study_groups.getSubject({
transaction
});
output.owner = await study_groups.getOwner({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.subjects,
as: 'subject',
where: filter.subject ? {
[Op.or]: [
{ id: { [Op.in]: filter.subject.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.subject.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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'study_groups',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'study_groups',
'description',
filter.description,
),
};
}
if (filter.member_limitRange) {
const [start, end] = filter.member_limitRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
member_limit: {
...where.member_limit,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
member_limit: {
...where.member_limit,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
if (filter.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.study_groups.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(
'study_groups',
'name',
query,
),
],
};
}
const records = await db.study_groups.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,464 @@
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 Subject_categoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subject_categories = await db.subject_categories.create(
{
id: data.id || undefined,
name_bn: data.name_bn
||
null
,
name_en: data.name_en
||
null
,
icon_key: data.icon_key
||
null
,
seed_tutor_count: data.seed_tutor_count
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return subject_categories;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const subject_categoriesData = data.map((item, index) => ({
id: item.id || undefined,
name_bn: item.name_bn
||
null
,
name_en: item.name_en
||
null
,
icon_key: item.icon_key
||
null
,
seed_tutor_count: item.seed_tutor_count
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const subject_categories = await db.subject_categories.bulkCreate(subject_categoriesData, { transaction });
// For each item created, replace relation files
return subject_categories;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const subject_categories = await db.subject_categories.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_bn !== undefined) updatePayload.name_bn = data.name_bn;
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
if (data.icon_key !== undefined) updatePayload.icon_key = data.icon_key;
if (data.seed_tutor_count !== undefined) updatePayload.seed_tutor_count = data.seed_tutor_count;
updatePayload.updatedById = currentUser.id;
await subject_categories.update(updatePayload, {transaction});
return subject_categories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subject_categories = await db.subject_categories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of subject_categories) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of subject_categories) {
await record.destroy({transaction});
}
});
return subject_categories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const subject_categories = await db.subject_categories.findByPk(id, options);
await subject_categories.update({
deletedBy: currentUser.id
}, {
transaction,
});
await subject_categories.destroy({
transaction
});
return subject_categories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const subject_categories = await db.subject_categories.findOne(
{ where },
{ transaction },
);
if (!subject_categories) {
return subject_categories;
}
const output = subject_categories.get({plain: true});
output.subjects_category = await subject_categories.getSubjects_category({
transaction
});
output.gigs_category = await subject_categories.getGigs_category({
transaction
});
output.spaces_category = await subject_categories.getSpaces_category({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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_bn) {
where = {
...where,
[Op.and]: Utils.ilike(
'subject_categories',
'name_bn',
filter.name_bn,
),
};
}
if (filter.name_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'subject_categories',
'name_en',
filter.name_en,
),
};
}
if (filter.icon_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'subject_categories',
'icon_key',
filter.icon_key,
),
};
}
if (filter.seed_tutor_countRange) {
const [start, end] = filter.seed_tutor_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
seed_tutor_count: {
...where.seed_tutor_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
seed_tutor_count: {
...where.seed_tutor_count,
[Op.lte]: end,
},
};
}
}
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.subject_categories.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'subject_categories',
'name_en',
query,
),
],
};
}
const records = await db.subject_categories.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

View File

@ -0,0 +1,432 @@
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 SubjectsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subjects = await db.subjects.create(
{
id: data.id || undefined,
name: data.name
||
null
,
name_bn: data.name_bn
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await subjects.setCategory( data.category || null, {
transaction,
});
return subjects;
}
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 subjectsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
name_bn: item.name_bn
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const subjects = await db.subjects.bulkCreate(subjectsData, { transaction });
// For each item created, replace relation files
return subjects;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const subjects = await db.subjects.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.name_bn !== undefined) updatePayload.name_bn = data.name_bn;
updatePayload.updatedById = currentUser.id;
await subjects.update(updatePayload, {transaction});
if (data.category !== undefined) {
await subjects.setCategory(
data.category,
{ transaction }
);
}
return subjects;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subjects = await db.subjects.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of subjects) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of subjects) {
await record.destroy({transaction});
}
});
return subjects;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const subjects = await db.subjects.findByPk(id, options);
await subjects.update({
deletedBy: currentUser.id
}, {
transaction,
});
await subjects.destroy({
transaction
});
return subjects;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const subjects = await db.subjects.findOne(
{ where },
{ transaction },
);
if (!subjects) {
return subjects;
}
const output = subjects.get({plain: true});
output.study_groups_subject = await subjects.getStudy_groups_subject({
transaction
});
output.category = await subjects.getCategory({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.subject_categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
name_en: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'subjects',
'name',
filter.name,
),
};
}
if (filter.name_bn) {
where = {
...where,
[Op.and]: Utils.ilike(
'subjects',
'name_bn',
filter.name_bn,
),
};
}
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.subjects.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(
'subjects',
'name',
query,
),
],
};
}
const records = await db.subjects.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,
}));
}
};

367
backend/src/db/api/tags.js Normal file
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 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,
label: data.label
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ 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,
label: item.label
||
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 tags = await db.tags.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.label !== undefined) updatePayload.label = data.label;
updatePayload.updatedById = currentUser.id;
await tags.update(updatePayload, {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});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.label) {
where = {
...where,
[Op.and]: Utils.ilike(
'tags',
'label',
filter.label,
),
};
}
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.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, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'tags',
'label',
query,
),
],
};
}
const records = await db.tags.findAll({
attributes: [ 'id', 'label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.label,
}));
}
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,478 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class User_badgesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_badges = await db.user_badges.create(
{
id: data.id || undefined,
earned_at: data.earned_at
||
null
,
context: data.context
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await user_badges.setUser( data.user || null, {
transaction,
});
await user_badges.setBadge( data.badge || null, {
transaction,
});
return user_badges;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const user_badgesData = data.map((item, index) => ({
id: item.id || undefined,
earned_at: item.earned_at
||
null
,
context: item.context
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const user_badges = await db.user_badges.bulkCreate(user_badgesData, { transaction });
// For each item created, replace relation files
return user_badges;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_badges = await db.user_badges.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.earned_at !== undefined) updatePayload.earned_at = data.earned_at;
if (data.context !== undefined) updatePayload.context = data.context;
updatePayload.updatedById = currentUser.id;
await user_badges.update(updatePayload, {transaction});
if (data.user !== undefined) {
await user_badges.setUser(
data.user,
{ transaction }
);
}
if (data.badge !== undefined) {
await user_badges.setBadge(
data.badge,
{ transaction }
);
}
return user_badges;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_badges = await db.user_badges.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_badges) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_badges) {
await record.destroy({transaction});
}
});
return user_badges;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_badges = await db.user_badges.findByPk(id, options);
await user_badges.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_badges.destroy({
transaction
});
return user_badges;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_badges = await db.user_badges.findOne(
{ where },
{ transaction },
);
if (!user_badges) {
return user_badges;
}
const output = user_badges.get({plain: true});
output.user = await user_badges.getUser({
transaction
});
output.badge = await user_badges.getBadge({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.badges,
as: 'badge',
where: filter.badge ? {
[Op.or]: [
{ id: { [Op.in]: filter.badge.split('|').map(term => Utils.uuid(term)) } },
{
name_en: {
[Op.or]: filter.badge.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.context) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_badges',
'context',
filter.context,
),
};
}
if (filter.earned_atRange) {
const [start, end] = filter.earned_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
earned_at: {
...where.earned_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
earned_at: {
...where.earned_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.user_badges.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(
'user_badges',
'context',
query,
),
],
};
}
const records = await db.user_badges.findAll({
attributes: [ 'id', 'context' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['context', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.context,
}));
}
};

View File

@ -0,0 +1,515 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class User_gamificationDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_gamification = await db.user_gamification.create(
{
id: data.id || undefined,
points_total: data.points_total
||
null
,
streak_days: data.streak_days
||
null
,
last_activity_at: data.last_activity_at
||
null
,
daily_activity_json: data.daily_activity_json
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await user_gamification.setUser( data.user || null, {
transaction,
});
return user_gamification;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const user_gamificationData = data.map((item, index) => ({
id: item.id || undefined,
points_total: item.points_total
||
null
,
streak_days: item.streak_days
||
null
,
last_activity_at: item.last_activity_at
||
null
,
daily_activity_json: item.daily_activity_json
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const user_gamification = await db.user_gamification.bulkCreate(user_gamificationData, { transaction });
// For each item created, replace relation files
return user_gamification;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_gamification = await db.user_gamification.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.points_total !== undefined) updatePayload.points_total = data.points_total;
if (data.streak_days !== undefined) updatePayload.streak_days = data.streak_days;
if (data.last_activity_at !== undefined) updatePayload.last_activity_at = data.last_activity_at;
if (data.daily_activity_json !== undefined) updatePayload.daily_activity_json = data.daily_activity_json;
updatePayload.updatedById = currentUser.id;
await user_gamification.update(updatePayload, {transaction});
if (data.user !== undefined) {
await user_gamification.setUser(
data.user,
{ transaction }
);
}
return user_gamification;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_gamification = await db.user_gamification.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_gamification) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_gamification) {
await record.destroy({transaction});
}
});
return user_gamification;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_gamification = await db.user_gamification.findByPk(id, options);
await user_gamification.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_gamification.destroy({
transaction
});
return user_gamification;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_gamification = await db.user_gamification.findOne(
{ where },
{ transaction },
);
if (!user_gamification) {
return user_gamification;
}
const output = user_gamification.get({plain: true});
output.user = await user_gamification.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.daily_activity_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_gamification',
'daily_activity_json',
filter.daily_activity_json,
),
};
}
if (filter.points_totalRange) {
const [start, end] = filter.points_totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
points_total: {
...where.points_total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
points_total: {
...where.points_total,
[Op.lte]: end,
},
};
}
}
if (filter.streak_daysRange) {
const [start, end] = filter.streak_daysRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
streak_days: {
...where.streak_days,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
streak_days: {
...where.streak_days,
[Op.lte]: end,
},
};
}
}
if (filter.last_activity_atRange) {
const [start, end] = filter.last_activity_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_activity_at: {
...where.last_activity_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_activity_at: {
...where.last_activity_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.user_gamification.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(
'user_gamification',
'daily_activity_json',
query,
),
],
};
}
const records = await db.user_gamification.findAll({
attributes: [ 'id', 'daily_activity_json' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['daily_activity_json', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.daily_activity_json,
}));
}
};

View File

@ -0,0 +1,485 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class User_login_historyDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_login_history = await db.user_login_history.create(
{
id: data.id || undefined,
device_label: data.device_label
||
null
,
ip_address: data.ip_address
||
null
,
event: data.event
||
null
,
occurred_at: data.occurred_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await user_login_history.setUser( data.user || null, {
transaction,
});
return user_login_history;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const user_login_historyData = data.map((item, index) => ({
id: item.id || undefined,
device_label: item.device_label
||
null
,
ip_address: item.ip_address
||
null
,
event: item.event
||
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 user_login_history = await db.user_login_history.bulkCreate(user_login_historyData, { transaction });
// For each item created, replace relation files
return user_login_history;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_login_history = await db.user_login_history.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.device_label !== undefined) updatePayload.device_label = data.device_label;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
if (data.event !== undefined) updatePayload.event = data.event;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
updatePayload.updatedById = currentUser.id;
await user_login_history.update(updatePayload, {transaction});
if (data.user !== undefined) {
await user_login_history.setUser(
data.user,
{ transaction }
);
}
return user_login_history;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_login_history = await db.user_login_history.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_login_history) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_login_history) {
await record.destroy({transaction});
}
});
return user_login_history;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_login_history = await db.user_login_history.findByPk(id, options);
await user_login_history.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_login_history.destroy({
transaction
});
return user_login_history;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_login_history = await db.user_login_history.findOne(
{ where },
{ transaction },
);
if (!user_login_history) {
return user_login_history;
}
const output = user_login_history.get({plain: true});
output.user = await user_login_history.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.device_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_login_history',
'device_label',
filter.device_label,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_login_history',
'ip_address',
filter.ip_address,
),
};
}
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) {
where = {
...where,
event: filter.event,
};
}
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.user_login_history.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(
'user_login_history',
'device_label',
query,
),
],
};
}
const records = await db.user_login_history.findAll({
attributes: [ 'id', 'device_label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['device_label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.device_label,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,592 @@
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 Weekly_challengesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const weekly_challenges = await db.weekly_challenges.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
tasks_json: data.tasks_json
||
null
,
reward_points: data.reward_points
||
null
,
reward_badge_key: data.reward_badge_key
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return weekly_challenges;
}
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 weekly_challengesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
tasks_json: item.tasks_json
||
null
,
reward_points: item.reward_points
||
null
,
reward_badge_key: item.reward_badge_key
||
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 weekly_challenges = await db.weekly_challenges.bulkCreate(weekly_challengesData, { transaction });
// For each item created, replace relation files
return weekly_challenges;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const weekly_challenges = await db.weekly_challenges.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.tasks_json !== undefined) updatePayload.tasks_json = data.tasks_json;
if (data.reward_points !== undefined) updatePayload.reward_points = data.reward_points;
if (data.reward_badge_key !== undefined) updatePayload.reward_badge_key = data.reward_badge_key;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await weekly_challenges.update(updatePayload, {transaction});
return weekly_challenges;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const weekly_challenges = await db.weekly_challenges.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of weekly_challenges) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of weekly_challenges) {
await record.destroy({transaction});
}
});
return weekly_challenges;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const weekly_challenges = await db.weekly_challenges.findByPk(id, options);
await weekly_challenges.update({
deletedBy: currentUser.id
}, {
transaction,
});
await weekly_challenges.destroy({
transaction
});
return weekly_challenges;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const weekly_challenges = await db.weekly_challenges.findOne(
{ where },
{ transaction },
);
if (!weekly_challenges) {
return weekly_challenges;
}
const output = weekly_challenges.get({plain: true});
output.challenge_participations_challenge = await weekly_challenges.getChallenge_participations_challenge({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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(
'weekly_challenges',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'weekly_challenges',
'description',
filter.description,
),
};
}
if (filter.tasks_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'weekly_challenges',
'tasks_json',
filter.tasks_json,
),
};
}
if (filter.reward_badge_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'weekly_challenges',
'reward_badge_key',
filter.reward_badge_key,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_atRange) {
const [start, end] = filter.start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.lte]: end,
},
};
}
}
if (filter.end_atRange) {
const [start, end] = filter.end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.lte]: end,
},
};
}
}
if (filter.reward_pointsRange) {
const [start, end] = filter.reward_pointsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reward_points: {
...where.reward_points,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reward_points: {
...where.reward_points,
[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.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.weekly_challenges.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(
'weekly_challenges',
'name',
query,
),
],
};
}
const records = await db.weekly_challenges.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_mentorhub_demo',
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,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 admin_audit_logs = sequelize.define(
'admin_audit_logs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
action: {
type: DataTypes.ENUM,
values: [
"verification_approved",
"verification_rejected",
"verification_requested_more_docs",
"booking_force_release",
"booking_refund",
"dispute_resolved",
"user_suspended",
"user_banned",
"user_warned",
"password_reset",
"config_updated",
"impersonation_started",
"impersonation_ended",
"content_removed",
"content_kept"
],
},
target_entity: {
type: DataTypes.TEXT,
},
target_id: {
type: DataTypes.TEXT,
},
details: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
admin_audit_logs.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.admin_audit_logs.belongsTo(db.users, {
as: 'admin_user',
foreignKey: {
name: 'admin_userId',
},
constraints: false,
});
db.admin_audit_logs.belongsTo(db.users, {
as: 'createdBy',
});
db.admin_audit_logs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return admin_audit_logs;
};

View File

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

View File

@ -0,0 +1,338 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const bookings = sequelize.define(
'bookings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
level_number: {
type: DataTypes.INTEGER,
},
level_name: {
type: DataTypes.TEXT,
},
price: {
type: DataTypes.DECIMAL,
},
platform_fee: {
type: DataTypes.DECIMAL,
},
tutor_payout: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"pending_acceptance",
"active",
"milestone_submitted",
"revision_requested",
"completed",
"disputed",
"cancelled",
"refunded"
],
},
escrow_status: {
type: DataTypes.ENUM,
values: [
"held",
"released",
"refunded"
],
},
scheduled_at: {
type: DataTypes.DATE,
},
accepted_at: {
type: DataTypes.DATE,
},
milestone_submitted_at: {
type: DataTypes.DATE,
},
auto_release_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
deliverable_notes: {
type: DataTypes.TEXT,
},
revision_count: {
type: DataTypes.INTEGER,
},
revision_reason: {
type: DataTypes.TEXT,
},
jitsi_meet_meeting_id: {
type: DataTypes.TEXT,
},
jitsi_meet_password: {
type: DataTypes.TEXT,
},
admin_note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
bookings.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.bookings.hasMany(db.reviews, {
as: 'reviews_booking',
foreignKey: {
name: 'bookingId',
},
constraints: false,
});
db.bookings.hasMany(db.notes, {
as: 'notes_booking',
foreignKey: {
name: 'bookingId',
},
constraints: false,
});
db.bookings.hasMany(db.disputes, {
as: 'disputes_booking',
foreignKey: {
name: 'bookingId',
},
constraints: false,
});
db.bookings.hasMany(db.certificates, {
as: 'certificates_booking',
foreignKey: {
name: 'bookingId',
},
constraints: false,
});
//end loop
db.bookings.belongsTo(db.users, {
as: 'learner',
foreignKey: {
name: 'learnerId',
},
constraints: false,
});
db.bookings.belongsTo(db.users, {
as: 'tutor',
foreignKey: {
name: 'tutorId',
},
constraints: false,
});
db.bookings.belongsTo(db.gigs, {
as: 'gig',
foreignKey: {
name: 'gigId',
},
constraints: false,
});
db.bookings.belongsTo(db.gig_levels, {
as: 'gig_level',
foreignKey: {
name: 'gig_levelId',
},
constraints: false,
});
db.bookings.hasMany(db.file, {
as: 'deliverable_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.bookings.getTableName(),
belongsToColumn: 'deliverable_files',
},
});
db.bookings.belongsTo(db.users, {
as: 'createdBy',
});
db.bookings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return bookings;
};

View File

@ -0,0 +1,151 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const certificates = sequelize.define(
'certificates',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
subject_label: {
type: DataTypes.TEXT,
},
level_label: {
type: DataTypes.TEXT,
},
issued_at: {
type: DataTypes.DATE,
},
certificate_html: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
certificates.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.certificates.belongsTo(db.bookings, {
as: 'booking',
foreignKey: {
name: 'bookingId',
},
constraints: false,
});
db.certificates.belongsTo(db.users, {
as: 'learner',
foreignKey: {
name: 'learnerId',
},
constraints: false,
});
db.certificates.belongsTo(db.users, {
as: 'tutor',
foreignKey: {
name: 'tutorId',
},
constraints: false,
});
db.certificates.belongsTo(db.users, {
as: 'createdBy',
});
db.certificates.belongsTo(db.users, {
as: 'updatedBy',
});
};
return certificates;
};

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 challenge_participations = sequelize.define(
'challenge_participations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
progress_value: {
type: DataTypes.INTEGER,
},
target_value: {
type: DataTypes.INTEGER,
},
is_completed: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
completed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
challenge_participations.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.challenge_participations.belongsTo(db.weekly_challenges, {
as: 'challenge',
foreignKey: {
name: 'challengeId',
},
constraints: false,
});
db.challenge_participations.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.challenge_participations.belongsTo(db.users, {
as: 'createdBy',
});
db.challenge_participations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return challenge_participations;
};

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 community_comments = sequelize.define(
'community_comments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
body: {
type: DataTypes.TEXT,
},
visibility: {
type: DataTypes.ENUM,
values: [
"visible",
"hidden",
"removed"
],
},
like_count: {
type: DataTypes.INTEGER,
},
published_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
community_comments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.community_comments.hasMany(db.community_reactions, {
as: 'community_reactions_comment',
foreignKey: {
name: 'commentId',
},
constraints: false,
});
//end loop
db.community_comments.belongsTo(db.community_posts, {
as: 'post',
foreignKey: {
name: 'postId',
},
constraints: false,
});
db.community_comments.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.community_comments.belongsTo(db.community_comments, {
as: 'parent_comment',
foreignKey: {
name: 'parent_commentId',
},
constraints: false,
});
db.community_comments.belongsTo(db.users, {
as: 'createdBy',
});
db.community_comments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return community_comments;
};

View File

@ -0,0 +1,261 @@
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 community_posts = sequelize.define(
'community_posts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
post_type: {
type: DataTypes.ENUM,
values: [
"text",
"question",
"poll",
"resource",
"success_story",
"milestone_announcement",
"challenge_update"
],
},
title: {
type: DataTypes.TEXT,
},
body: {
type: DataTypes.TEXT,
},
image_url: {
type: DataTypes.TEXT,
},
resource_url: {
type: DataTypes.TEXT,
},
poll_options_json: {
type: DataTypes.TEXT,
},
is_pinned: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
visibility: {
type: DataTypes.ENUM,
values: [
"visible",
"hidden",
"removed"
],
},
like_count: {
type: DataTypes.INTEGER,
},
love_count: {
type: DataTypes.INTEGER,
},
insightful_count: {
type: DataTypes.INTEGER,
},
comment_count: {
type: DataTypes.INTEGER,
},
published_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
community_posts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.community_posts.hasMany(db.community_comments, {
as: 'community_comments_post',
foreignKey: {
name: 'postId',
},
constraints: false,
});
db.community_posts.hasMany(db.community_reactions, {
as: 'community_reactions_post',
foreignKey: {
name: 'postId',
},
constraints: false,
});
//end loop
db.community_posts.belongsTo(db.spaces, {
as: 'space',
foreignKey: {
name: 'spaceId',
},
constraints: false,
});
db.community_posts.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.community_posts.belongsTo(db.users, {
as: 'createdBy',
});
db.community_posts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return community_posts;
};

View File

@ -0,0 +1,152 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const community_reactions = sequelize.define(
'community_reactions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
reaction_type: {
type: DataTypes.ENUM,
values: [
"like",
"love",
"insightful",
"save"
],
},
reacted_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
community_reactions.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.community_reactions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.community_reactions.belongsTo(db.community_posts, {
as: 'post',
foreignKey: {
name: 'postId',
},
constraints: false,
});
db.community_reactions.belongsTo(db.community_comments, {
as: 'comment',
foreignKey: {
name: 'commentId',
},
constraints: false,
});
db.community_reactions.belongsTo(db.users, {
as: 'createdBy',
});
db.community_reactions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return community_reactions;
};

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 community_reports = sequelize.define(
'community_reports',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
content_type: {
type: DataTypes.ENUM,
values: [
"post",
"comment",
"user_profile"
],
},
content_id: {
type: DataTypes.TEXT,
},
reason: {
type: DataTypes.TEXT,
},
details: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"reviewing",
"resolved",
"dismissed"
],
},
resolved_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
community_reports.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.community_reports.belongsTo(db.users, {
as: 'reporter',
foreignKey: {
name: 'reporterId',
},
constraints: false,
});
db.community_reports.belongsTo(db.users, {
as: 'resolved_by',
foreignKey: {
name: 'resolved_byId',
},
constraints: false,
});
db.community_reports.belongsTo(db.users, {
as: 'createdBy',
});
db.community_reports.belongsTo(db.users, {
as: 'updatedBy',
});
};
return community_reports;
};

View File

@ -0,0 +1,151 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const conversations = sequelize.define(
'conversations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
last_message: {
type: DataTypes.TEXT,
},
last_message_at: {
type: DataTypes.DATE,
},
tutor_unread_count: {
type: DataTypes.INTEGER,
},
learner_unread_count: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
conversations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.conversations.hasMany(db.messages, {
as: 'messages_conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
//end loop
db.conversations.belongsTo(db.users, {
as: 'tutor',
foreignKey: {
name: 'tutorId',
},
constraints: false,
});
db.conversations.belongsTo(db.users, {
as: 'learner',
foreignKey: {
name: 'learnerId',
},
constraints: false,
});
db.conversations.belongsTo(db.users, {
as: 'createdBy',
});
db.conversations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return conversations;
};

View File

@ -0,0 +1,212 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const disputes = sequelize.define(
'disputes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
reason: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"under_review",
"resolved"
],
},
resolution: {
type: DataTypes.ENUM,
values: [
"none",
"tutor_favor",
"learner_favor",
"split"
],
},
admin_notes: {
type: DataTypes.TEXT,
},
resolved_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
disputes.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.disputes.belongsTo(db.bookings, {
as: 'booking',
foreignKey: {
name: 'bookingId',
},
constraints: false,
});
db.disputes.belongsTo(db.users, {
as: 'opened_by',
foreignKey: {
name: 'opened_byId',
},
constraints: false,
});
db.disputes.belongsTo(db.users, {
as: 'resolved_by',
foreignKey: {
name: 'resolved_byId',
},
constraints: false,
});
db.disputes.hasMany(db.file, {
as: 'tutor_evidence',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'tutor_evidence',
},
});
db.disputes.hasMany(db.file, {
as: 'learner_evidence',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'learner_evidence',
},
});
db.disputes.belongsTo(db.users, {
as: 'createdBy',
});
db.disputes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return disputes;
};

View File

@ -0,0 +1,141 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const event_rsvps = sequelize.define(
'event_rsvps',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"going",
"not_going",
"waitlist"
],
},
rsvped_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
event_rsvps.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.event_rsvps.belongsTo(db.live_events, {
as: 'event',
foreignKey: {
name: 'eventId',
},
constraints: false,
});
db.event_rsvps.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.event_rsvps.belongsTo(db.users, {
as: 'createdBy',
});
db.event_rsvps.belongsTo(db.users, {
as: 'updatedBy',
});
};
return event_rsvps;
};

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,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 gig_levels = sequelize.define(
'gig_levels',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
level_number: {
type: DataTypes.INTEGER,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
deliverables_json: {
type: DataTypes.TEXT,
},
price: {
type: DataTypes.DECIMAL,
},
duration_minutes: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
gig_levels.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.gig_levels.hasMany(db.bookings, {
as: 'bookings_gig_level',
foreignKey: {
name: 'gig_levelId',
},
constraints: false,
});
//end loop
db.gig_levels.belongsTo(db.gigs, {
as: 'gig',
foreignKey: {
name: 'gigId',
},
constraints: false,
});
db.gig_levels.belongsTo(db.users, {
as: 'createdBy',
});
db.gig_levels.belongsTo(db.users, {
as: 'updatedBy',
});
};
return gig_levels;
};

View File

@ -0,0 +1,211 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const gigs = sequelize.define(
'gigs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"paused",
"under_review"
],
},
impressions: {
type: DataTypes.INTEGER,
},
total_orders: {
type: DataTypes.INTEGER,
},
rating: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
gigs.associate = (db) => {
db.gigs.belongsToMany(db.tags, {
as: 'tags',
foreignKey: {
name: 'gigs_tagsId',
},
constraints: false,
through: 'gigsTagsTags',
});
db.gigs.belongsToMany(db.tags, {
as: 'tags_filter',
foreignKey: {
name: 'gigs_tagsId',
},
constraints: false,
through: 'gigsTagsTags',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.gigs.hasMany(db.gig_levels, {
as: 'gig_levels_gig',
foreignKey: {
name: 'gigId',
},
constraints: false,
});
db.gigs.hasMany(db.bookings, {
as: 'bookings_gig',
foreignKey: {
name: 'gigId',
},
constraints: false,
});
db.gigs.hasMany(db.invites, {
as: 'invites_gig',
foreignKey: {
name: 'gigId',
},
constraints: false,
});
//end loop
db.gigs.belongsTo(db.tutor_profiles, {
as: 'tutor_profile',
foreignKey: {
name: 'tutor_profileId',
},
constraints: false,
});
db.gigs.belongsTo(db.subject_categories, {
as: 'category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
db.gigs.belongsTo(db.users, {
as: 'createdBy',
});
db.gigs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return gigs;
};

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,169 @@
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 invites = sequelize.define(
'invites',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
message: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"sent",
"accepted",
"declined",
"expired",
"cancelled"
],
},
sent_at: {
type: DataTypes.DATE,
},
responded_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
invites.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.invites.belongsTo(db.users, {
as: 'sender',
foreignKey: {
name: 'senderId',
},
constraints: false,
});
db.invites.belongsTo(db.users, {
as: 'receiver',
foreignKey: {
name: 'receiverId',
},
constraints: false,
});
db.invites.belongsTo(db.gigs, {
as: 'gig',
foreignKey: {
name: 'gigId',
},
constraints: false,
});
db.invites.belongsTo(db.users, {
as: 'createdBy',
});
db.invites.belongsTo(db.users, {
as: 'updatedBy',
});
};
return invites;
};

View File

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

View File

@ -0,0 +1,202 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const learner_profiles = sequelize.define(
'learner_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
main_goal: {
type: DataTypes.ENUM,
values: [
"admission_prep",
"career_switch",
"skill_up",
"exam_result",
"study_abroad",
"personal_interest"
],
},
preferred_session_format: {
type: DataTypes.ENUM,
values: [
"live_video",
"async_review",
"both"
],
},
session_language_preference: {
type: DataTypes.ENUM,
values: [
"bangla",
"english",
"either"
],
},
budget_range: {
type: DataTypes.ENUM,
values: [
"bdt_300_600",
"bdt_600_1200",
"bdt_1200_2500",
"bdt_2500_plus"
],
},
availability_json: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
learner_profiles.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.learner_profiles.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.learner_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.learner_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return learner_profiles;
};

View File

@ -0,0 +1,241 @@
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 live_events = sequelize.define(
'live_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
event_type: {
type: DataTypes.ENUM,
values: [
"free_webinar",
"paid_masterclass",
"group_study_session",
"qa_session"
],
},
meeting_provider: {
type: DataTypes.ENUM,
values: [
"jitsi",
"zoom",
"google_meet",
"other"
],
},
meeting_link: {
type: DataTypes.TEXT,
},
recording_link: {
type: DataTypes.TEXT,
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
capacity: {
type: DataTypes.INTEGER,
},
price_amount: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
live_events.associate = (db) => {
db.live_events.belongsToMany(db.tags, {
as: 'tags',
foreignKey: {
name: 'live_events_tagsId',
},
constraints: false,
through: 'live_eventsTagsTags',
});
db.live_events.belongsToMany(db.tags, {
as: 'tags_filter',
foreignKey: {
name: 'live_events_tagsId',
},
constraints: false,
through: 'live_eventsTagsTags',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.live_events.hasMany(db.event_rsvps, {
as: 'event_rsvps_event',
foreignKey: {
name: 'eventId',
},
constraints: false,
});
//end loop
db.live_events.belongsTo(db.users, {
as: 'host',
foreignKey: {
name: 'hostId',
},
constraints: false,
});
db.live_events.belongsTo(db.spaces, {
as: 'space',
foreignKey: {
name: 'spaceId',
},
constraints: false,
});
db.live_events.belongsTo(db.users, {
as: 'createdBy',
});
db.live_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return live_events;
};

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 messages = sequelize.define(
'messages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
type: {
type: DataTypes.ENUM,
values: [
"text",
"file",
"system",
"booking_link"
],
},
content: {
type: DataTypes.TEXT,
},
file_url: {
type: DataTypes.TEXT,
},
file_name: {
type: DataTypes.TEXT,
},
is_pii_masked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_read: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
sent_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
messages.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.messages.belongsTo(db.conversations, {
as: 'conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.messages.belongsTo(db.users, {
as: 'sender',
foreignKey: {
name: 'senderId',
},
constraints: false,
});
db.messages.belongsTo(db.users, {
as: 'receiver',
foreignKey: {
name: 'receiverId',
},
constraints: false,
});
db.messages.belongsTo(db.users, {
as: 'createdBy',
});
db.messages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return messages;
};

View File

@ -0,0 +1,135 @@
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 notes = sequelize.define(
'notes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
tutor_private_notes: {
type: DataTypes.TEXT,
},
learner_private_notes: {
type: DataTypes.TEXT,
},
shared_notes: {
type: DataTypes.TEXT,
},
session_summary: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notes.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.notes.belongsTo(db.bookings, {
as: 'booking',
foreignKey: {
name: 'bookingId',
},
constraints: false,
});
db.notes.belongsTo(db.users, {
as: 'createdBy',
});
db.notes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notes;
};

View File

@ -0,0 +1,196 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const notifications = sequelize.define(
'notifications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
type: {
type: DataTypes.ENUM,
values: [
"new_booking",
"booking_accepted",
"booking_declined",
"milestone_submitted",
"funds_released",
"revision_requested",
"dispute_opened",
"dispute_resolved",
"new_message",
"new_review",
"invite_sent",
"verification_update",
"auto_release",
"community_reply",
"challenge_complete",
"badge_earned"
],
},
title: {
type: DataTypes.TEXT,
},
body: {
type: DataTypes.TEXT,
},
link: {
type: DataTypes.TEXT,
},
is_read: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notifications.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.notifications.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.notifications.belongsTo(db.users, {
as: 'createdBy',
});
db.notifications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notifications;
};

View File

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

View File

@ -0,0 +1,195 @@
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 platform_config = sequelize.define(
'platform_config',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
platform_fee_percent: {
type: DataTypes.DECIMAL,
},
auto_release_days: {
type: DataTypes.INTEGER,
},
max_revision_count: {
type: DataTypes.INTEGER,
},
min_review_length: {
type: DataTypes.INTEGER,
},
new_user_verify_email: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
tutor_two_factor_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
maintenance_mode: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
maintenance_message: {
type: DataTypes.TEXT,
},
announcement_banner_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
announcement_banner_text: {
type: DataTypes.TEXT,
},
jitsi_sdk_key: {
type: DataTypes.TEXT,
},
jitsi_sdk_secret: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
platform_config.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.platform_config.belongsTo(db.users, {
as: 'createdBy',
});
db.platform_config.belongsTo(db.users, {
as: 'updatedBy',
});
};
return platform_config;
};

View File

@ -0,0 +1,215 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const reviews = sequelize.define(
'reviews',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
rating: {
type: DataTypes.DECIMAL,
},
communication_rating: {
type: DataTypes.INTEGER,
},
knowledge_rating: {
type: DataTypes.INTEGER,
},
punctuality_rating: {
type: DataTypes.INTEGER,
},
value_rating: {
type: DataTypes.INTEGER,
},
review_text: {
type: DataTypes.TEXT,
},
would_recommend: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
tutor_response: {
type: DataTypes.TEXT,
},
tutor_response_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"published",
"removed"
],
},
published_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
reviews.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.reviews.belongsTo(db.bookings, {
as: 'booking',
foreignKey: {
name: 'bookingId',
},
constraints: false,
});
db.reviews.belongsTo(db.users, {
as: 'tutor',
foreignKey: {
name: 'tutorId',
},
constraints: false,
});
db.reviews.belongsTo(db.users, {
as: 'learner',
foreignKey: {
name: 'learnerId',
},
constraints: false,
});
db.reviews.belongsTo(db.users, {
as: 'createdBy',
});
db.reviews.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reviews;
};

View File

@ -0,0 +1,139 @@
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,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
roles.associate = (db) => {
db.roles.belongsToMany(db.permissions, {
as: 'permissions',
foreignKey: {
name: 'roles_permissionsId',
},
constraints: false,
through: 'rolesPermissionsPermissions',
});
db.roles.belongsToMany(db.permissions, {
as: 'permissions_filter',
foreignKey: {
name: 'roles_permissionsId',
},
constraints: false,
through: 'rolesPermissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.roles.hasMany(db.users, {
as: 'users_app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
//end loop
db.roles.belongsTo(db.users, {
as: 'createdBy',
});
db.roles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return roles;
};

View File

@ -0,0 +1,163 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const space_memberships = sequelize.define(
'space_memberships',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
role: {
type: DataTypes.ENUM,
values: [
"member",
"moderator",
"admin"
],
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"requested",
"invited",
"banned"
],
},
joined_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
space_memberships.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.space_memberships.belongsTo(db.spaces, {
as: 'space',
foreignKey: {
name: 'spaceId',
},
constraints: false,
});
db.space_memberships.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.space_memberships.belongsTo(db.users, {
as: 'createdBy',
});
db.space_memberships.belongsTo(db.users, {
as: 'updatedBy',
});
};
return space_memberships;
};

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 spaces = sequelize.define(
'spaces',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
name_bn: {
type: DataTypes.TEXT,
},
visibility: {
type: DataTypes.ENUM,
values: [
"public",
"private",
"secret",
"locked"
],
},
space_kind: {
type: DataTypes.ENUM,
values: [
"general",
"subject_space",
"tutor_lounge",
"welcome",
"weekly_challenge",
"live_events"
],
},
description: {
type: DataTypes.TEXT,
},
unread_seed_count: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
spaces.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.spaces.hasMany(db.space_memberships, {
as: 'space_memberships_space',
foreignKey: {
name: 'spaceId',
},
constraints: false,
});
db.spaces.hasMany(db.community_posts, {
as: 'community_posts_space',
foreignKey: {
name: 'spaceId',
},
constraints: false,
});
db.spaces.hasMany(db.live_events, {
as: 'live_events_space',
foreignKey: {
name: 'spaceId',
},
constraints: false,
});
//end loop
db.spaces.belongsTo(db.subject_categories, {
as: 'category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
db.spaces.belongsTo(db.users, {
as: 'createdBy',
});
db.spaces.belongsTo(db.users, {
as: 'updatedBy',
});
};
return spaces;
};

View File

@ -0,0 +1,141 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const study_group_memberships = sequelize.define(
'study_group_memberships',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
role: {
type: DataTypes.ENUM,
values: [
"member",
"moderator",
"owner"
],
},
joined_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
study_group_memberships.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.study_group_memberships.belongsTo(db.study_groups, {
as: 'study_group',
foreignKey: {
name: 'study_groupId',
},
constraints: false,
});
db.study_group_memberships.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.study_group_memberships.belongsTo(db.users, {
as: 'createdBy',
});
db.study_group_memberships.belongsTo(db.users, {
as: 'updatedBy',
});
};
return study_group_memberships;
};

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 study_group_messages = sequelize.define(
'study_group_messages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
type: {
type: DataTypes.ENUM,
values: [
"text",
"file",
"system"
],
},
content: {
type: DataTypes.TEXT,
},
file_name: {
type: DataTypes.TEXT,
},
file_url: {
type: DataTypes.TEXT,
},
sent_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
study_group_messages.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.study_group_messages.belongsTo(db.study_groups, {
as: 'study_group',
foreignKey: {
name: 'study_groupId',
},
constraints: false,
});
db.study_group_messages.belongsTo(db.users, {
as: 'sender',
foreignKey: {
name: 'senderId',
},
constraints: false,
});
db.study_group_messages.belongsTo(db.users, {
as: 'createdBy',
});
db.study_group_messages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return study_group_messages;
};

View File

@ -0,0 +1,152 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const study_group_posts = sequelize.define(
'study_group_posts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
body: {
type: DataTypes.TEXT,
},
visibility: {
type: DataTypes.ENUM,
values: [
"visible",
"removed"
],
},
published_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
study_group_posts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.study_group_posts.belongsTo(db.study_groups, {
as: 'study_group',
foreignKey: {
name: 'study_groupId',
},
constraints: false,
});
db.study_group_posts.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.study_group_posts.belongsTo(db.users, {
as: 'createdBy',
});
db.study_group_posts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return study_group_posts;
};

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 study_group_resources = sequelize.define(
'study_group_resources',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
url: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
study_group_resources.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.study_group_resources.belongsTo(db.study_groups, {
as: 'study_group',
foreignKey: {
name: 'study_groupId',
},
constraints: false,
});
db.study_group_resources.belongsTo(db.users, {
as: 'added_by',
foreignKey: {
name: 'added_byId',
},
constraints: false,
});
db.study_group_resources.hasMany(db.file, {
as: 'files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.study_group_resources.getTableName(),
belongsToColumn: 'files',
},
});
db.study_group_resources.belongsTo(db.users, {
as: 'createdBy',
});
db.study_group_resources.belongsTo(db.users, {
as: 'updatedBy',
});
};
return study_group_resources;
};

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 study_groups = sequelize.define(
'study_groups',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
visibility: {
type: DataTypes.ENUM,
values: [
"public",
"private"
],
},
member_limit: {
type: DataTypes.INTEGER,
},
description: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
study_groups.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.study_groups.hasMany(db.study_group_memberships, {
as: 'study_group_memberships_study_group',
foreignKey: {
name: 'study_groupId',
},
constraints: false,
});
db.study_groups.hasMany(db.study_group_posts, {
as: 'study_group_posts_study_group',
foreignKey: {
name: 'study_groupId',
},
constraints: false,
});
db.study_groups.hasMany(db.study_group_messages, {
as: 'study_group_messages_study_group',
foreignKey: {
name: 'study_groupId',
},
constraints: false,
});
db.study_groups.hasMany(db.study_group_resources, {
as: 'study_group_resources_study_group',
foreignKey: {
name: 'study_groupId',
},
constraints: false,
});
//end loop
db.study_groups.belongsTo(db.subjects, {
as: 'subject',
foreignKey: {
name: 'subjectId',
},
constraints: false,
});
db.study_groups.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.study_groups.belongsTo(db.users, {
as: 'createdBy',
});
db.study_groups.belongsTo(db.users, {
as: 'updatedBy',
});
};
return study_groups;
};

View File

@ -0,0 +1,151 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const subject_categories = sequelize.define(
'subject_categories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_bn: {
type: DataTypes.TEXT,
},
name_en: {
type: DataTypes.TEXT,
},
icon_key: {
type: DataTypes.TEXT,
},
seed_tutor_count: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
subject_categories.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.subject_categories.hasMany(db.subjects, {
as: 'subjects_category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
db.subject_categories.hasMany(db.gigs, {
as: 'gigs_category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
db.subject_categories.hasMany(db.spaces, {
as: 'spaces_category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
//end loop
db.subject_categories.belongsTo(db.users, {
as: 'createdBy',
});
db.subject_categories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return subject_categories;
};

View File

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

View File

@ -0,0 +1,106 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const tags = sequelize.define(
'tags',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
label: {
type: DataTypes.TEXT,
},
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
//end loop
db.tags.belongsTo(db.users, {
as: 'createdBy',
});
db.tags.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tags;
};

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