Initial version

This commit is contained in:
Flatlogic Bot 2026-03-16 18:07:00 +00:00
commit 1b832e87de
616 changed files with 166937 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>Daily Doodle App</h2>
<p>Daily Doodle: earn and spend virtual coins for memberships, media, games, and chat with admin management 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 @@
# Daily Doodle App
## 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_39219
DB_USER=app_39219
DB_PASS=73d96fbc-80c6-4bec-bd70-5b0b4f3016f9
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 @@
#Daily Doodle App - 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_daily_doodle_app;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_daily_doodle_app 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": "dailydoodleapp",
"description": "Daily Doodle App - 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: "73d96fbc",
user_pass: "5b0b4f3016f9",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '73d96fbc-80c6-4bec-bd70-5b0b4f3016f9',
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: 'Daily Doodle App <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: 'Member',
},
project_uuid: '73d96fbc-80c6-4bec-bd70-5b0b4f3016f9',
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 = 'Colorful doodles on notebook page';
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,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 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
,
entity_name: data.entity_name
||
null
,
entity_reference: data.entity_reference
||
null
,
occurred_at: data.occurred_at
||
null
,
details: data.details
||
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
,
entity_name: item.entity_name
||
null
,
entity_reference: item.entity_reference
||
null
,
occurred_at: item.occurred_at
||
null
,
details: item.details
||
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.entity_name !== undefined) updatePayload.entity_name = data.entity_name;
if (data.entity_reference !== undefined) updatePayload.entity_reference = data.entity_reference;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
if (data.details !== undefined) updatePayload.details = data.details;
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.entity_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'admin_audit_logs',
'entity_name',
filter.entity_name,
),
};
}
if (filter.entity_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'admin_audit_logs',
'entity_reference',
filter.entity_reference,
),
};
}
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',
'entity_name',
query,
),
],
};
}
const records = await db.admin_audit_logs.findAll({
attributes: [ 'id', 'entity_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['entity_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.entity_name,
}));
}
};

View File

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

View File

@ -0,0 +1,413 @@
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 Article_contentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const article_contents = await db.article_contents.create(
{
id: data.id || undefined,
body: data.body
||
null
,
excerpt: data.excerpt
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await article_contents.setProduct( data.product || null, {
transaction,
});
return article_contents;
}
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 article_contentsData = data.map((item, index) => ({
id: item.id || undefined,
body: item.body
||
null
,
excerpt: item.excerpt
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const article_contents = await db.article_contents.bulkCreate(article_contentsData, { transaction });
// For each item created, replace relation files
return article_contents;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const article_contents = await db.article_contents.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.body !== undefined) updatePayload.body = data.body;
if (data.excerpt !== undefined) updatePayload.excerpt = data.excerpt;
updatePayload.updatedById = currentUser.id;
await article_contents.update(updatePayload, {transaction});
if (data.product !== undefined) {
await article_contents.setProduct(
data.product,
{ transaction }
);
}
return article_contents;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const article_contents = await db.article_contents.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of article_contents) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of article_contents) {
await record.destroy({transaction});
}
});
return article_contents;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const article_contents = await db.article_contents.findByPk(id, options);
await article_contents.update({
deletedBy: currentUser.id
}, {
transaction,
});
await article_contents.destroy({
transaction
});
return article_contents;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const article_contents = await db.article_contents.findOne(
{ where },
{ transaction },
);
if (!article_contents) {
return article_contents;
}
const output = article_contents.get({plain: true});
output.product = await article_contents.getProduct({
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.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'article_contents',
'body',
filter.body,
),
};
}
if (filter.excerpt) {
where = {
...where,
[Op.and]: Utils.ilike(
'article_contents',
'excerpt',
filter.excerpt,
),
};
}
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.article_contents.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(
'article_contents',
'excerpt',
query,
),
],
};
}
const records = await db.article_contents.findAll({
attributes: [ 'id', 'excerpt' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['excerpt', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.excerpt,
}));
}
};

View File

@ -0,0 +1,518 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Chat_membershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const chat_memberships = await db.chat_memberships.create(
{
id: data.id || undefined,
member_role: data.member_role
||
null
,
joined_at: data.joined_at
||
null
,
left_at: data.left_at
||
null
,
muted: data.muted
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await chat_memberships.setChat_room( data.chat_room || null, {
transaction,
});
await chat_memberships.setUser( data.user || null, {
transaction,
});
return chat_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 chat_membershipsData = data.map((item, index) => ({
id: item.id || undefined,
member_role: item.member_role
||
null
,
joined_at: item.joined_at
||
null
,
left_at: item.left_at
||
null
,
muted: item.muted
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const chat_memberships = await db.chat_memberships.bulkCreate(chat_membershipsData, { transaction });
// For each item created, replace relation files
return chat_memberships;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const chat_memberships = await db.chat_memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.member_role !== undefined) updatePayload.member_role = data.member_role;
if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
if (data.left_at !== undefined) updatePayload.left_at = data.left_at;
if (data.muted !== undefined) updatePayload.muted = data.muted;
updatePayload.updatedById = currentUser.id;
await chat_memberships.update(updatePayload, {transaction});
if (data.chat_room !== undefined) {
await chat_memberships.setChat_room(
data.chat_room,
{ transaction }
);
}
if (data.user !== undefined) {
await chat_memberships.setUser(
data.user,
{ transaction }
);
}
return chat_memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const chat_memberships = await db.chat_memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of chat_memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of chat_memberships) {
await record.destroy({transaction});
}
});
return chat_memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const chat_memberships = await db.chat_memberships.findByPk(id, options);
await chat_memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await chat_memberships.destroy({
transaction
});
return chat_memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const chat_memberships = await db.chat_memberships.findOne(
{ where },
{ transaction },
);
if (!chat_memberships) {
return chat_memberships;
}
const output = chat_memberships.get({plain: true});
output.chat_room = await chat_memberships.getChat_room({
transaction
});
output.user = await chat_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.chat_rooms,
as: 'chat_room',
where: filter.chat_room ? {
[Op.or]: [
{ id: { [Op.in]: filter.chat_room.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.chat_room.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.left_atRange) {
const [start, end] = filter.left_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
left_at: {
...where.left_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
left_at: {
...where.left_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.member_role) {
where = {
...where,
member_role: filter.member_role,
};
}
if (filter.muted) {
where = {
...where,
muted: filter.muted,
};
}
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.chat_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(
'chat_memberships',
'member_role',
query,
),
],
};
}
const records = await db.chat_memberships.findAll({
attributes: [ 'id', 'member_role' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['member_role', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.member_role,
}));
}
};

View File

@ -0,0 +1,564 @@
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 Chat_messagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const chat_messages = await db.chat_messages.create(
{
id: data.id || undefined,
message_text: data.message_text
||
null
,
sent_at: data.sent_at
||
null
,
edited_at: data.edited_at
||
null
,
deleted: data.deleted
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await chat_messages.setChat_room( data.chat_room || null, {
transaction,
});
await chat_messages.setSender( data.sender || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.chat_messages.getTableName(),
belongsToColumn: 'attachments',
belongsToId: chat_messages.id,
},
data.attachments,
options,
);
return chat_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 chat_messagesData = data.map((item, index) => ({
id: item.id || undefined,
message_text: item.message_text
||
null
,
sent_at: item.sent_at
||
null
,
edited_at: item.edited_at
||
null
,
deleted: item.deleted
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const chat_messages = await db.chat_messages.bulkCreate(chat_messagesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < chat_messages.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.chat_messages.getTableName(),
belongsToColumn: 'attachments',
belongsToId: chat_messages[i].id,
},
data[i].attachments,
options,
);
}
return chat_messages;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const chat_messages = await db.chat_messages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.message_text !== undefined) updatePayload.message_text = data.message_text;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.edited_at !== undefined) updatePayload.edited_at = data.edited_at;
if (data.deleted !== undefined) updatePayload.deleted = data.deleted;
updatePayload.updatedById = currentUser.id;
await chat_messages.update(updatePayload, {transaction});
if (data.chat_room !== undefined) {
await chat_messages.setChat_room(
data.chat_room,
{ transaction }
);
}
if (data.sender !== undefined) {
await chat_messages.setSender(
data.sender,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.chat_messages.getTableName(),
belongsToColumn: 'attachments',
belongsToId: chat_messages.id,
},
data.attachments,
options,
);
return chat_messages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const chat_messages = await db.chat_messages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of chat_messages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of chat_messages) {
await record.destroy({transaction});
}
});
return chat_messages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const chat_messages = await db.chat_messages.findByPk(id, options);
await chat_messages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await chat_messages.destroy({
transaction
});
return chat_messages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const chat_messages = await db.chat_messages.findOne(
{ where },
{ transaction },
);
if (!chat_messages) {
return chat_messages;
}
const output = chat_messages.get({plain: true});
output.chat_room = await chat_messages.getChat_room({
transaction
});
output.sender = await chat_messages.getSender({
transaction
});
output.attachments = await chat_messages.getAttachments({
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.chat_rooms,
as: 'chat_room',
where: filter.chat_room ? {
[Op.or]: [
{ id: { [Op.in]: filter.chat_room.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.chat_room.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.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.message_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'chat_messages',
'message_text',
filter.message_text,
),
};
}
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.edited_atRange) {
const [start, end] = filter.edited_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
edited_at: {
...where.edited_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
edited_at: {
...where.edited_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.deleted) {
where = {
...where,
deleted: filter.deleted,
};
}
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.chat_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(
'chat_messages',
'message_text',
query,
),
],
};
}
const records = await db.chat_messages.findAll({
attributes: [ 'id', 'message_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['message_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.message_text,
}));
}
};

View File

@ -0,0 +1,513 @@
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 Chat_roomsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const chat_rooms = await db.chat_rooms.create(
{
id: data.id || undefined,
room_type: data.room_type
||
null
,
name: data.name
||
null
,
private_room: data.private_room
||
false
,
created_at_time: data.created_at_time
||
null
,
last_message_at: data.last_message_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await chat_rooms.setCreated_by_user( data.created_by_user || null, {
transaction,
});
return chat_rooms;
}
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 chat_roomsData = data.map((item, index) => ({
id: item.id || undefined,
room_type: item.room_type
||
null
,
name: item.name
||
null
,
private_room: item.private_room
||
false
,
created_at_time: item.created_at_time
||
null
,
last_message_at: item.last_message_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const chat_rooms = await db.chat_rooms.bulkCreate(chat_roomsData, { transaction });
// For each item created, replace relation files
return chat_rooms;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const chat_rooms = await db.chat_rooms.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.room_type !== undefined) updatePayload.room_type = data.room_type;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.private_room !== undefined) updatePayload.private_room = data.private_room;
if (data.created_at_time !== undefined) updatePayload.created_at_time = data.created_at_time;
if (data.last_message_at !== undefined) updatePayload.last_message_at = data.last_message_at;
updatePayload.updatedById = currentUser.id;
await chat_rooms.update(updatePayload, {transaction});
if (data.created_by_user !== undefined) {
await chat_rooms.setCreated_by_user(
data.created_by_user,
{ transaction }
);
}
return chat_rooms;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const chat_rooms = await db.chat_rooms.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of chat_rooms) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of chat_rooms) {
await record.destroy({transaction});
}
});
return chat_rooms;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const chat_rooms = await db.chat_rooms.findByPk(id, options);
await chat_rooms.update({
deletedBy: currentUser.id
}, {
transaction,
});
await chat_rooms.destroy({
transaction
});
return chat_rooms;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const chat_rooms = await db.chat_rooms.findOne(
{ where },
{ transaction },
);
if (!chat_rooms) {
return chat_rooms;
}
const output = chat_rooms.get({plain: true});
output.chat_memberships_chat_room = await chat_rooms.getChat_memberships_chat_room({
transaction
});
output.chat_messages_chat_room = await chat_rooms.getChat_messages_chat_room({
transaction
});
output.created_by_user = await chat_rooms.getCreated_by_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: 'created_by_user',
where: filter.created_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_by_user.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(
'chat_rooms',
'name',
filter.name,
),
};
}
if (filter.created_at_timeRange) {
const [start, end] = filter.created_at_timeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_time: {
...where.created_at_time,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_time: {
...where.created_at_time,
[Op.lte]: end,
},
};
}
}
if (filter.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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.room_type) {
where = {
...where,
room_type: filter.room_type,
};
}
if (filter.private_room) {
where = {
...where,
private_room: filter.private_room,
};
}
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.chat_rooms.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(
'chat_rooms',
'name',
query,
),
],
};
}
const records = await db.chat_rooms.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,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 Coin_code_redemptionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const coin_code_redemptions = await db.coin_code_redemptions.create(
{
id: data.id || undefined,
redeemed_at: data.redeemed_at
||
null
,
amount_doodlecoins: data.amount_doodlecoins
||
null
,
status_message: data.status_message
||
null
,
successful: data.successful
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await coin_code_redemptions.setCoin_code( data.coin_code || null, {
transaction,
});
await coin_code_redemptions.setUser( data.user || null, {
transaction,
});
return coin_code_redemptions;
}
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 coin_code_redemptionsData = data.map((item, index) => ({
id: item.id || undefined,
redeemed_at: item.redeemed_at
||
null
,
amount_doodlecoins: item.amount_doodlecoins
||
null
,
status_message: item.status_message
||
null
,
successful: item.successful
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const coin_code_redemptions = await db.coin_code_redemptions.bulkCreate(coin_code_redemptionsData, { transaction });
// For each item created, replace relation files
return coin_code_redemptions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const coin_code_redemptions = await db.coin_code_redemptions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.redeemed_at !== undefined) updatePayload.redeemed_at = data.redeemed_at;
if (data.amount_doodlecoins !== undefined) updatePayload.amount_doodlecoins = data.amount_doodlecoins;
if (data.status_message !== undefined) updatePayload.status_message = data.status_message;
if (data.successful !== undefined) updatePayload.successful = data.successful;
updatePayload.updatedById = currentUser.id;
await coin_code_redemptions.update(updatePayload, {transaction});
if (data.coin_code !== undefined) {
await coin_code_redemptions.setCoin_code(
data.coin_code,
{ transaction }
);
}
if (data.user !== undefined) {
await coin_code_redemptions.setUser(
data.user,
{ transaction }
);
}
return coin_code_redemptions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const coin_code_redemptions = await db.coin_code_redemptions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of coin_code_redemptions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of coin_code_redemptions) {
await record.destroy({transaction});
}
});
return coin_code_redemptions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const coin_code_redemptions = await db.coin_code_redemptions.findByPk(id, options);
await coin_code_redemptions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await coin_code_redemptions.destroy({
transaction
});
return coin_code_redemptions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const coin_code_redemptions = await db.coin_code_redemptions.findOne(
{ where },
{ transaction },
);
if (!coin_code_redemptions) {
return coin_code_redemptions;
}
const output = coin_code_redemptions.get({plain: true});
output.coin_code = await coin_code_redemptions.getCoin_code({
transaction
});
output.user = await coin_code_redemptions.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.coin_codes,
as: 'coin_code',
where: filter.coin_code ? {
[Op.or]: [
{ id: { [Op.in]: filter.coin_code.split('|').map(term => Utils.uuid(term)) } },
{
code: {
[Op.or]: filter.coin_code.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.status_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'coin_code_redemptions',
'status_message',
filter.status_message,
),
};
}
if (filter.redeemed_atRange) {
const [start, end] = filter.redeemed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
redeemed_at: {
...where.redeemed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
redeemed_at: {
...where.redeemed_at,
[Op.lte]: end,
},
};
}
}
if (filter.amount_doodlecoinsRange) {
const [start, end] = filter.amount_doodlecoinsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount_doodlecoins: {
...where.amount_doodlecoins,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount_doodlecoins: {
...where.amount_doodlecoins,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.successful) {
where = {
...where,
successful: filter.successful,
};
}
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.coin_code_redemptions.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(
'coin_code_redemptions',
'status_message',
query,
),
],
};
}
const records = await db.coin_code_redemptions.findAll({
attributes: [ 'id', 'status_message' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status_message', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status_message,
}));
}
};

View File

@ -0,0 +1,537 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Coin_codesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const coin_codes = await db.coin_codes.create(
{
id: data.id || undefined,
code: data.code
||
null
,
pin: data.pin
||
null
,
amount_doodlecoins: data.amount_doodlecoins
||
null
,
max_redemptions: data.max_redemptions
||
null
,
expires_at: data.expires_at
||
null
,
success_message: data.success_message
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return coin_codes;
}
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 coin_codesData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
pin: item.pin
||
null
,
amount_doodlecoins: item.amount_doodlecoins
||
null
,
max_redemptions: item.max_redemptions
||
null
,
expires_at: item.expires_at
||
null
,
success_message: item.success_message
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const coin_codes = await db.coin_codes.bulkCreate(coin_codesData, { transaction });
// For each item created, replace relation files
return coin_codes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const coin_codes = await db.coin_codes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.pin !== undefined) updatePayload.pin = data.pin;
if (data.amount_doodlecoins !== undefined) updatePayload.amount_doodlecoins = data.amount_doodlecoins;
if (data.max_redemptions !== undefined) updatePayload.max_redemptions = data.max_redemptions;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.success_message !== undefined) updatePayload.success_message = data.success_message;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await coin_codes.update(updatePayload, {transaction});
return coin_codes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const coin_codes = await db.coin_codes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of coin_codes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of coin_codes) {
await record.destroy({transaction});
}
});
return coin_codes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const coin_codes = await db.coin_codes.findByPk(id, options);
await coin_codes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await coin_codes.destroy({
transaction
});
return coin_codes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const coin_codes = await db.coin_codes.findOne(
{ where },
{ transaction },
);
if (!coin_codes) {
return coin_codes;
}
const output = coin_codes.get({plain: true});
output.coin_code_redemptions_coin_code = await coin_codes.getCoin_code_redemptions_coin_code({
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.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'coin_codes',
'code',
filter.code,
),
};
}
if (filter.pin) {
where = {
...where,
[Op.and]: Utils.ilike(
'coin_codes',
'pin',
filter.pin,
),
};
}
if (filter.success_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'coin_codes',
'success_message',
filter.success_message,
),
};
}
if (filter.amount_doodlecoinsRange) {
const [start, end] = filter.amount_doodlecoinsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount_doodlecoins: {
...where.amount_doodlecoins,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount_doodlecoins: {
...where.amount_doodlecoins,
[Op.lte]: end,
},
};
}
}
if (filter.max_redemptionsRange) {
const [start, end] = filter.max_redemptionsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_redemptions: {
...where.max_redemptions,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_redemptions: {
...where.max_redemptions,
[Op.lte]: end,
},
};
}
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
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.coin_codes.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(
'coin_codes',
'code',
query,
),
],
};
}
const records = await db.coin_codes.findAll({
attributes: [ 'id', 'code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.code,
}));
}
};

View File

@ -0,0 +1,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 Coin_conversionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const coin_conversions = await db.coin_conversions.create(
{
id: data.id || undefined,
from_doodlecoins: data.from_doodlecoins
||
null
,
to_supercharged: data.to_supercharged
||
null
,
rate_from: data.rate_from
||
null
,
rate_to: data.rate_to
||
null
,
converted_at: data.converted_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await coin_conversions.setUser( data.user || null, {
transaction,
});
return coin_conversions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const coin_conversionsData = data.map((item, index) => ({
id: item.id || undefined,
from_doodlecoins: item.from_doodlecoins
||
null
,
to_supercharged: item.to_supercharged
||
null
,
rate_from: item.rate_from
||
null
,
rate_to: item.rate_to
||
null
,
converted_at: item.converted_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const coin_conversions = await db.coin_conversions.bulkCreate(coin_conversionsData, { transaction });
// For each item created, replace relation files
return coin_conversions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const coin_conversions = await db.coin_conversions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.from_doodlecoins !== undefined) updatePayload.from_doodlecoins = data.from_doodlecoins;
if (data.to_supercharged !== undefined) updatePayload.to_supercharged = data.to_supercharged;
if (data.rate_from !== undefined) updatePayload.rate_from = data.rate_from;
if (data.rate_to !== undefined) updatePayload.rate_to = data.rate_to;
if (data.converted_at !== undefined) updatePayload.converted_at = data.converted_at;
updatePayload.updatedById = currentUser.id;
await coin_conversions.update(updatePayload, {transaction});
if (data.user !== undefined) {
await coin_conversions.setUser(
data.user,
{ transaction }
);
}
return coin_conversions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const coin_conversions = await db.coin_conversions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of coin_conversions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of coin_conversions) {
await record.destroy({transaction});
}
});
return coin_conversions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const coin_conversions = await db.coin_conversions.findByPk(id, options);
await coin_conversions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await coin_conversions.destroy({
transaction
});
return coin_conversions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const coin_conversions = await db.coin_conversions.findOne(
{ where },
{ transaction },
);
if (!coin_conversions) {
return coin_conversions;
}
const output = coin_conversions.get({plain: true});
output.user = await coin_conversions.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.from_doodlecoinsRange) {
const [start, end] = filter.from_doodlecoinsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
from_doodlecoins: {
...where.from_doodlecoins,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
from_doodlecoins: {
...where.from_doodlecoins,
[Op.lte]: end,
},
};
}
}
if (filter.to_superchargedRange) {
const [start, end] = filter.to_superchargedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
to_supercharged: {
...where.to_supercharged,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
to_supercharged: {
...where.to_supercharged,
[Op.lte]: end,
},
};
}
}
if (filter.rate_fromRange) {
const [start, end] = filter.rate_fromRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rate_from: {
...where.rate_from,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rate_from: {
...where.rate_from,
[Op.lte]: end,
},
};
}
}
if (filter.rate_toRange) {
const [start, end] = filter.rate_toRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rate_to: {
...where.rate_to,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rate_to: {
...where.rate_to,
[Op.lte]: end,
},
};
}
}
if (filter.converted_atRange) {
const [start, end] = filter.converted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
converted_at: {
...where.converted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
converted_at: {
...where.converted_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.coin_conversions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'coin_conversions',
'converted_at',
query,
),
],
};
}
const records = await db.coin_conversions.findAll({
attributes: [ 'id', 'converted_at' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['converted_at', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.converted_at,
}));
}
};

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 Coin_earning_rulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const coin_earning_rules = await db.coin_earning_rules.create(
{
id: data.id || undefined,
name: data.name
||
null
,
source: data.source
||
null
,
active: data.active
||
false
,
base_doodlecoins: data.base_doodlecoins
||
null
,
multiplier: data.multiplier
||
null
,
min_streak_days: data.min_streak_days
||
null
,
max_streak_days: data.max_streak_days
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return coin_earning_rules;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const coin_earning_rulesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
source: item.source
||
null
,
active: item.active
||
false
,
base_doodlecoins: item.base_doodlecoins
||
null
,
multiplier: item.multiplier
||
null
,
min_streak_days: item.min_streak_days
||
null
,
max_streak_days: item.max_streak_days
||
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 coin_earning_rules = await db.coin_earning_rules.bulkCreate(coin_earning_rulesData, { transaction });
// For each item created, replace relation files
return coin_earning_rules;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const coin_earning_rules = await db.coin_earning_rules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.source !== undefined) updatePayload.source = data.source;
if (data.active !== undefined) updatePayload.active = data.active;
if (data.base_doodlecoins !== undefined) updatePayload.base_doodlecoins = data.base_doodlecoins;
if (data.multiplier !== undefined) updatePayload.multiplier = data.multiplier;
if (data.min_streak_days !== undefined) updatePayload.min_streak_days = data.min_streak_days;
if (data.max_streak_days !== undefined) updatePayload.max_streak_days = data.max_streak_days;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await coin_earning_rules.update(updatePayload, {transaction});
return coin_earning_rules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const coin_earning_rules = await db.coin_earning_rules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of coin_earning_rules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of coin_earning_rules) {
await record.destroy({transaction});
}
});
return coin_earning_rules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const coin_earning_rules = await db.coin_earning_rules.findByPk(id, options);
await coin_earning_rules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await coin_earning_rules.destroy({
transaction
});
return coin_earning_rules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const coin_earning_rules = await db.coin_earning_rules.findOne(
{ where },
{ transaction },
);
if (!coin_earning_rules) {
return coin_earning_rules;
}
const output = coin_earning_rules.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(
'coin_earning_rules',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'coin_earning_rules',
'description',
filter.description,
),
};
}
if (filter.base_doodlecoinsRange) {
const [start, end] = filter.base_doodlecoinsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
base_doodlecoins: {
...where.base_doodlecoins,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
base_doodlecoins: {
...where.base_doodlecoins,
[Op.lte]: end,
},
};
}
}
if (filter.multiplierRange) {
const [start, end] = filter.multiplierRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
multiplier: {
...where.multiplier,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
multiplier: {
...where.multiplier,
[Op.lte]: end,
},
};
}
}
if (filter.min_streak_daysRange) {
const [start, end] = filter.min_streak_daysRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_streak_days: {
...where.min_streak_days,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_streak_days: {
...where.min_streak_days,
[Op.lte]: end,
},
};
}
}
if (filter.max_streak_daysRange) {
const [start, end] = filter.max_streak_daysRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_streak_days: {
...where.max_streak_days,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_streak_days: {
...where.max_streak_days,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.source) {
where = {
...where,
source: filter.source,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
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.coin_earning_rules.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'coin_earning_rules',
'name',
query,
),
],
};
}
const records = await db.coin_earning_rules.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,407 @@
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 Comic_contentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const comic_contents = await db.comic_contents.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await comic_contents.setProduct( data.product || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.comic_contents.getTableName(),
belongsToColumn: 'comic_pdf',
belongsToId: comic_contents.id,
},
data.comic_pdf,
options,
);
return comic_contents;
}
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 comic_contentsData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const comic_contents = await db.comic_contents.bulkCreate(comic_contentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < comic_contents.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.comic_contents.getTableName(),
belongsToColumn: 'comic_pdf',
belongsToId: comic_contents[i].id,
},
data[i].comic_pdf,
options,
);
}
return comic_contents;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const comic_contents = await db.comic_contents.findByPk(id, {}, {transaction});
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await comic_contents.update(updatePayload, {transaction});
if (data.product !== undefined) {
await comic_contents.setProduct(
data.product,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.comic_contents.getTableName(),
belongsToColumn: 'comic_pdf',
belongsToId: comic_contents.id,
},
data.comic_pdf,
options,
);
return comic_contents;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const comic_contents = await db.comic_contents.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of comic_contents) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of comic_contents) {
await record.destroy({transaction});
}
});
return comic_contents;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const comic_contents = await db.comic_contents.findByPk(id, options);
await comic_contents.update({
deletedBy: currentUser.id
}, {
transaction,
});
await comic_contents.destroy({
transaction
});
return comic_contents;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const comic_contents = await db.comic_contents.findOne(
{ where },
{ transaction },
);
if (!comic_contents) {
return comic_contents;
}
const output = comic_contents.get({plain: true});
output.product = await comic_contents.getProduct({
transaction
});
output.comic_pdf = await comic_contents.getComic_pdf({
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.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'comic_pdf',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.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.comic_contents.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(
'comic_contents',
'comic_pdf',
query,
),
],
};
}
const records = await db.comic_contents.findAll({
attributes: [ 'id', 'comic_pdf' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['comic_pdf', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.comic_pdf,
}));
}
};

View File

@ -0,0 +1,551 @@
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 Content_consumptionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const content_consumptions = await db.content_consumptions.create(
{
id: data.id || undefined,
action: data.action
||
null
,
started_at: data.started_at
||
null
,
completed_at: data.completed_at
||
null
,
duration_seconds: data.duration_seconds
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await content_consumptions.setUser( data.user || null, {
transaction,
});
await content_consumptions.setProduct( data.product || null, {
transaction,
});
return content_consumptions;
}
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 content_consumptionsData = data.map((item, index) => ({
id: item.id || undefined,
action: item.action
||
null
,
started_at: item.started_at
||
null
,
completed_at: item.completed_at
||
null
,
duration_seconds: item.duration_seconds
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const content_consumptions = await db.content_consumptions.bulkCreate(content_consumptionsData, { transaction });
// For each item created, replace relation files
return content_consumptions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const content_consumptions = await db.content_consumptions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.action !== undefined) updatePayload.action = data.action;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
updatePayload.updatedById = currentUser.id;
await content_consumptions.update(updatePayload, {transaction});
if (data.user !== undefined) {
await content_consumptions.setUser(
data.user,
{ transaction }
);
}
if (data.product !== undefined) {
await content_consumptions.setProduct(
data.product,
{ transaction }
);
}
return content_consumptions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const content_consumptions = await db.content_consumptions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of content_consumptions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of content_consumptions) {
await record.destroy({transaction});
}
});
return content_consumptions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const content_consumptions = await db.content_consumptions.findByPk(id, options);
await content_consumptions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await content_consumptions.destroy({
transaction
});
return content_consumptions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const content_consumptions = await db.content_consumptions.findOne(
{ where },
{ transaction },
);
if (!content_consumptions) {
return content_consumptions;
}
const output = content_consumptions.get({plain: true});
output.user = await content_consumptions.getUser({
transaction
});
output.product = await content_consumptions.getProduct({
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.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
started_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
completed_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.duration_secondsRange) {
const [start, end] = filter.duration_secondsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.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.content_consumptions.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(
'content_consumptions',
'action',
query,
),
],
};
}
const records = await db.content_consumptions.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,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,451 @@
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 Game_contentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const game_contents = await db.game_contents.create(
{
id: data.id || undefined,
launch_type: data.launch_type
||
null
,
redirect_url: data.redirect_url
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await game_contents.setProduct( data.product || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.game_contents.getTableName(),
belongsToColumn: 'html_bundle',
belongsToId: game_contents.id,
},
data.html_bundle,
options,
);
return game_contents;
}
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 game_contentsData = data.map((item, index) => ({
id: item.id || undefined,
launch_type: item.launch_type
||
null
,
redirect_url: item.redirect_url
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const game_contents = await db.game_contents.bulkCreate(game_contentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < game_contents.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.game_contents.getTableName(),
belongsToColumn: 'html_bundle',
belongsToId: game_contents[i].id,
},
data[i].html_bundle,
options,
);
}
return game_contents;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const game_contents = await db.game_contents.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.launch_type !== undefined) updatePayload.launch_type = data.launch_type;
if (data.redirect_url !== undefined) updatePayload.redirect_url = data.redirect_url;
updatePayload.updatedById = currentUser.id;
await game_contents.update(updatePayload, {transaction});
if (data.product !== undefined) {
await game_contents.setProduct(
data.product,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.game_contents.getTableName(),
belongsToColumn: 'html_bundle',
belongsToId: game_contents.id,
},
data.html_bundle,
options,
);
return game_contents;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const game_contents = await db.game_contents.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of game_contents) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of game_contents) {
await record.destroy({transaction});
}
});
return game_contents;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const game_contents = await db.game_contents.findByPk(id, options);
await game_contents.update({
deletedBy: currentUser.id
}, {
transaction,
});
await game_contents.destroy({
transaction
});
return game_contents;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const game_contents = await db.game_contents.findOne(
{ where },
{ transaction },
);
if (!game_contents) {
return game_contents;
}
const output = game_contents.get({plain: true});
output.product = await game_contents.getProduct({
transaction
});
output.html_bundle = await game_contents.getHtml_bundle({
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.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'html_bundle',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.redirect_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'game_contents',
'redirect_url',
filter.redirect_url,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.launch_type) {
where = {
...where,
launch_type: filter.launch_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.game_contents.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(
'game_contents',
'launch_type',
query,
),
],
};
}
const records = await db.game_contents.findAll({
attributes: [ 'id', 'launch_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['launch_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.launch_type,
}));
}
};

View File

@ -0,0 +1,520 @@
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 Item_redemptionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const item_redemptions = await db.item_redemptions.create(
{
id: data.id || undefined,
redeemed_at: data.redeemed_at
||
null
,
cost_doodlecoins: data.cost_doodlecoins
||
null
,
status: data.status
||
null
,
note: data.note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await item_redemptions.setUser( data.user || null, {
transaction,
});
await item_redemptions.setShop_item( data.shop_item || null, {
transaction,
});
return item_redemptions;
}
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 item_redemptionsData = data.map((item, index) => ({
id: item.id || undefined,
redeemed_at: item.redeemed_at
||
null
,
cost_doodlecoins: item.cost_doodlecoins
||
null
,
status: item.status
||
null
,
note: item.note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const item_redemptions = await db.item_redemptions.bulkCreate(item_redemptionsData, { transaction });
// For each item created, replace relation files
return item_redemptions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const item_redemptions = await db.item_redemptions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.redeemed_at !== undefined) updatePayload.redeemed_at = data.redeemed_at;
if (data.cost_doodlecoins !== undefined) updatePayload.cost_doodlecoins = data.cost_doodlecoins;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.note !== undefined) updatePayload.note = data.note;
updatePayload.updatedById = currentUser.id;
await item_redemptions.update(updatePayload, {transaction});
if (data.user !== undefined) {
await item_redemptions.setUser(
data.user,
{ transaction }
);
}
if (data.shop_item !== undefined) {
await item_redemptions.setShop_item(
data.shop_item,
{ transaction }
);
}
return item_redemptions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const item_redemptions = await db.item_redemptions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of item_redemptions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of item_redemptions) {
await record.destroy({transaction});
}
});
return item_redemptions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const item_redemptions = await db.item_redemptions.findByPk(id, options);
await item_redemptions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await item_redemptions.destroy({
transaction
});
return item_redemptions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const item_redemptions = await db.item_redemptions.findOne(
{ where },
{ transaction },
);
if (!item_redemptions) {
return item_redemptions;
}
const output = item_redemptions.get({plain: true});
output.user = await item_redemptions.getUser({
transaction
});
output.shop_item = await item_redemptions.getShop_item({
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.shop_items,
as: 'shop_item',
where: filter.shop_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.shop_item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.shop_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'item_redemptions',
'note',
filter.note,
),
};
}
if (filter.redeemed_atRange) {
const [start, end] = filter.redeemed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
redeemed_at: {
...where.redeemed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
redeemed_at: {
...where.redeemed_at,
[Op.lte]: end,
},
};
}
}
if (filter.cost_doodlecoinsRange) {
const [start, end] = filter.cost_doodlecoinsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cost_doodlecoins: {
...where.cost_doodlecoins,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cost_doodlecoins: {
...where.cost_doodlecoins,
[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.item_redemptions.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(
'item_redemptions',
'status',
query,
),
],
};
}
const records = await db.item_redemptions.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,533 @@
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 Membership_plansDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const membership_plans = await db.membership_plans.create(
{
id: data.id || undefined,
name: data.name
||
null
,
tier: data.tier
||
null
,
monthly_doodlecoins: data.monthly_doodlecoins
||
null
,
doodlecoin_multiplier: data.doodlecoin_multiplier
||
null
,
price_supercharged: data.price_supercharged
||
null
,
perks_summary: data.perks_summary
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return membership_plans;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const membership_plansData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
tier: item.tier
||
null
,
monthly_doodlecoins: item.monthly_doodlecoins
||
null
,
doodlecoin_multiplier: item.doodlecoin_multiplier
||
null
,
price_supercharged: item.price_supercharged
||
null
,
perks_summary: item.perks_summary
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const membership_plans = await db.membership_plans.bulkCreate(membership_plansData, { transaction });
// For each item created, replace relation files
return membership_plans;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const membership_plans = await db.membership_plans.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.tier !== undefined) updatePayload.tier = data.tier;
if (data.monthly_doodlecoins !== undefined) updatePayload.monthly_doodlecoins = data.monthly_doodlecoins;
if (data.doodlecoin_multiplier !== undefined) updatePayload.doodlecoin_multiplier = data.doodlecoin_multiplier;
if (data.price_supercharged !== undefined) updatePayload.price_supercharged = data.price_supercharged;
if (data.perks_summary !== undefined) updatePayload.perks_summary = data.perks_summary;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await membership_plans.update(updatePayload, {transaction});
return membership_plans;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const membership_plans = await db.membership_plans.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of membership_plans) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of membership_plans) {
await record.destroy({transaction});
}
});
return membership_plans;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const membership_plans = await db.membership_plans.findByPk(id, options);
await membership_plans.update({
deletedBy: currentUser.id
}, {
transaction,
});
await membership_plans.destroy({
transaction
});
return membership_plans;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const membership_plans = await db.membership_plans.findOne(
{ where },
{ transaction },
);
if (!membership_plans) {
return membership_plans;
}
const output = membership_plans.get({plain: true});
output.user_memberships_membership_plan = await membership_plans.getUser_memberships_membership_plan({
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(
'membership_plans',
'name',
filter.name,
),
};
}
if (filter.perks_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'membership_plans',
'perks_summary',
filter.perks_summary,
),
};
}
if (filter.monthly_doodlecoinsRange) {
const [start, end] = filter.monthly_doodlecoinsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
monthly_doodlecoins: {
...where.monthly_doodlecoins,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
monthly_doodlecoins: {
...where.monthly_doodlecoins,
[Op.lte]: end,
},
};
}
}
if (filter.doodlecoin_multiplierRange) {
const [start, end] = filter.doodlecoin_multiplierRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
doodlecoin_multiplier: {
...where.doodlecoin_multiplier,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
doodlecoin_multiplier: {
...where.doodlecoin_multiplier,
[Op.lte]: end,
},
};
}
}
if (filter.price_superchargedRange) {
const [start, end] = filter.price_superchargedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_supercharged: {
...where.price_supercharged,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_supercharged: {
...where.price_supercharged,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.tier) {
where = {
...where,
tier: filter.tier,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
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.membership_plans.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'membership_plans',
'name',
query,
),
],
};
}
const records = await db.membership_plans.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,352 @@
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,557 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Product_purchasesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const product_purchases = await db.product_purchases.create(
{
id: data.id || undefined,
purchased_at: data.purchased_at
||
null
,
price_supercharged: data.price_supercharged
||
null
,
access_status: data.access_status
||
null
,
access_expires_at: data.access_expires_at
||
null
,
note: data.note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await product_purchases.setUser( data.user || null, {
transaction,
});
await product_purchases.setProduct( data.product || null, {
transaction,
});
return product_purchases;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const product_purchasesData = data.map((item, index) => ({
id: item.id || undefined,
purchased_at: item.purchased_at
||
null
,
price_supercharged: item.price_supercharged
||
null
,
access_status: item.access_status
||
null
,
access_expires_at: item.access_expires_at
||
null
,
note: item.note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const product_purchases = await db.product_purchases.bulkCreate(product_purchasesData, { transaction });
// For each item created, replace relation files
return product_purchases;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const product_purchases = await db.product_purchases.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.purchased_at !== undefined) updatePayload.purchased_at = data.purchased_at;
if (data.price_supercharged !== undefined) updatePayload.price_supercharged = data.price_supercharged;
if (data.access_status !== undefined) updatePayload.access_status = data.access_status;
if (data.access_expires_at !== undefined) updatePayload.access_expires_at = data.access_expires_at;
if (data.note !== undefined) updatePayload.note = data.note;
updatePayload.updatedById = currentUser.id;
await product_purchases.update(updatePayload, {transaction});
if (data.user !== undefined) {
await product_purchases.setUser(
data.user,
{ transaction }
);
}
if (data.product !== undefined) {
await product_purchases.setProduct(
data.product,
{ transaction }
);
}
return product_purchases;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const product_purchases = await db.product_purchases.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of product_purchases) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of product_purchases) {
await record.destroy({transaction});
}
});
return product_purchases;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const product_purchases = await db.product_purchases.findByPk(id, options);
await product_purchases.update({
deletedBy: currentUser.id
}, {
transaction,
});
await product_purchases.destroy({
transaction
});
return product_purchases;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const product_purchases = await db.product_purchases.findOne(
{ where },
{ transaction },
);
if (!product_purchases) {
return product_purchases;
}
const output = product_purchases.get({plain: true});
output.user = await product_purchases.getUser({
transaction
});
output.product = await product_purchases.getProduct({
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.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'product_purchases',
'note',
filter.note,
),
};
}
if (filter.purchased_atRange) {
const [start, end] = filter.purchased_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
purchased_at: {
...where.purchased_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
purchased_at: {
...where.purchased_at,
[Op.lte]: end,
},
};
}
}
if (filter.price_superchargedRange) {
const [start, end] = filter.price_superchargedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_supercharged: {
...where.price_supercharged,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_supercharged: {
...where.price_supercharged,
[Op.lte]: end,
},
};
}
}
if (filter.access_expires_atRange) {
const [start, end] = filter.access_expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
access_expires_at: {
...where.access_expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
access_expires_at: {
...where.access_expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.access_status) {
where = {
...where,
access_status: filter.access_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.product_purchases.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(
'product_purchases',
'access_status',
query,
),
],
};
}
const records = await db.product_purchases.findAll({
attributes: [ 'id', 'access_status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['access_status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.access_status,
}));
}
};

View File

@ -0,0 +1,667 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ProductsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const products = await db.products.create(
{
id: data.id || undefined,
product_type: data.product_type
||
null
,
name: data.name
||
null
,
description: data.description
||
null
,
price_supercharged: data.price_supercharged
||
null
,
expires_at: data.expires_at
||
null
,
max_purchases: data.max_purchases
||
null
,
status: data.status
||
null
,
published_at: data.published_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await products.setCreated_by_user( data.created_by_user || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'thumbnail_image',
belongsToId: products.id,
},
data.thumbnail_image,
options,
);
return products;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const productsData = data.map((item, index) => ({
id: item.id || undefined,
product_type: item.product_type
||
null
,
name: item.name
||
null
,
description: item.description
||
null
,
price_supercharged: item.price_supercharged
||
null
,
expires_at: item.expires_at
||
null
,
max_purchases: item.max_purchases
||
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 products = await db.products.bulkCreate(productsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < products.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'thumbnail_image',
belongsToId: products[i].id,
},
data[i].thumbnail_image,
options,
);
}
return products;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.product_type !== undefined) updatePayload.product_type = data.product_type;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.price_supercharged !== undefined) updatePayload.price_supercharged = data.price_supercharged;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.max_purchases !== undefined) updatePayload.max_purchases = data.max_purchases;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
updatePayload.updatedById = currentUser.id;
await products.update(updatePayload, {transaction});
if (data.created_by_user !== undefined) {
await products.setCreated_by_user(
data.created_by_user,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.products.getTableName(),
belongsToColumn: 'thumbnail_image',
belongsToId: products.id,
},
data.thumbnail_image,
options,
);
return products;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of products) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of products) {
await record.destroy({transaction});
}
});
return products;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findByPk(id, options);
await products.update({
deletedBy: currentUser.id
}, {
transaction,
});
await products.destroy({
transaction
});
return products;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const products = await db.products.findOne(
{ where },
{ transaction },
);
if (!products) {
return products;
}
const output = products.get({plain: true});
output.article_contents_product = await products.getArticle_contents_product({
transaction
});
output.comic_contents_product = await products.getComic_contents_product({
transaction
});
output.video_contents_product = await products.getVideo_contents_product({
transaction
});
output.game_contents_product = await products.getGame_contents_product({
transaction
});
output.product_purchases_product = await products.getProduct_purchases_product({
transaction
});
output.content_consumptions_product = await products.getContent_consumptions_product({
transaction
});
output.thumbnail_image = await products.getThumbnail_image({
transaction
});
output.created_by_user = await products.getCreated_by_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: 'created_by_user',
where: filter.created_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'thumbnail_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'products',
'description',
filter.description,
),
};
}
if (filter.price_superchargedRange) {
const [start, end] = filter.price_superchargedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_supercharged: {
...where.price_supercharged,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_supercharged: {
...where.price_supercharged,
[Op.lte]: end,
},
};
}
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.max_purchasesRange) {
const [start, end] = filter.max_purchasesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_purchases: {
...where.max_purchases,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_purchases: {
...where.max_purchases,
[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.product_type) {
where = {
...where,
product_type: filter.product_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.products.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'products',
'name',
query,
),
],
};
}
const records = await db.products.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,642 @@
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 ReferralsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referrals = await db.referrals.create(
{
id: data.id || undefined,
referral_code: data.referral_code
||
null
,
referred_email: data.referred_email
||
null
,
status: data.status
||
null
,
invited_at: data.invited_at
||
null
,
signed_up_at: data.signed_up_at
||
null
,
rewarded_at: data.rewarded_at
||
null
,
reward_doodlecoins: data.reward_doodlecoins
||
null
,
note: data.note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await referrals.setReferrer( data.referrer || null, {
transaction,
});
await referrals.setReferred_user( data.referred_user || null, {
transaction,
});
return referrals;
}
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 referralsData = data.map((item, index) => ({
id: item.id || undefined,
referral_code: item.referral_code
||
null
,
referred_email: item.referred_email
||
null
,
status: item.status
||
null
,
invited_at: item.invited_at
||
null
,
signed_up_at: item.signed_up_at
||
null
,
rewarded_at: item.rewarded_at
||
null
,
reward_doodlecoins: item.reward_doodlecoins
||
null
,
note: item.note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const referrals = await db.referrals.bulkCreate(referralsData, { transaction });
// For each item created, replace relation files
return referrals;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const referrals = await db.referrals.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.referral_code !== undefined) updatePayload.referral_code = data.referral_code;
if (data.referred_email !== undefined) updatePayload.referred_email = data.referred_email;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.invited_at !== undefined) updatePayload.invited_at = data.invited_at;
if (data.signed_up_at !== undefined) updatePayload.signed_up_at = data.signed_up_at;
if (data.rewarded_at !== undefined) updatePayload.rewarded_at = data.rewarded_at;
if (data.reward_doodlecoins !== undefined) updatePayload.reward_doodlecoins = data.reward_doodlecoins;
if (data.note !== undefined) updatePayload.note = data.note;
updatePayload.updatedById = currentUser.id;
await referrals.update(updatePayload, {transaction});
if (data.referrer !== undefined) {
await referrals.setReferrer(
data.referrer,
{ transaction }
);
}
if (data.referred_user !== undefined) {
await referrals.setReferred_user(
data.referred_user,
{ transaction }
);
}
return referrals;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const referrals = await db.referrals.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of referrals) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of referrals) {
await record.destroy({transaction});
}
});
return referrals;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const referrals = await db.referrals.findByPk(id, options);
await referrals.update({
deletedBy: currentUser.id
}, {
transaction,
});
await referrals.destroy({
transaction
});
return referrals;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const referrals = await db.referrals.findOne(
{ where },
{ transaction },
);
if (!referrals) {
return referrals;
}
const output = referrals.get({plain: true});
output.referrer = await referrals.getReferrer({
transaction
});
output.referred_user = await referrals.getReferred_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: 'referrer',
where: filter.referrer ? {
[Op.or]: [
{ id: { [Op.in]: filter.referrer.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.referrer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'referred_user',
where: filter.referred_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.referred_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.referred_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.referral_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'referrals',
'referral_code',
filter.referral_code,
),
};
}
if (filter.referred_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'referrals',
'referred_email',
filter.referred_email,
),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'referrals',
'note',
filter.note,
),
};
}
if (filter.invited_atRange) {
const [start, end] = filter.invited_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
invited_at: {
...where.invited_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
invited_at: {
...where.invited_at,
[Op.lte]: end,
},
};
}
}
if (filter.signed_up_atRange) {
const [start, end] = filter.signed_up_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
signed_up_at: {
...where.signed_up_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
signed_up_at: {
...where.signed_up_at,
[Op.lte]: end,
},
};
}
}
if (filter.rewarded_atRange) {
const [start, end] = filter.rewarded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rewarded_at: {
...where.rewarded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rewarded_at: {
...where.rewarded_at,
[Op.lte]: end,
},
};
}
}
if (filter.reward_doodlecoinsRange) {
const [start, end] = filter.reward_doodlecoinsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reward_doodlecoins: {
...where.reward_doodlecoins,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reward_doodlecoins: {
...where.reward_doodlecoins,
[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.referrals.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(
'referrals',
'referral_code',
query,
),
],
};
}
const records = await db.referrals.findAll({
attributes: [ 'id', 'referral_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['referral_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.referral_code,
}));
}
};

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

@ -0,0 +1,422 @@
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,481 @@
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 Shop_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shop_items = await db.shop_items.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
cost_doodlecoins: data.cost_doodlecoins
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.shop_items.getTableName(),
belongsToColumn: 'thumbnail_image',
belongsToId: shop_items.id,
},
data.thumbnail_image,
options,
);
return shop_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const shop_itemsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
cost_doodlecoins: item.cost_doodlecoins
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const shop_items = await db.shop_items.bulkCreate(shop_itemsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < shop_items.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.shop_items.getTableName(),
belongsToColumn: 'thumbnail_image',
belongsToId: shop_items[i].id,
},
data[i].thumbnail_image,
options,
);
}
return shop_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const shop_items = await db.shop_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.cost_doodlecoins !== undefined) updatePayload.cost_doodlecoins = data.cost_doodlecoins;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await shop_items.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.shop_items.getTableName(),
belongsToColumn: 'thumbnail_image',
belongsToId: shop_items.id,
},
data.thumbnail_image,
options,
);
return shop_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shop_items = await db.shop_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of shop_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of shop_items) {
await record.destroy({transaction});
}
});
return shop_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const shop_items = await db.shop_items.findByPk(id, options);
await shop_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await shop_items.destroy({
transaction
});
return shop_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const shop_items = await db.shop_items.findOne(
{ where },
{ transaction },
);
if (!shop_items) {
return shop_items;
}
const output = shop_items.get({plain: true});
output.item_redemptions_shop_item = await shop_items.getItem_redemptions_shop_item({
transaction
});
output.thumbnail_image = await shop_items.getThumbnail_image({
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.file,
as: 'thumbnail_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'shop_items',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'shop_items',
'description',
filter.description,
),
};
}
if (filter.cost_doodlecoinsRange) {
const [start, end] = filter.cost_doodlecoinsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cost_doodlecoins: {
...where.cost_doodlecoins,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cost_doodlecoins: {
...where.cost_doodlecoins,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
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.shop_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'shop_items',
'name',
query,
),
],
};
}
const records = await db.shop_items.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,649 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class User_membershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_memberships = await db.user_memberships.create(
{
id: data.id || undefined,
status: data.status
||
null
,
started_at: data.started_at
||
null
,
next_billing_at: data.next_billing_at
||
null
,
cancelled_at: data.cancelled_at
||
null
,
ends_at: data.ends_at
||
null
,
price_supercharged: data.price_supercharged
||
null
,
perks_snapshot: data.perks_snapshot
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await user_memberships.setUser( data.user || null, {
transaction,
});
await user_memberships.setMembership_plan( data.membership_plan || null, {
transaction,
});
return user_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 user_membershipsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
started_at: item.started_at
||
null
,
next_billing_at: item.next_billing_at
||
null
,
cancelled_at: item.cancelled_at
||
null
,
ends_at: item.ends_at
||
null
,
price_supercharged: item.price_supercharged
||
null
,
perks_snapshot: item.perks_snapshot
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const user_memberships = await db.user_memberships.bulkCreate(user_membershipsData, { transaction });
// For each item created, replace relation files
return user_memberships;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_memberships = await db.user_memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.next_billing_at !== undefined) updatePayload.next_billing_at = data.next_billing_at;
if (data.cancelled_at !== undefined) updatePayload.cancelled_at = data.cancelled_at;
if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at;
if (data.price_supercharged !== undefined) updatePayload.price_supercharged = data.price_supercharged;
if (data.perks_snapshot !== undefined) updatePayload.perks_snapshot = data.perks_snapshot;
updatePayload.updatedById = currentUser.id;
await user_memberships.update(updatePayload, {transaction});
if (data.user !== undefined) {
await user_memberships.setUser(
data.user,
{ transaction }
);
}
if (data.membership_plan !== undefined) {
await user_memberships.setMembership_plan(
data.membership_plan,
{ transaction }
);
}
return user_memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_memberships = await db.user_memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_memberships) {
await record.destroy({transaction});
}
});
return user_memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_memberships = await db.user_memberships.findByPk(id, options);
await user_memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_memberships.destroy({
transaction
});
return user_memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_memberships = await db.user_memberships.findOne(
{ where },
{ transaction },
);
if (!user_memberships) {
return user_memberships;
}
const output = user_memberships.get({plain: true});
output.user = await user_memberships.getUser({
transaction
});
output.membership_plan = await user_memberships.getMembership_plan({
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.membership_plans,
as: 'membership_plan',
where: filter.membership_plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.membership_plan.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.membership_plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.perks_snapshot) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_memberships',
'perks_snapshot',
filter.perks_snapshot,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
started_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ends_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.next_billing_atRange) {
const [start, end] = filter.next_billing_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
next_billing_at: {
...where.next_billing_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
next_billing_at: {
...where.next_billing_at,
[Op.lte]: end,
},
};
}
}
if (filter.cancelled_atRange) {
const [start, end] = filter.cancelled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cancelled_at: {
...where.cancelled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cancelled_at: {
...where.cancelled_at,
[Op.lte]: end,
},
};
}
}
if (filter.ends_atRange) {
const [start, end] = filter.ends_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ends_at: {
...where.ends_at,
[Op.lte]: end,
},
};
}
}
if (filter.price_superchargedRange) {
const [start, end] = filter.price_superchargedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_supercharged: {
...where.price_supercharged,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_supercharged: {
...where.price_supercharged,
[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.user_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(
'user_memberships',
'status',
query,
),
],
};
}
const records = await db.user_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,570 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class User_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_sessions = await db.user_sessions.create(
{
id: data.id || undefined,
session_token: data.session_token
||
null
,
signed_in_at: data.signed_in_at
||
null
,
expires_at: data.expires_at
||
null
,
signed_out_at: data.signed_out_at
||
null
,
ip_address: data.ip_address
||
null
,
user_agent: data.user_agent
||
null
,
remember_me: data.remember_me
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await user_sessions.setUser( data.user || null, {
transaction,
});
return user_sessions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const user_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
session_token: item.session_token
||
null
,
signed_in_at: item.signed_in_at
||
null
,
expires_at: item.expires_at
||
null
,
signed_out_at: item.signed_out_at
||
null
,
ip_address: item.ip_address
||
null
,
user_agent: item.user_agent
||
null
,
remember_me: item.remember_me
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const user_sessions = await db.user_sessions.bulkCreate(user_sessionsData, { transaction });
// For each item created, replace relation files
return user_sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_sessions = await db.user_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.session_token !== undefined) updatePayload.session_token = data.session_token;
if (data.signed_in_at !== undefined) updatePayload.signed_in_at = data.signed_in_at;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.signed_out_at !== undefined) updatePayload.signed_out_at = data.signed_out_at;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
if (data.remember_me !== undefined) updatePayload.remember_me = data.remember_me;
updatePayload.updatedById = currentUser.id;
await user_sessions.update(updatePayload, {transaction});
if (data.user !== undefined) {
await user_sessions.setUser(
data.user,
{ transaction }
);
}
return user_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_sessions = await db.user_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_sessions) {
await record.destroy({transaction});
}
});
return user_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_sessions = await db.user_sessions.findByPk(id, options);
await user_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_sessions.destroy({
transaction
});
return user_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_sessions = await db.user_sessions.findOne(
{ where },
{ transaction },
);
if (!user_sessions) {
return user_sessions;
}
const output = user_sessions.get({plain: true});
output.user = await user_sessions.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.session_token) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_sessions',
'session_token',
filter.session_token,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_sessions',
'ip_address',
filter.ip_address,
),
};
}
if (filter.user_agent) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_sessions',
'user_agent',
filter.user_agent,
),
};
}
if (filter.signed_in_atRange) {
const [start, end] = filter.signed_in_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
signed_in_at: {
...where.signed_in_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
signed_in_at: {
...where.signed_in_at,
[Op.lte]: end,
},
};
}
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.signed_out_atRange) {
const [start, end] = filter.signed_out_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
signed_out_at: {
...where.signed_out_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
signed_out_at: {
...where.signed_out_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.remember_me) {
where = {
...where,
remember_me: filter.remember_me,
};
}
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_sessions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'user_sessions',
'session_token',
query,
),
],
};
}
const records = await db.user_sessions.findAll({
attributes: [ 'id', 'session_token' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['session_token', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.session_token,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,431 @@
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 Video_contentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const video_contents = await db.video_contents.create(
{
id: data.id || undefined,
video_caption: data.video_caption
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await video_contents.setProduct( data.product || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.video_contents.getTableName(),
belongsToColumn: 'video_file',
belongsToId: video_contents.id,
},
data.video_file,
options,
);
return video_contents;
}
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 video_contentsData = data.map((item, index) => ({
id: item.id || undefined,
video_caption: item.video_caption
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const video_contents = await db.video_contents.bulkCreate(video_contentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < video_contents.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.video_contents.getTableName(),
belongsToColumn: 'video_file',
belongsToId: video_contents[i].id,
},
data[i].video_file,
options,
);
}
return video_contents;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const video_contents = await db.video_contents.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.video_caption !== undefined) updatePayload.video_caption = data.video_caption;
updatePayload.updatedById = currentUser.id;
await video_contents.update(updatePayload, {transaction});
if (data.product !== undefined) {
await video_contents.setProduct(
data.product,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.video_contents.getTableName(),
belongsToColumn: 'video_file',
belongsToId: video_contents.id,
},
data.video_file,
options,
);
return video_contents;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const video_contents = await db.video_contents.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of video_contents) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of video_contents) {
await record.destroy({transaction});
}
});
return video_contents;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const video_contents = await db.video_contents.findByPk(id, options);
await video_contents.update({
deletedBy: currentUser.id
}, {
transaction,
});
await video_contents.destroy({
transaction
});
return video_contents;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const video_contents = await db.video_contents.findOne(
{ where },
{ transaction },
);
if (!video_contents) {
return video_contents;
}
const output = video_contents.get({plain: true});
output.product = await video_contents.getProduct({
transaction
});
output.video_file = await video_contents.getVideo_file({
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.products,
as: 'product',
where: filter.product ? {
[Op.or]: [
{ id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'video_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.video_caption) {
where = {
...where,
[Op.and]: Utils.ilike(
'video_contents',
'video_caption',
filter.video_caption,
),
};
}
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.video_contents.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(
'video_contents',
'video_caption',
query,
),
],
};
}
const records = await db.video_contents.findAll({
attributes: [ 'id', 'video_caption' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['video_caption', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.video_caption,
}));
}
};

View File

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

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -0,0 +1,172 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const admin_audit_logs = sequelize.define(
'admin_audit_logs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
action: {
type: DataTypes.ENUM,
values: [
"USER_UPDATE",
"USER_DELETE",
"COIN_ADJUST",
"PRODUCT_CREATE",
"PRODUCT_UPDATE",
"PRODUCT_DELETE",
"CODE_CREATE",
"CODE_UPDATE",
"CODE_DELETE",
"ITEM_CREATE",
"ITEM_UPDATE",
"ITEM_DELETE",
"MEMBERSHIP_PLAN_UPDATE",
"OTHER"
],
},
entity_name: {
type: DataTypes.TEXT,
},
entity_reference: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
details: {
type: DataTypes.TEXT,
},
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,115 @@
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 app_settings = sequelize.define(
'app_settings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
key: {
type: DataTypes.TEXT,
},
value: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
public: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
app_settings.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.app_settings.belongsTo(db.users, {
as: 'createdBy',
});
db.app_settings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return app_settings;
};

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 article_contents = sequelize.define(
'article_contents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
body: {
type: DataTypes.TEXT,
},
excerpt: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
article_contents.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.article_contents.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.article_contents.belongsTo(db.users, {
as: 'createdBy',
});
db.article_contents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return article_contents;
};

View File

@ -0,0 +1,143 @@
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 chat_memberships = sequelize.define(
'chat_memberships',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
member_role: {
type: DataTypes.ENUM,
values: [
"OWNER",
"MODERATOR",
"MEMBER"
],
},
joined_at: {
type: DataTypes.DATE,
},
left_at: {
type: DataTypes.DATE,
},
muted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
chat_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.chat_memberships.belongsTo(db.chat_rooms, {
as: 'chat_room',
foreignKey: {
name: 'chat_roomId',
},
constraints: false,
});
db.chat_memberships.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.chat_memberships.belongsTo(db.users, {
as: 'createdBy',
});
db.chat_memberships.belongsTo(db.users, {
as: 'updatedBy',
});
};
return chat_memberships;
};

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 chat_messages = sequelize.define(
'chat_messages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
message_text: {
type: DataTypes.TEXT,
},
sent_at: {
type: DataTypes.DATE,
},
edited_at: {
type: DataTypes.DATE,
},
deleted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
chat_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.chat_messages.belongsTo(db.chat_rooms, {
as: 'chat_room',
foreignKey: {
name: 'chat_roomId',
},
constraints: false,
});
db.chat_messages.belongsTo(db.users, {
as: 'sender',
foreignKey: {
name: 'senderId',
},
constraints: false,
});
db.chat_messages.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.chat_messages.getTableName(),
belongsToColumn: 'attachments',
},
});
db.chat_messages.belongsTo(db.users, {
as: 'createdBy',
});
db.chat_messages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return chat_messages;
};

View File

@ -0,0 +1,158 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const chat_rooms = sequelize.define(
'chat_rooms',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
room_type: {
type: DataTypes.ENUM,
values: [
"PUBLIC",
"DIRECT",
"GROUP"
],
},
name: {
type: DataTypes.TEXT,
},
private_room: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
created_at_time: {
type: DataTypes.DATE,
},
last_message_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
chat_rooms.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.chat_rooms.hasMany(db.chat_memberships, {
as: 'chat_memberships_chat_room',
foreignKey: {
name: 'chat_roomId',
},
constraints: false,
});
db.chat_rooms.hasMany(db.chat_messages, {
as: 'chat_messages_chat_room',
foreignKey: {
name: 'chat_roomId',
},
constraints: false,
});
//end loop
db.chat_rooms.belongsTo(db.users, {
as: 'created_by_user',
foreignKey: {
name: 'created_by_userId',
},
constraints: false,
});
db.chat_rooms.belongsTo(db.users, {
as: 'createdBy',
});
db.chat_rooms.belongsTo(db.users, {
as: 'updatedBy',
});
};
return chat_rooms;
};

View File

@ -0,0 +1,131 @@
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 coin_code_redemptions = sequelize.define(
'coin_code_redemptions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
redeemed_at: {
type: DataTypes.DATE,
},
amount_doodlecoins: {
type: DataTypes.INTEGER,
},
status_message: {
type: DataTypes.TEXT,
},
successful: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
coin_code_redemptions.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.coin_code_redemptions.belongsTo(db.coin_codes, {
as: 'coin_code',
foreignKey: {
name: 'coin_codeId',
},
constraints: false,
});
db.coin_code_redemptions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.coin_code_redemptions.belongsTo(db.users, {
as: 'createdBy',
});
db.coin_code_redemptions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return coin_code_redemptions;
};

View File

@ -0,0 +1,144 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const coin_codes = sequelize.define(
'coin_codes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
pin: {
type: DataTypes.TEXT,
},
amount_doodlecoins: {
type: DataTypes.INTEGER,
},
max_redemptions: {
type: DataTypes.INTEGER,
},
expires_at: {
type: DataTypes.DATE,
},
success_message: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
coin_codes.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.coin_codes.hasMany(db.coin_code_redemptions, {
as: 'coin_code_redemptions_coin_code',
foreignKey: {
name: 'coin_codeId',
},
constraints: false,
});
//end loop
db.coin_codes.belongsTo(db.users, {
as: 'createdBy',
});
db.coin_codes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return coin_codes;
};

View File

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

View File

@ -0,0 +1,161 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const coin_earning_rules = sequelize.define(
'coin_earning_rules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
source: {
type: DataTypes.ENUM,
values: [
"STREAK",
"REFERRAL",
"PRODUCT_BONUS",
"ADMIN_ADJUSTMENT",
"OTHER"
],
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
base_doodlecoins: {
type: DataTypes.INTEGER,
},
multiplier: {
type: DataTypes.DECIMAL,
},
min_streak_days: {
type: DataTypes.INTEGER,
},
max_streak_days: {
type: DataTypes.INTEGER,
},
description: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
coin_earning_rules.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.coin_earning_rules.belongsTo(db.users, {
as: 'createdBy',
});
db.coin_earning_rules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return coin_earning_rules;
};

View File

@ -0,0 +1,102 @@
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 comic_contents = sequelize.define(
'comic_contents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
comic_contents.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.comic_contents.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.comic_contents.hasMany(db.file, {
as: 'comic_pdf',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.comic_contents.getTableName(),
belongsToColumn: 'comic_pdf',
},
});
db.comic_contents.belongsTo(db.users, {
as: 'createdBy',
});
db.comic_contents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return comic_contents;
};

View File

@ -0,0 +1,143 @@
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 content_consumptions = sequelize.define(
'content_consumptions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
action: {
type: DataTypes.ENUM,
values: [
"VIEW",
"READ",
"WATCH",
"PLAY"
],
},
started_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
duration_seconds: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
content_consumptions.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.content_consumptions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.content_consumptions.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.content_consumptions.belongsTo(db.users, {
as: 'createdBy',
});
db.content_consumptions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return content_consumptions;
};

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,125 @@
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 game_contents = sequelize.define(
'game_contents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
launch_type: {
type: DataTypes.ENUM,
values: [
"UPLOAD_HTML",
"REDIRECT_URL"
],
},
redirect_url: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
game_contents.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.game_contents.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.game_contents.hasMany(db.file, {
as: 'html_bundle',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.game_contents.getTableName(),
belongsToColumn: 'html_bundle',
},
});
db.game_contents.belongsTo(db.users, {
as: 'createdBy',
});
db.game_contents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return game_contents;
};

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,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 item_redemptions = sequelize.define(
'item_redemptions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
redeemed_at: {
type: DataTypes.DATE,
},
cost_doodlecoins: {
type: DataTypes.INTEGER,
},
status: {
type: DataTypes.ENUM,
values: [
"REQUESTED",
"APPROVED",
"FULFILLED",
"REJECTED",
"CANCELLED"
],
},
note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
item_redemptions.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.item_redemptions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.item_redemptions.belongsTo(db.shop_items, {
as: 'shop_item',
foreignKey: {
name: 'shop_itemId',
},
constraints: false,
});
db.item_redemptions.belongsTo(db.users, {
as: 'createdBy',
});
db.item_redemptions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return item_redemptions;
};

View File

@ -0,0 +1,159 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const membership_plans = sequelize.define(
'membership_plans',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
tier: {
type: DataTypes.ENUM,
values: [
"FREE",
"SILVER",
"GOLD",
"PREMIUM"
],
},
monthly_doodlecoins: {
type: DataTypes.INTEGER,
},
doodlecoin_multiplier: {
type: DataTypes.DECIMAL,
},
price_supercharged: {
type: DataTypes.INTEGER,
},
perks_summary: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
membership_plans.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.membership_plans.hasMany(db.user_memberships, {
as: 'user_memberships_membership_plan',
foreignKey: {
name: 'membership_planId',
},
constraints: false,
});
//end loop
db.membership_plans.belongsTo(db.users, {
as: 'createdBy',
});
db.membership_plans.belongsTo(db.users, {
as: 'updatedBy',
});
};
return membership_plans;
};

View File

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

View File

@ -0,0 +1,147 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const product_purchases = sequelize.define(
'product_purchases',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
purchased_at: {
type: DataTypes.DATE,
},
price_supercharged: {
type: DataTypes.INTEGER,
},
access_status: {
type: DataTypes.ENUM,
values: [
"ACTIVE",
"EXPIRED",
"REVOKED"
],
},
access_expires_at: {
type: DataTypes.DATE,
},
note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
product_purchases.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.product_purchases.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.product_purchases.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.product_purchases.belongsTo(db.users, {
as: 'createdBy',
});
db.product_purchases.belongsTo(db.users, {
as: 'updatedBy',
});
};
return product_purchases;
};

View File

@ -0,0 +1,233 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const products = sequelize.define(
'products',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
product_type: {
type: DataTypes.ENUM,
values: [
"ARTICLE",
"COMIC",
"VIDEO",
"GAME"
],
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
price_supercharged: {
type: DataTypes.INTEGER,
},
expires_at: {
type: DataTypes.DATE,
},
max_purchases: {
type: DataTypes.INTEGER,
},
status: {
type: DataTypes.ENUM,
values: [
"DRAFT",
"PUBLISHED",
"ARCHIVED"
],
},
published_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
products.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.products.hasMany(db.article_contents, {
as: 'article_contents_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.comic_contents, {
as: 'comic_contents_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.video_contents, {
as: 'video_contents_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.game_contents, {
as: 'game_contents_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.product_purchases, {
as: 'product_purchases_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.products.hasMany(db.content_consumptions, {
as: 'content_consumptions_product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
//end loop
db.products.belongsTo(db.users, {
as: 'created_by_user',
foreignKey: {
name: 'created_by_userId',
},
constraints: false,
});
db.products.hasMany(db.file, {
as: 'thumbnail_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.products.getTableName(),
belongsToColumn: 'thumbnail_image',
},
});
db.products.belongsTo(db.users, {
as: 'createdBy',
});
db.products.belongsTo(db.users, {
as: 'updatedBy',
});
};
return products;
};

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 referrals = sequelize.define(
'referrals',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
referral_code: {
type: DataTypes.TEXT,
},
referred_email: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"INVITED",
"SIGNED_UP",
"REWARDED",
"CANCELLED"
],
},
invited_at: {
type: DataTypes.DATE,
},
signed_up_at: {
type: DataTypes.DATE,
},
rewarded_at: {
type: DataTypes.DATE,
},
reward_doodlecoins: {
type: DataTypes.INTEGER,
},
note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
referrals.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.referrals.belongsTo(db.users, {
as: 'referrer',
foreignKey: {
name: 'referrerId',
},
constraints: false,
});
db.referrals.belongsTo(db.users, {
as: 'referred_user',
foreignKey: {
name: 'referred_userId',
},
constraints: false,
});
db.referrals.belongsTo(db.users, {
as: 'createdBy',
});
db.referrals.belongsTo(db.users, {
as: 'updatedBy',
});
};
return referrals;
};

View File

@ -0,0 +1,124 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const 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,133 @@
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 shop_items = sequelize.define(
'shop_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
cost_doodlecoins: {
type: DataTypes.INTEGER,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
shop_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.shop_items.hasMany(db.item_redemptions, {
as: 'item_redemptions_shop_item',
foreignKey: {
name: 'shop_itemId',
},
constraints: false,
});
//end loop
db.shop_items.hasMany(db.file, {
as: 'thumbnail_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.shop_items.getTableName(),
belongsToColumn: 'thumbnail_image',
},
});
db.shop_items.belongsTo(db.users, {
as: 'createdBy',
});
db.shop_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return shop_items;
};

View File

@ -0,0 +1,161 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const user_memberships = sequelize.define(
'user_memberships',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"ACTIVE",
"CANCELLED",
"EXPIRED"
],
},
started_at: {
type: DataTypes.DATE,
},
next_billing_at: {
type: DataTypes.DATE,
},
cancelled_at: {
type: DataTypes.DATE,
},
ends_at: {
type: DataTypes.DATE,
},
price_supercharged: {
type: DataTypes.INTEGER,
},
perks_snapshot: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
user_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.user_memberships.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.user_memberships.belongsTo(db.membership_plans, {
as: 'membership_plan',
foreignKey: {
name: 'membership_planId',
},
constraints: false,
});
db.user_memberships.belongsTo(db.users, {
as: 'createdBy',
});
db.user_memberships.belongsTo(db.users, {
as: 'updatedBy',
});
};
return user_memberships;
};

View File

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

View File

@ -0,0 +1,369 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const users = sequelize.define(
'users',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
firstName: {
type: DataTypes.TEXT,
},
lastName: {
type: DataTypes.TEXT,
},
phoneNumber: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
disabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
password: {
type: DataTypes.TEXT,
},
emailVerified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
emailVerificationToken: {
type: DataTypes.TEXT,
},
emailVerificationTokenExpiresAt: {
type: DataTypes.DATE,
},
passwordResetToken: {
type: DataTypes.TEXT,
},
passwordResetTokenExpiresAt: {
type: DataTypes.DATE,
},
provider: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
users.associate = (db) => {
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions_filter',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.users.hasMany(db.user_sessions, {
as: 'user_sessions_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.referrals, {
as: 'referrals_referrer',
foreignKey: {
name: 'referrerId',
},
constraints: false,
});
db.users.hasMany(db.referrals, {
as: 'referrals_referred_user',
foreignKey: {
name: 'referred_userId',
},
constraints: false,
});
db.users.hasMany(db.coin_code_redemptions, {
as: 'coin_code_redemptions_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.wallet_transactions, {
as: 'wallet_transactions_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.coin_conversions, {
as: 'coin_conversions_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.user_memberships, {
as: 'user_memberships_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.item_redemptions, {
as: 'item_redemptions_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.products, {
as: 'products_created_by_user',
foreignKey: {
name: 'created_by_userId',
},
constraints: false,
});
db.users.hasMany(db.product_purchases, {
as: 'product_purchases_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.content_consumptions, {
as: 'content_consumptions_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.chat_rooms, {
as: 'chat_rooms_created_by_user',
foreignKey: {
name: 'created_by_userId',
},
constraints: false,
});
db.users.hasMany(db.chat_memberships, {
as: 'chat_memberships_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.chat_messages, {
as: 'chat_messages_sender',
foreignKey: {
name: 'senderId',
},
constraints: false,
});
db.users.hasMany(db.admin_audit_logs, {
as: 'admin_audit_logs_admin_user',
foreignKey: {
name: 'admin_userId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

View File

@ -0,0 +1,109 @@
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 video_contents = sequelize.define(
'video_contents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
video_caption: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
video_contents.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.video_contents.belongsTo(db.products, {
as: 'product',
foreignKey: {
name: 'productId',
},
constraints: false,
});
db.video_contents.hasMany(db.file, {
as: 'video_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.video_contents.getTableName(),
belongsToColumn: 'video_file',
},
});
db.video_contents.belongsTo(db.users, {
as: 'createdBy',
});
db.video_contents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return video_contents;
};

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 wallet_transactions = sequelize.define(
'wallet_transactions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
currency: {
type: DataTypes.ENUM,
values: [
"DOODLECOIN",
"SUPERCHARGED"
],
},
direction: {
type: DataTypes.ENUM,
values: [
"CREDIT",
"DEBIT"
],
},
amount: {
type: DataTypes.INTEGER,
},
balance_after: {
type: DataTypes.INTEGER,
},
reason: {
type: DataTypes.ENUM,
values: [
"CODE_REDEMPTION",
"REFERRAL_REWARD",
"STREAK_REWARD",
"CONVERSION",
"MEMBERSHIP_PURCHASE",
"PRODUCT_PURCHASE",
"ITEM_REDEMPTION",
"ADMIN_ADJUSTMENT",
"OTHER"
],
},
reference: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
wallet_transactions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.wallet_transactions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.wallet_transactions.belongsTo(db.users, {
as: 'createdBy',
});
db.wallet_transactions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return wallet_transactions;
};

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

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

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

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

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

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

@ -0,0 +1,228 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const user_sessionsRoutes = require('./routes/user_sessions');
const referralsRoutes = require('./routes/referrals');
const coin_earning_rulesRoutes = require('./routes/coin_earning_rules');
const coin_codesRoutes = require('./routes/coin_codes');
const coin_code_redemptionsRoutes = require('./routes/coin_code_redemptions');
const wallet_transactionsRoutes = require('./routes/wallet_transactions');
const coin_conversionsRoutes = require('./routes/coin_conversions');
const membership_plansRoutes = require('./routes/membership_plans');
const user_membershipsRoutes = require('./routes/user_memberships');
const shop_itemsRoutes = require('./routes/shop_items');
const item_redemptionsRoutes = require('./routes/item_redemptions');
const productsRoutes = require('./routes/products');
const article_contentsRoutes = require('./routes/article_contents');
const comic_contentsRoutes = require('./routes/comic_contents');
const video_contentsRoutes = require('./routes/video_contents');
const game_contentsRoutes = require('./routes/game_contents');
const product_purchasesRoutes = require('./routes/product_purchases');
const content_consumptionsRoutes = require('./routes/content_consumptions');
const chat_roomsRoutes = require('./routes/chat_rooms');
const chat_membershipsRoutes = require('./routes/chat_memberships');
const chat_messagesRoutes = require('./routes/chat_messages');
const app_settingsRoutes = require('./routes/app_settings');
const admin_audit_logsRoutes = require('./routes/admin_audit_logs');
const getBaseUrl = (url) => {
if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url;
};
const options = {
definition: {
openapi: "3.0.0",
info: {
version: "1.0.0",
title: "Daily Doodle App",
description: "Daily Doodle App Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
},
servers: [
{
url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
description: "Development server",
}
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
},
responses: {
UnauthorizedError: {
description: "Access token is missing or invalid"
}
}
},
security: [{
bearerAuth: []
}]
},
apis: ["./src/routes/*.js"],
};
const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
next()
}, swaggerUI.serve, swaggerUI.setup(specs))
app.use(cors({origin: true}));
require('./auth/auth');
app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');
app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);
app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);
app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);
app.use('/api/user_sessions', passport.authenticate('jwt', {session: false}), user_sessionsRoutes);
app.use('/api/referrals', passport.authenticate('jwt', {session: false}), referralsRoutes);
app.use('/api/coin_earning_rules', passport.authenticate('jwt', {session: false}), coin_earning_rulesRoutes);
app.use('/api/coin_codes', passport.authenticate('jwt', {session: false}), coin_codesRoutes);
app.use('/api/coin_code_redemptions', passport.authenticate('jwt', {session: false}), coin_code_redemptionsRoutes);
app.use('/api/wallet_transactions', passport.authenticate('jwt', {session: false}), wallet_transactionsRoutes);
app.use('/api/coin_conversions', passport.authenticate('jwt', {session: false}), coin_conversionsRoutes);
app.use('/api/membership_plans', passport.authenticate('jwt', {session: false}), membership_plansRoutes);
app.use('/api/user_memberships', passport.authenticate('jwt', {session: false}), user_membershipsRoutes);
app.use('/api/shop_items', passport.authenticate('jwt', {session: false}), shop_itemsRoutes);
app.use('/api/item_redemptions', passport.authenticate('jwt', {session: false}), item_redemptionsRoutes);
app.use('/api/products', passport.authenticate('jwt', {session: false}), productsRoutes);
app.use('/api/article_contents', passport.authenticate('jwt', {session: false}), article_contentsRoutes);
app.use('/api/comic_contents', passport.authenticate('jwt', {session: false}), comic_contentsRoutes);
app.use('/api/video_contents', passport.authenticate('jwt', {session: false}), video_contentsRoutes);
app.use('/api/game_contents', passport.authenticate('jwt', {session: false}), game_contentsRoutes);
app.use('/api/product_purchases', passport.authenticate('jwt', {session: false}), product_purchasesRoutes);
app.use('/api/content_consumptions', passport.authenticate('jwt', {session: false}), content_consumptionsRoutes);
app.use('/api/chat_rooms', passport.authenticate('jwt', {session: false}), chat_roomsRoutes);
app.use('/api/chat_memberships', passport.authenticate('jwt', {session: false}), chat_membershipsRoutes);
app.use('/api/chat_messages', passport.authenticate('jwt', {session: false}), chat_messagesRoutes);
app.use('/api/app_settings', passport.authenticate('jwt', {session: false}), app_settingsRoutes);
app.use('/api/admin_audit_logs', passport.authenticate('jwt', {session: false}), admin_audit_logsRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
module.exports = app;

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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