Initial version

This commit is contained in:
Flatlogic Bot 2026-02-17 01:04:19 +00:00
commit 453c680d47
569 changed files with 162025 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>Crafted Network</h2>
<p>Trust-first service directory with verification, transparent pricing, AI-style matching, and request tracking.</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/

306
README.md Normal file
View File

@ -0,0 +1,306 @@
# Crafted Network
## This project was generated by [Flatlogic Platform](https://flatlogic.com).
- Frontend: [React.js](https://flatlogic.com/templates?framework%5B%5D=react&sort=default)
- Design: [Material UI](https://flatlogic.com/templates?design%5B%5D=material&sort=default)
<details><summary>Frontend Folder Structure</summary>
The generated application has the following frontend folder structure:
`src` folder which contains your working files that will be used later to create the build. the src folder contains folders as:
- `actions` - the instructions the user issue to the redux to either write or fetch data from the store;
- `components` - this module consists of a collection of UI components of your project;
- `context` - contains all your context files;
- `images` - contains all images used in your project ;
- `pages` - this module contains the general components for CRUD:
- `CRUD/Users` folder, which includes `form`, `helpers`, `page`, `tables` folders;
- `dashboard` folder;
- `error` folder;
- `login` folder;
- `reset` folder;
- `starter` folder;
- `user` folder;
- `verify` folder.
- `reducer` - contains functions that take actions from the application, perform an action and return a new state based on the action passed into it.
`public` - is the web-accessible root of the site. Basically whatever is in that folder can be opened from the browser address bar. The server won't provide user access to files outside the public.
</details>
- 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`
### Quick Start
#### 1. Run `yarn install`
This will install both run-time project dependencies and developer tools listed
in [package.json](../project-files/package.json) file.
#### 2. Run `yarn start`
Runs the app in the development mode.
Open http://localhost:3000 to view it in the browser. Whenever you modify any of the source files inside the `/src` folder,
the module bundler ([Webpack](http://webpack.github.io/)) will recompile the
app on the fly and refresh all the connected browsers.
#### 3. Run `yarn build`
Builds the app for production to the build folder.
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.
Your app is ready to be deployed!
## 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_38501
DB_USER=app_38501
DB_PASS=b2096650-3f1a-4a16-b97d-7302e7d1c0fe
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 @@
#Crafted Network - 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_crafted_network;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_crafted_network 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": "craftednetwork",
"description": "Crafted Network - 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: "b2096650",
user_pass: "7302e7d1c0fe",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'b2096650-3f1a-4a16-b97d-7302e7d1c0fe',
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: 'Crafted Network <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: 'Verified Business Owner',
},
project_uuid: 'b2096650-3f1a-4a16-b97d-7302e7d1c0fe',
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 = 'Crafted bridge over calm river';
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,519 @@
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 Audit_logsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.create(
{
id: data.id || undefined,
action: data.action
||
null
,
entity_type: data.entity_type
||
null
,
entity_key: data.entity_key
||
null
,
meta_json: data.meta_json
||
null
,
tenant_key: data.tenant_key
||
null
,
created_at_ts: data.created_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audit_logs.setActor_user( data.actor_user || null, {
transaction,
});
return 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 audit_logsData = data.map((item, index) => ({
id: item.id || undefined,
action: item.action
||
null
,
entity_type: item.entity_type
||
null
,
entity_key: item.entity_key
||
null
,
meta_json: item.meta_json
||
null
,
tenant_key: item.tenant_key
||
null
,
created_at_ts: item.created_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const audit_logs = await db.audit_logs.bulkCreate(audit_logsData, { transaction });
// For each item created, replace relation files
return audit_logs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.action !== undefined) updatePayload.action = data.action;
if (data.entity_type !== undefined) updatePayload.entity_type = data.entity_type;
if (data.entity_key !== undefined) updatePayload.entity_key = data.entity_key;
if (data.meta_json !== undefined) updatePayload.meta_json = data.meta_json;
if (data.tenant_key !== undefined) updatePayload.tenant_key = data.tenant_key;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
updatePayload.updatedById = currentUser.id;
await audit_logs.update(updatePayload, {transaction});
if (data.actor_user !== undefined) {
await audit_logs.setActor_user(
data.actor_user,
{ transaction }
);
}
return audit_logs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of audit_logs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of audit_logs) {
await record.destroy({transaction});
}
});
return audit_logs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findByPk(id, options);
await audit_logs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await audit_logs.destroy({
transaction
});
return audit_logs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findOne(
{ where },
{ transaction },
);
if (!audit_logs) {
return audit_logs;
}
const output = audit_logs.get({plain: true});
output.actor_user = await audit_logs.getActor_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: 'actor_user',
where: filter.actor_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.actor_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.actor_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.action) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'action',
filter.action,
),
};
}
if (filter.entity_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'entity_type',
filter.entity_type,
),
};
}
if (filter.entity_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'entity_key',
filter.entity_key,
),
};
}
if (filter.meta_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'meta_json',
filter.meta_json,
),
};
}
if (filter.tenant_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'tenant_key',
filter.tenant_key,
),
};
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[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.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(
'audit_logs',
'action',
query,
),
],
};
}
const records = await db.audit_logs.findAll({
attributes: [ 'id', 'action' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['action', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.action,
}));
}
};

View File

@ -0,0 +1,489 @@
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 Badge_rulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const badge_rules = await db.badge_rules.create(
{
id: data.id || undefined,
badge_type: data.badge_type
||
null
,
required_evidence_json: data.required_evidence_json
||
null
,
is_active: data.is_active
||
false
,
tenant_key: data.tenant_key
||
null
,
created_at_ts: data.created_at_ts
||
null
,
updated_at_ts: data.updated_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return badge_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 badge_rulesData = data.map((item, index) => ({
id: item.id || undefined,
badge_type: item.badge_type
||
null
,
required_evidence_json: item.required_evidence_json
||
null
,
is_active: item.is_active
||
false
,
tenant_key: item.tenant_key
||
null
,
created_at_ts: item.created_at_ts
||
null
,
updated_at_ts: item.updated_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const badge_rules = await db.badge_rules.bulkCreate(badge_rulesData, { transaction });
// For each item created, replace relation files
return badge_rules;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const badge_rules = await db.badge_rules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.badge_type !== undefined) updatePayload.badge_type = data.badge_type;
if (data.required_evidence_json !== undefined) updatePayload.required_evidence_json = data.required_evidence_json;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.tenant_key !== undefined) updatePayload.tenant_key = data.tenant_key;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
updatePayload.updatedById = currentUser.id;
await badge_rules.update(updatePayload, {transaction});
return badge_rules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const badge_rules = await db.badge_rules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of badge_rules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of badge_rules) {
await record.destroy({transaction});
}
});
return badge_rules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const badge_rules = await db.badge_rules.findByPk(id, options);
await badge_rules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await badge_rules.destroy({
transaction
});
return badge_rules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const badge_rules = await db.badge_rules.findOne(
{ where },
{ transaction },
);
if (!badge_rules) {
return badge_rules;
}
const output = badge_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.required_evidence_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'badge_rules',
'required_evidence_json',
filter.required_evidence_json,
),
};
}
if (filter.tenant_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'badge_rules',
'tenant_key',
filter.tenant_key,
),
};
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.updated_at_tsRange) {
const [start, end] = filter.updated_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.badge_type) {
where = {
...where,
badge_type: filter.badge_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_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.badge_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(
'badge_rules',
'required_evidence_json',
query,
),
],
};
}
const records = await db.badge_rules.findAll({
attributes: [ 'id', 'required_evidence_json' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['required_evidence_json', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.required_evidence_json,
}));
}
};

View File

@ -0,0 +1,574 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Business_badgesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const business_badges = await db.business_badges.create(
{
id: data.id || undefined,
badge_type: data.badge_type
||
null
,
status: data.status
||
null
,
granted_at: data.granted_at
||
null
,
revoked_at: data.revoked_at
||
null
,
notes: data.notes
||
null
,
created_at_ts: data.created_at_ts
||
null
,
updated_at_ts: data.updated_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await business_badges.setBusiness( data.business || null, {
transaction,
});
return business_badges;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const business_badgesData = data.map((item, index) => ({
id: item.id || undefined,
badge_type: item.badge_type
||
null
,
status: item.status
||
null
,
granted_at: item.granted_at
||
null
,
revoked_at: item.revoked_at
||
null
,
notes: item.notes
||
null
,
created_at_ts: item.created_at_ts
||
null
,
updated_at_ts: item.updated_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const business_badges = await db.business_badges.bulkCreate(business_badgesData, { transaction });
// For each item created, replace relation files
return business_badges;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const business_badges = await db.business_badges.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.badge_type !== undefined) updatePayload.badge_type = data.badge_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.granted_at !== undefined) updatePayload.granted_at = data.granted_at;
if (data.revoked_at !== undefined) updatePayload.revoked_at = data.revoked_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
updatePayload.updatedById = currentUser.id;
await business_badges.update(updatePayload, {transaction});
if (data.business !== undefined) {
await business_badges.setBusiness(
data.business,
{ transaction }
);
}
return business_badges;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const business_badges = await db.business_badges.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of business_badges) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of business_badges) {
await record.destroy({transaction});
}
});
return business_badges;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const business_badges = await db.business_badges.findByPk(id, options);
await business_badges.update({
deletedBy: currentUser.id
}, {
transaction,
});
await business_badges.destroy({
transaction
});
return business_badges;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const business_badges = await db.business_badges.findOne(
{ where },
{ transaction },
);
if (!business_badges) {
return business_badges;
}
const output = business_badges.get({plain: true});
output.business = await business_badges.getBusiness({
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.businesses,
as: 'business',
where: filter.business ? {
[Op.or]: [
{ id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'business_badges',
'notes',
filter.notes,
),
};
}
if (filter.granted_atRange) {
const [start, end] = filter.granted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
granted_at: {
...where.granted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
granted_at: {
...where.granted_at,
[Op.lte]: end,
},
};
}
}
if (filter.revoked_atRange) {
const [start, end] = filter.revoked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.lte]: end,
},
};
}
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.updated_at_tsRange) {
const [start, end] = filter.updated_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.badge_type) {
where = {
...where,
badge_type: filter.badge_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.business_badges.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'business_badges',
'notes',
query,
),
],
};
}
const records = await db.business_badges.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};

View File

@ -0,0 +1,436 @@
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 Business_categoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const business_categories = await db.business_categories.create(
{
id: data.id || undefined,
created_at_ts: data.created_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await business_categories.setBusiness( data.business || null, {
transaction,
});
await business_categories.setCategory( data.category || null, {
transaction,
});
return business_categories;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const business_categoriesData = data.map((item, index) => ({
id: item.id || undefined,
created_at_ts: item.created_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const business_categories = await db.business_categories.bulkCreate(business_categoriesData, { transaction });
// For each item created, replace relation files
return business_categories;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const business_categories = await db.business_categories.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
updatePayload.updatedById = currentUser.id;
await business_categories.update(updatePayload, {transaction});
if (data.business !== undefined) {
await business_categories.setBusiness(
data.business,
{ transaction }
);
}
if (data.category !== undefined) {
await business_categories.setCategory(
data.category,
{ transaction }
);
}
return business_categories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const business_categories = await db.business_categories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of business_categories) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of business_categories) {
await record.destroy({transaction});
}
});
return business_categories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const business_categories = await db.business_categories.findByPk(id, options);
await business_categories.update({
deletedBy: currentUser.id
}, {
transaction,
});
await business_categories.destroy({
transaction
});
return business_categories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const business_categories = await db.business_categories.findOne(
{ where },
{ transaction },
);
if (!business_categories) {
return business_categories;
}
const output = business_categories.get({plain: true});
output.business = await business_categories.getBusiness({
transaction
});
output.category = await business_categories.getCategory({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.businesses,
as: 'business',
where: filter.business ? {
[Op.or]: [
{ id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[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.business_categories.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'business_categories',
'created_at_ts',
query,
),
],
};
}
const records = await db.business_categories.findAll({
attributes: [ 'id', 'created_at_ts' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['created_at_ts', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.created_at_ts,
}));
}
};

View File

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

View File

@ -0,0 +1,970 @@
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 BusinessesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const businesses = await db.businesses.create(
{
id: data.id || undefined,
name: data.name
||
null
,
slug: data.slug
||
null
,
description: data.description
||
null
,
phone: data.phone
||
null
,
email: data.email
||
null
,
website: data.website
||
null
,
address: data.address
||
null
,
city: data.city
||
null
,
state: data.state
||
null
,
zip: data.zip
||
null
,
lat: data.lat
||
null
,
lng: data.lng
||
null
,
hours_json: data.hours_json
||
null
,
availability_status: data.availability_status
||
null
,
is_active: data.is_active
||
false
,
reliability_score: data.reliability_score
||
null
,
reliability_breakdown_json: data.reliability_breakdown_json
||
null
,
response_time_median_minutes: data.response_time_median_minutes
||
null
,
tenant_key: data.tenant_key
||
null
,
created_at_ts: data.created_at_ts
||
null
,
updated_at_ts: data.updated_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await businesses.setOwner_user( data.owner_user || null, {
transaction,
});
return businesses;
}
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 businessesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
slug: item.slug
||
null
,
description: item.description
||
null
,
phone: item.phone
||
null
,
email: item.email
||
null
,
website: item.website
||
null
,
address: item.address
||
null
,
city: item.city
||
null
,
state: item.state
||
null
,
zip: item.zip
||
null
,
lat: item.lat
||
null
,
lng: item.lng
||
null
,
hours_json: item.hours_json
||
null
,
availability_status: item.availability_status
||
null
,
is_active: item.is_active
||
false
,
reliability_score: item.reliability_score
||
null
,
reliability_breakdown_json: item.reliability_breakdown_json
||
null
,
response_time_median_minutes: item.response_time_median_minutes
||
null
,
tenant_key: item.tenant_key
||
null
,
created_at_ts: item.created_at_ts
||
null
,
updated_at_ts: item.updated_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const businesses = await db.businesses.bulkCreate(businessesData, { transaction });
// For each item created, replace relation files
return businesses;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const businesses = await db.businesses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.website !== undefined) updatePayload.website = data.website;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state !== undefined) updatePayload.state = data.state;
if (data.zip !== undefined) updatePayload.zip = data.zip;
if (data.lat !== undefined) updatePayload.lat = data.lat;
if (data.lng !== undefined) updatePayload.lng = data.lng;
if (data.hours_json !== undefined) updatePayload.hours_json = data.hours_json;
if (data.availability_status !== undefined) updatePayload.availability_status = data.availability_status;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.reliability_score !== undefined) updatePayload.reliability_score = data.reliability_score;
if (data.reliability_breakdown_json !== undefined) updatePayload.reliability_breakdown_json = data.reliability_breakdown_json;
if (data.response_time_median_minutes !== undefined) updatePayload.response_time_median_minutes = data.response_time_median_minutes;
if (data.tenant_key !== undefined) updatePayload.tenant_key = data.tenant_key;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
updatePayload.updatedById = currentUser.id;
await businesses.update(updatePayload, {transaction});
if (data.owner_user !== undefined) {
await businesses.setOwner_user(
data.owner_user,
{ transaction }
);
}
return businesses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const businesses = await db.businesses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of businesses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of businesses) {
await record.destroy({transaction});
}
});
return businesses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const businesses = await db.businesses.findByPk(id, options);
await businesses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await businesses.destroy({
transaction
});
return businesses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const businesses = await db.businesses.findOne(
{ where },
{ transaction },
);
if (!businesses) {
return businesses;
}
const output = businesses.get({plain: true});
output.business_photos_business = await businesses.getBusiness_photos_business({
transaction
});
output.business_categories_business = await businesses.getBusiness_categories_business({
transaction
});
output.service_prices_business = await businesses.getService_prices_business({
transaction
});
output.business_badges_business = await businesses.getBusiness_badges_business({
transaction
});
output.verification_submissions_business = await businesses.getVerification_submissions_business({
transaction
});
output.lead_matches_business = await businesses.getLead_matches_business({
transaction
});
output.reviews_business = await businesses.getReviews_business({
transaction
});
output.trust_adjustments_business = await businesses.getTrust_adjustments_business({
transaction
});
output.owner_user = await businesses.getOwner_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: 'owner_user',
where: filter.owner_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'name',
filter.name,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'slug',
filter.slug,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'description',
filter.description,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'phone',
filter.phone,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'email',
filter.email,
),
};
}
if (filter.website) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'website',
filter.website,
),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'address',
filter.address,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'city',
filter.city,
),
};
}
if (filter.state) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'state',
filter.state,
),
};
}
if (filter.zip) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'zip',
filter.zip,
),
};
}
if (filter.hours_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'hours_json',
filter.hours_json,
),
};
}
if (filter.reliability_breakdown_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'reliability_breakdown_json',
filter.reliability_breakdown_json,
),
};
}
if (filter.tenant_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'businesses',
'tenant_key',
filter.tenant_key,
),
};
}
if (filter.latRange) {
const [start, end] = filter.latRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lat: {
...where.lat,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lat: {
...where.lat,
[Op.lte]: end,
},
};
}
}
if (filter.lngRange) {
const [start, end] = filter.lngRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lng: {
...where.lng,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lng: {
...where.lng,
[Op.lte]: end,
},
};
}
}
if (filter.reliability_scoreRange) {
const [start, end] = filter.reliability_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reliability_score: {
...where.reliability_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reliability_score: {
...where.reliability_score,
[Op.lte]: end,
},
};
}
}
if (filter.response_time_median_minutesRange) {
const [start, end] = filter.response_time_median_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
response_time_median_minutes: {
...where.response_time_median_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
response_time_median_minutes: {
...where.response_time_median_minutes,
[Op.lte]: end,
},
};
}
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.updated_at_tsRange) {
const [start, end] = filter.updated_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.availability_status) {
where = {
...where,
availability_status: filter.availability_status,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_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.businesses.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(
'businesses',
'name',
query,
),
],
};
}
const records = await db.businesses.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,549 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class CategoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const categories = await db.categories.create(
{
id: data.id || undefined,
name: data.name
||
null
,
slug: data.slug
||
null
,
icon: data.icon
||
null
,
description: data.description
||
null
,
is_active: data.is_active
||
false
,
tenant_key: data.tenant_key
||
null
,
created_at_ts: data.created_at_ts
||
null
,
updated_at_ts: data.updated_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return categories;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const categoriesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
slug: item.slug
||
null
,
icon: item.icon
||
null
,
description: item.description
||
null
,
is_active: item.is_active
||
false
,
tenant_key: item.tenant_key
||
null
,
created_at_ts: item.created_at_ts
||
null
,
updated_at_ts: item.updated_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const categories = await db.categories.bulkCreate(categoriesData, { transaction });
// For each item created, replace relation files
return categories;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const categories = await db.categories.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.icon !== undefined) updatePayload.icon = data.icon;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.tenant_key !== undefined) updatePayload.tenant_key = data.tenant_key;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
updatePayload.updatedById = currentUser.id;
await categories.update(updatePayload, {transaction});
return categories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const categories = await db.categories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of categories) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of categories) {
await record.destroy({transaction});
}
});
return categories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const categories = await db.categories.findByPk(id, options);
await categories.update({
deletedBy: currentUser.id
}, {
transaction,
});
await categories.destroy({
transaction
});
return categories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const categories = await db.categories.findOne(
{ where },
{ transaction },
);
if (!categories) {
return categories;
}
const output = categories.get({plain: true});
output.business_categories_category = await categories.getBusiness_categories_category({
transaction
});
output.leads_category = await categories.getLeads_category({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'categories',
'name',
filter.name,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'categories',
'slug',
filter.slug,
),
};
}
if (filter.icon) {
where = {
...where,
[Op.and]: Utils.ilike(
'categories',
'icon',
filter.icon,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'categories',
'description',
filter.description,
),
};
}
if (filter.tenant_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'categories',
'tenant_key',
filter.tenant_key,
),
};
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.updated_at_tsRange) {
const [start, end] = filter.updated_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.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.categories.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'categories',
'name',
query,
),
],
};
}
const records = await db.categories.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,541 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class DisputesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.create(
{
id: data.id || undefined,
reason: data.reason
||
null
,
status: data.status
||
null
,
resolution_notes: data.resolution_notes
||
null
,
created_at_ts: data.created_at_ts
||
null
,
updated_at_ts: data.updated_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await disputes.setLead( data.lead || null, {
transaction,
});
await disputes.setOpened_by_user( data.opened_by_user || null, {
transaction,
});
return disputes;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const disputesData = data.map((item, index) => ({
id: item.id || undefined,
reason: item.reason
||
null
,
status: item.status
||
null
,
resolution_notes: item.resolution_notes
||
null
,
created_at_ts: item.created_at_ts
||
null
,
updated_at_ts: item.updated_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const disputes = await db.disputes.bulkCreate(disputesData, { transaction });
// For each item created, replace relation files
return disputes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.reason !== undefined) updatePayload.reason = data.reason;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.resolution_notes !== undefined) updatePayload.resolution_notes = data.resolution_notes;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
updatePayload.updatedById = currentUser.id;
await disputes.update(updatePayload, {transaction});
if (data.lead !== undefined) {
await disputes.setLead(
data.lead,
{ transaction }
);
}
if (data.opened_by_user !== undefined) {
await disputes.setOpened_by_user(
data.opened_by_user,
{ transaction }
);
}
return disputes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of disputes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of disputes) {
await record.destroy({transaction});
}
});
return disputes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findByPk(id, options);
await disputes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await disputes.destroy({
transaction
});
return disputes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findOne(
{ where },
{ transaction },
);
if (!disputes) {
return disputes;
}
const output = disputes.get({plain: true});
output.lead = await disputes.getLead({
transaction
});
output.opened_by_user = await disputes.getOpened_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.leads,
as: 'lead',
where: filter.lead ? {
[Op.or]: [
{ id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } },
{
keyword: {
[Op.or]: filter.lead.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'opened_by_user',
where: filter.opened_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.opened_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.opened_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reason) {
where = {
...where,
[Op.and]: Utils.ilike(
'disputes',
'reason',
filter.reason,
),
};
}
if (filter.resolution_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'disputes',
'resolution_notes',
filter.resolution_notes,
),
};
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.updated_at_tsRange) {
const [start, end] = filter.updated_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[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.disputes.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'disputes',
'reason',
query,
),
],
};
}
const records = await db.disputes.findAll({
attributes: [ 'id', 'reason' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reason', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reason,
}));
}
};

View File

@ -0,0 +1,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,528 @@
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 Lead_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const lead_events = await db.lead_events.create(
{
id: data.id || undefined,
event_type: data.event_type
||
null
,
from_value: data.from_value
||
null
,
to_value: data.to_value
||
null
,
meta_json: data.meta_json
||
null
,
created_at_ts: data.created_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await lead_events.setLead( data.lead || null, {
transaction,
});
await lead_events.setActor_user( data.actor_user || null, {
transaction,
});
return lead_events;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const lead_eventsData = data.map((item, index) => ({
id: item.id || undefined,
event_type: item.event_type
||
null
,
from_value: item.from_value
||
null
,
to_value: item.to_value
||
null
,
meta_json: item.meta_json
||
null
,
created_at_ts: item.created_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const lead_events = await db.lead_events.bulkCreate(lead_eventsData, { transaction });
// For each item created, replace relation files
return lead_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const lead_events = await db.lead_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
if (data.from_value !== undefined) updatePayload.from_value = data.from_value;
if (data.to_value !== undefined) updatePayload.to_value = data.to_value;
if (data.meta_json !== undefined) updatePayload.meta_json = data.meta_json;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
updatePayload.updatedById = currentUser.id;
await lead_events.update(updatePayload, {transaction});
if (data.lead !== undefined) {
await lead_events.setLead(
data.lead,
{ transaction }
);
}
if (data.actor_user !== undefined) {
await lead_events.setActor_user(
data.actor_user,
{ transaction }
);
}
return lead_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const lead_events = await db.lead_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of lead_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of lead_events) {
await record.destroy({transaction});
}
});
return lead_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const lead_events = await db.lead_events.findByPk(id, options);
await lead_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await lead_events.destroy({
transaction
});
return lead_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const lead_events = await db.lead_events.findOne(
{ where },
{ transaction },
);
if (!lead_events) {
return lead_events;
}
const output = lead_events.get({plain: true});
output.lead = await lead_events.getLead({
transaction
});
output.actor_user = await lead_events.getActor_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.leads,
as: 'lead',
where: filter.lead ? {
[Op.or]: [
{ id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } },
{
keyword: {
[Op.or]: filter.lead.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'actor_user',
where: filter.actor_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.actor_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.actor_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.from_value) {
where = {
...where,
[Op.and]: Utils.ilike(
'lead_events',
'from_value',
filter.from_value,
),
};
}
if (filter.to_value) {
where = {
...where,
[Op.and]: Utils.ilike(
'lead_events',
'to_value',
filter.to_value,
),
};
}
if (filter.meta_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'lead_events',
'meta_json',
filter.meta_json,
),
};
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.event_type) {
where = {
...where,
event_type: filter.event_type,
};
}
if (filter.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.lead_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'lead_events',
'event_type',
query,
),
],
};
}
const records = await db.lead_events.findAll({
attributes: [ 'id', 'event_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['event_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.event_type,
}));
}
};

View File

@ -0,0 +1,752 @@
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 Lead_matchesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const lead_matches = await db.lead_matches.create(
{
id: data.id || undefined,
match_score: data.match_score
||
null
,
status: data.status
||
null
,
sent_at: data.sent_at
||
null
,
viewed_at: data.viewed_at
||
null
,
responded_at: data.responded_at
||
null
,
scheduled_at: data.scheduled_at
||
null
,
completed_at: data.completed_at
||
null
,
declined_at: data.declined_at
||
null
,
created_at_ts: data.created_at_ts
||
null
,
updated_at_ts: data.updated_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await lead_matches.setLead( data.lead || null, {
transaction,
});
await lead_matches.setBusiness( data.business || null, {
transaction,
});
return lead_matches;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const lead_matchesData = data.map((item, index) => ({
id: item.id || undefined,
match_score: item.match_score
||
null
,
status: item.status
||
null
,
sent_at: item.sent_at
||
null
,
viewed_at: item.viewed_at
||
null
,
responded_at: item.responded_at
||
null
,
scheduled_at: item.scheduled_at
||
null
,
completed_at: item.completed_at
||
null
,
declined_at: item.declined_at
||
null
,
created_at_ts: item.created_at_ts
||
null
,
updated_at_ts: item.updated_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const lead_matches = await db.lead_matches.bulkCreate(lead_matchesData, { transaction });
// For each item created, replace relation files
return lead_matches;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const lead_matches = await db.lead_matches.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.match_score !== undefined) updatePayload.match_score = data.match_score;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.viewed_at !== undefined) updatePayload.viewed_at = data.viewed_at;
if (data.responded_at !== undefined) updatePayload.responded_at = data.responded_at;
if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.declined_at !== undefined) updatePayload.declined_at = data.declined_at;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
updatePayload.updatedById = currentUser.id;
await lead_matches.update(updatePayload, {transaction});
if (data.lead !== undefined) {
await lead_matches.setLead(
data.lead,
{ transaction }
);
}
if (data.business !== undefined) {
await lead_matches.setBusiness(
data.business,
{ transaction }
);
}
return lead_matches;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const lead_matches = await db.lead_matches.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of lead_matches) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of lead_matches) {
await record.destroy({transaction});
}
});
return lead_matches;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const lead_matches = await db.lead_matches.findByPk(id, options);
await lead_matches.update({
deletedBy: currentUser.id
}, {
transaction,
});
await lead_matches.destroy({
transaction
});
return lead_matches;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const lead_matches = await db.lead_matches.findOne(
{ where },
{ transaction },
);
if (!lead_matches) {
return lead_matches;
}
const output = lead_matches.get({plain: true});
output.lead = await lead_matches.getLead({
transaction
});
output.business = await lead_matches.getBusiness({
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.leads,
as: 'lead',
where: filter.lead ? {
[Op.or]: [
{ id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } },
{
keyword: {
[Op.or]: filter.lead.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.businesses,
as: 'business',
where: filter.business ? {
[Op.or]: [
{ id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.match_scoreRange) {
const [start, end] = filter.match_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
match_score: {
...where.match_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
match_score: {
...where.match_score,
[Op.lte]: end,
},
};
}
}
if (filter.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.viewed_atRange) {
const [start, end] = filter.viewed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
viewed_at: {
...where.viewed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
viewed_at: {
...where.viewed_at,
[Op.lte]: end,
},
};
}
}
if (filter.responded_atRange) {
const [start, end] = filter.responded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
responded_at: {
...where.responded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
responded_at: {
...where.responded_at,
[Op.lte]: end,
},
};
}
}
if (filter.scheduled_atRange) {
const [start, end] = filter.scheduled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.declined_atRange) {
const [start, end] = filter.declined_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
declined_at: {
...where.declined_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
declined_at: {
...where.declined_at,
[Op.lte]: end,
},
};
}
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.updated_at_tsRange) {
const [start, end] = filter.updated_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[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.lead_matches.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'lead_matches',
'status',
query,
),
],
};
}
const records = await db.lead_matches.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,441 @@
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 Lead_photosDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const lead_photos = await db.lead_photos.create(
{
id: data.id || undefined,
created_at_ts: data.created_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await lead_photos.setLead( data.lead || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.lead_photos.getTableName(),
belongsToColumn: 'photos',
belongsToId: lead_photos.id,
},
data.photos,
options,
);
return lead_photos;
}
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 lead_photosData = data.map((item, index) => ({
id: item.id || undefined,
created_at_ts: item.created_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const lead_photos = await db.lead_photos.bulkCreate(lead_photosData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < lead_photos.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.lead_photos.getTableName(),
belongsToColumn: 'photos',
belongsToId: lead_photos[i].id,
},
data[i].photos,
options,
);
}
return lead_photos;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const lead_photos = await db.lead_photos.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
updatePayload.updatedById = currentUser.id;
await lead_photos.update(updatePayload, {transaction});
if (data.lead !== undefined) {
await lead_photos.setLead(
data.lead,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.lead_photos.getTableName(),
belongsToColumn: 'photos',
belongsToId: lead_photos.id,
},
data.photos,
options,
);
return lead_photos;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const lead_photos = await db.lead_photos.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of lead_photos) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of lead_photos) {
await record.destroy({transaction});
}
});
return lead_photos;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const lead_photos = await db.lead_photos.findByPk(id, options);
await lead_photos.update({
deletedBy: currentUser.id
}, {
transaction,
});
await lead_photos.destroy({
transaction
});
return lead_photos;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const lead_photos = await db.lead_photos.findOne(
{ where },
{ transaction },
);
if (!lead_photos) {
return lead_photos;
}
const output = lead_photos.get({plain: true});
output.lead = await lead_photos.getLead({
transaction
});
output.photos = await lead_photos.getPhotos({
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.leads,
as: 'lead',
where: filter.lead ? {
[Op.or]: [
{ id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } },
{
keyword: {
[Op.or]: filter.lead.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'photos',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[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.lead_photos.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(
'lead_photos',
'photos',
query,
),
],
};
}
const records = await db.lead_photos.findAll({
attributes: [ 'id', 'photos' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['photos', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.photos,
}));
}
};

875
backend/src/db/api/leads.js Normal file
View File

@ -0,0 +1,875 @@
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 LeadsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const leads = await db.leads.create(
{
id: data.id || undefined,
keyword: data.keyword
||
null
,
description: data.description
||
null
,
urgency: data.urgency
||
null
,
status: data.status
||
null
,
contact_name: data.contact_name
||
null
,
contact_phone: data.contact_phone
||
null
,
contact_email: data.contact_email
||
null
,
address: data.address
||
null
,
city: data.city
||
null
,
state: data.state
||
null
,
zip: data.zip
||
null
,
lat: data.lat
||
null
,
lng: data.lng
||
null
,
inferred_tags_json: data.inferred_tags_json
||
null
,
tenant_key: data.tenant_key
||
null
,
created_at_ts: data.created_at_ts
||
null
,
updated_at_ts: data.updated_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await leads.setUser( data.user || null, {
transaction,
});
await leads.setCategory( data.category || null, {
transaction,
});
return leads;
}
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 leadsData = data.map((item, index) => ({
id: item.id || undefined,
keyword: item.keyword
||
null
,
description: item.description
||
null
,
urgency: item.urgency
||
null
,
status: item.status
||
null
,
contact_name: item.contact_name
||
null
,
contact_phone: item.contact_phone
||
null
,
contact_email: item.contact_email
||
null
,
address: item.address
||
null
,
city: item.city
||
null
,
state: item.state
||
null
,
zip: item.zip
||
null
,
lat: item.lat
||
null
,
lng: item.lng
||
null
,
inferred_tags_json: item.inferred_tags_json
||
null
,
tenant_key: item.tenant_key
||
null
,
created_at_ts: item.created_at_ts
||
null
,
updated_at_ts: item.updated_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const leads = await db.leads.bulkCreate(leadsData, { transaction });
// For each item created, replace relation files
return leads;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const leads = await db.leads.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.keyword !== undefined) updatePayload.keyword = data.keyword;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.urgency !== undefined) updatePayload.urgency = data.urgency;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
if (data.contact_phone !== undefined) updatePayload.contact_phone = data.contact_phone;
if (data.contact_email !== undefined) updatePayload.contact_email = data.contact_email;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state !== undefined) updatePayload.state = data.state;
if (data.zip !== undefined) updatePayload.zip = data.zip;
if (data.lat !== undefined) updatePayload.lat = data.lat;
if (data.lng !== undefined) updatePayload.lng = data.lng;
if (data.inferred_tags_json !== undefined) updatePayload.inferred_tags_json = data.inferred_tags_json;
if (data.tenant_key !== undefined) updatePayload.tenant_key = data.tenant_key;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
updatePayload.updatedById = currentUser.id;
await leads.update(updatePayload, {transaction});
if (data.user !== undefined) {
await leads.setUser(
data.user,
{ transaction }
);
}
if (data.category !== undefined) {
await leads.setCategory(
data.category,
{ transaction }
);
}
return leads;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const leads = await db.leads.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of leads) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of leads) {
await record.destroy({transaction});
}
});
return leads;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const leads = await db.leads.findByPk(id, options);
await leads.update({
deletedBy: currentUser.id
}, {
transaction,
});
await leads.destroy({
transaction
});
return leads;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const leads = await db.leads.findOne(
{ where },
{ transaction },
);
if (!leads) {
return leads;
}
const output = leads.get({plain: true});
output.lead_photos_lead = await leads.getLead_photos_lead({
transaction
});
output.lead_matches_lead = await leads.getLead_matches_lead({
transaction
});
output.messages_lead = await leads.getMessages_lead({
transaction
});
output.lead_events_lead = await leads.getLead_events_lead({
transaction
});
output.reviews_lead = await leads.getReviews_lead({
transaction
});
output.disputes_lead = await leads.getDisputes_lead({
transaction
});
output.user = await leads.getUser({
transaction
});
output.category = await leads.getCategory({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.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.categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.keyword) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'keyword',
filter.keyword,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'description',
filter.description,
),
};
}
if (filter.contact_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'contact_name',
filter.contact_name,
),
};
}
if (filter.contact_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'contact_phone',
filter.contact_phone,
),
};
}
if (filter.contact_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'contact_email',
filter.contact_email,
),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'address',
filter.address,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'city',
filter.city,
),
};
}
if (filter.state) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'state',
filter.state,
),
};
}
if (filter.zip) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'zip',
filter.zip,
),
};
}
if (filter.inferred_tags_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'inferred_tags_json',
filter.inferred_tags_json,
),
};
}
if (filter.tenant_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'leads',
'tenant_key',
filter.tenant_key,
),
};
}
if (filter.latRange) {
const [start, end] = filter.latRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lat: {
...where.lat,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lat: {
...where.lat,
[Op.lte]: end,
},
};
}
}
if (filter.lngRange) {
const [start, end] = filter.lngRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lng: {
...where.lng,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lng: {
...where.lng,
[Op.lte]: end,
},
};
}
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.updated_at_tsRange) {
const [start, end] = filter.updated_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.urgency) {
where = {
...where,
urgency: filter.urgency,
};
}
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.leads.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(
'leads',
'keyword',
query,
),
],
};
}
const records = await db.leads.findAll({
attributes: [ 'id', 'keyword' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['keyword', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.keyword,
}));
}
};

View File

@ -0,0 +1,556 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class LocationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const locations = await db.locations.create(
{
id: data.id || undefined,
label: data.label
||
null
,
city: data.city
||
null
,
state: data.state
||
null
,
zip: data.zip
||
null
,
lat: data.lat
||
null
,
lng: data.lng
||
null
,
tenant_key: data.tenant_key
||
null
,
created_at_ts: data.created_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return locations;
}
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 locationsData = data.map((item, index) => ({
id: item.id || undefined,
label: item.label
||
null
,
city: item.city
||
null
,
state: item.state
||
null
,
zip: item.zip
||
null
,
lat: item.lat
||
null
,
lng: item.lng
||
null
,
tenant_key: item.tenant_key
||
null
,
created_at_ts: item.created_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const locations = await db.locations.bulkCreate(locationsData, { transaction });
// For each item created, replace relation files
return locations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const locations = await db.locations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.label !== undefined) updatePayload.label = data.label;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state !== undefined) updatePayload.state = data.state;
if (data.zip !== undefined) updatePayload.zip = data.zip;
if (data.lat !== undefined) updatePayload.lat = data.lat;
if (data.lng !== undefined) updatePayload.lng = data.lng;
if (data.tenant_key !== undefined) updatePayload.tenant_key = data.tenant_key;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
updatePayload.updatedById = currentUser.id;
await locations.update(updatePayload, {transaction});
return locations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const locations = await db.locations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of locations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of locations) {
await record.destroy({transaction});
}
});
return locations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const locations = await db.locations.findByPk(id, options);
await locations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await locations.destroy({
transaction
});
return locations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const locations = await db.locations.findOne(
{ where },
{ transaction },
);
if (!locations) {
return locations;
}
const output = locations.get({plain: true});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.label) {
where = {
...where,
[Op.and]: Utils.ilike(
'locations',
'label',
filter.label,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'locations',
'city',
filter.city,
),
};
}
if (filter.state) {
where = {
...where,
[Op.and]: Utils.ilike(
'locations',
'state',
filter.state,
),
};
}
if (filter.zip) {
where = {
...where,
[Op.and]: Utils.ilike(
'locations',
'zip',
filter.zip,
),
};
}
if (filter.tenant_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'locations',
'tenant_key',
filter.tenant_key,
),
};
}
if (filter.latRange) {
const [start, end] = filter.latRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lat: {
...where.lat,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lat: {
...where.lat,
[Op.lte]: end,
},
};
}
}
if (filter.lngRange) {
const [start, end] = filter.lngRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lng: {
...where.lng,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lng: {
...where.lng,
[Op.lte]: end,
},
};
}
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[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.locations.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(
'locations',
'label',
query,
),
],
};
}
const records = await db.locations.findAll({
attributes: [ 'id', 'label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.label,
}));
}
};

View File

@ -0,0 +1,534 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class MessagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.create(
{
id: data.id || undefined,
body: data.body
||
null
,
read_at: data.read_at
||
null
,
created_at_ts: data.created_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await messages.setLead( data.lead || null, {
transaction,
});
await messages.setSender_user( data.sender_user || null, {
transaction,
});
await messages.setReceiver_user( data.receiver_user || null, {
transaction,
});
return messages;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const messagesData = data.map((item, index) => ({
id: item.id || undefined,
body: item.body
||
null
,
read_at: item.read_at
||
null
,
created_at_ts: item.created_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const messages = await db.messages.bulkCreate(messagesData, { transaction });
// For each item created, replace relation files
return messages;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.body !== undefined) updatePayload.body = data.body;
if (data.read_at !== undefined) updatePayload.read_at = data.read_at;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
updatePayload.updatedById = currentUser.id;
await messages.update(updatePayload, {transaction});
if (data.lead !== undefined) {
await messages.setLead(
data.lead,
{ transaction }
);
}
if (data.sender_user !== undefined) {
await messages.setSender_user(
data.sender_user,
{ transaction }
);
}
if (data.receiver_user !== undefined) {
await messages.setReceiver_user(
data.receiver_user,
{ transaction }
);
}
return messages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of messages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of messages) {
await record.destroy({transaction});
}
});
return messages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findByPk(id, options);
await messages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await messages.destroy({
transaction
});
return messages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const messages = await db.messages.findOne(
{ where },
{ transaction },
);
if (!messages) {
return messages;
}
const output = messages.get({plain: true});
output.lead = await messages.getLead({
transaction
});
output.sender_user = await messages.getSender_user({
transaction
});
output.receiver_user = await messages.getReceiver_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.leads,
as: 'lead',
where: filter.lead ? {
[Op.or]: [
{ id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } },
{
keyword: {
[Op.or]: filter.lead.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'sender_user',
where: filter.sender_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.sender_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.sender_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'receiver_user',
where: filter.receiver_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.receiver_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.receiver_user.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(
'messages',
'body',
filter.body,
),
};
}
if (filter.read_atRange) {
const [start, end] = filter.read_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
read_at: {
...where.read_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
read_at: {
...where.read_at,
[Op.lte]: end,
},
};
}
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[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.messages.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'messages',
'body',
query,
),
],
};
}
const records = await db.messages.findAll({
attributes: [ 'id', 'body' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['body', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.body,
}));
}
};

View File

@ -0,0 +1,349 @@
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,545 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Refresh_tokensDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const refresh_tokens = await db.refresh_tokens.create(
{
id: data.id || undefined,
token_hash: data.token_hash
||
null
,
expires_at: data.expires_at
||
null
,
revoked_at: data.revoked_at
||
null
,
ip_address: data.ip_address
||
null
,
user_agent: data.user_agent
||
null
,
created_at_ts: data.created_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await refresh_tokens.setUser( data.user || null, {
transaction,
});
return refresh_tokens;
}
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 refresh_tokensData = data.map((item, index) => ({
id: item.id || undefined,
token_hash: item.token_hash
||
null
,
expires_at: item.expires_at
||
null
,
revoked_at: item.revoked_at
||
null
,
ip_address: item.ip_address
||
null
,
user_agent: item.user_agent
||
null
,
created_at_ts: item.created_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const refresh_tokens = await db.refresh_tokens.bulkCreate(refresh_tokensData, { transaction });
// For each item created, replace relation files
return refresh_tokens;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const refresh_tokens = await db.refresh_tokens.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.token_hash !== undefined) updatePayload.token_hash = data.token_hash;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.revoked_at !== undefined) updatePayload.revoked_at = data.revoked_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.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
updatePayload.updatedById = currentUser.id;
await refresh_tokens.update(updatePayload, {transaction});
if (data.user !== undefined) {
await refresh_tokens.setUser(
data.user,
{ transaction }
);
}
return refresh_tokens;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const refresh_tokens = await db.refresh_tokens.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of refresh_tokens) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of refresh_tokens) {
await record.destroy({transaction});
}
});
return refresh_tokens;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const refresh_tokens = await db.refresh_tokens.findByPk(id, options);
await refresh_tokens.update({
deletedBy: currentUser.id
}, {
transaction,
});
await refresh_tokens.destroy({
transaction
});
return refresh_tokens;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const refresh_tokens = await db.refresh_tokens.findOne(
{ where },
{ transaction },
);
if (!refresh_tokens) {
return refresh_tokens;
}
const output = refresh_tokens.get({plain: true});
output.user = await refresh_tokens.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.token_hash) {
where = {
...where,
[Op.and]: Utils.ilike(
'refresh_tokens',
'token_hash',
filter.token_hash,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'refresh_tokens',
'ip_address',
filter.ip_address,
),
};
}
if (filter.user_agent) {
where = {
...where,
[Op.and]: Utils.ilike(
'refresh_tokens',
'user_agent',
filter.user_agent,
),
};
}
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.revoked_atRange) {
const [start, end] = filter.revoked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.lte]: end,
},
};
}
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[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.refresh_tokens.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(
'refresh_tokens',
'token_hash',
query,
),
],
};
}
const records = await db.refresh_tokens.findAll({
attributes: [ 'id', 'token_hash' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['token_hash', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.token_hash,
}));
}
};

View File

@ -0,0 +1,637 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ReviewsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reviews = await db.reviews.create(
{
id: data.id || undefined,
rating: data.rating
||
null
,
text: data.text
||
null
,
is_verified_job: data.is_verified_job
||
false
,
status: data.status
||
null
,
moderation_notes: data.moderation_notes
||
null
,
created_at_ts: data.created_at_ts
||
null
,
updated_at_ts: data.updated_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await reviews.setBusiness( data.business || null, {
transaction,
});
await reviews.setUser( data.user || null, {
transaction,
});
await reviews.setLead( data.lead || null, {
transaction,
});
return reviews;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const reviewsData = data.map((item, index) => ({
id: item.id || undefined,
rating: item.rating
||
null
,
text: item.text
||
null
,
is_verified_job: item.is_verified_job
||
false
,
status: item.status
||
null
,
moderation_notes: item.moderation_notes
||
null
,
created_at_ts: item.created_at_ts
||
null
,
updated_at_ts: item.updated_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const reviews = await db.reviews.bulkCreate(reviewsData, { transaction });
// For each item created, replace relation files
return reviews;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reviews = await db.reviews.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.rating !== undefined) updatePayload.rating = data.rating;
if (data.text !== undefined) updatePayload.text = data.text;
if (data.is_verified_job !== undefined) updatePayload.is_verified_job = data.is_verified_job;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.moderation_notes !== undefined) updatePayload.moderation_notes = data.moderation_notes;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
updatePayload.updatedById = currentUser.id;
await reviews.update(updatePayload, {transaction});
if (data.business !== undefined) {
await reviews.setBusiness(
data.business,
{ transaction }
);
}
if (data.user !== undefined) {
await reviews.setUser(
data.user,
{ transaction }
);
}
if (data.lead !== undefined) {
await reviews.setLead(
data.lead,
{ transaction }
);
}
return reviews;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reviews = await db.reviews.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of reviews) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of reviews) {
await record.destroy({transaction});
}
});
return reviews;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reviews = await db.reviews.findByPk(id, options);
await reviews.update({
deletedBy: currentUser.id
}, {
transaction,
});
await reviews.destroy({
transaction
});
return reviews;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const reviews = await db.reviews.findOne(
{ where },
{ transaction },
);
if (!reviews) {
return reviews;
}
const output = reviews.get({plain: true});
output.business = await reviews.getBusiness({
transaction
});
output.user = await reviews.getUser({
transaction
});
output.lead = await reviews.getLead({
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.businesses,
as: 'business',
where: filter.business ? {
[Op.or]: [
{ id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.leads,
as: 'lead',
where: filter.lead ? {
[Op.or]: [
{ id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } },
{
keyword: {
[Op.or]: filter.lead.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.text) {
where = {
...where,
[Op.and]: Utils.ilike(
'reviews',
'text',
filter.text,
),
};
}
if (filter.moderation_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'reviews',
'moderation_notes',
filter.moderation_notes,
),
};
}
if (filter.ratingRange) {
const [start, end] = filter.ratingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rating: {
...where.rating,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rating: {
...where.rating,
[Op.lte]: end,
},
};
}
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.updated_at_tsRange) {
const [start, end] = filter.updated_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_verified_job) {
where = {
...where,
is_verified_job: filter.is_verified_job,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.reviews.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'reviews',
'text',
query,
),
],
};
}
const records = await db.reviews.findAll({
attributes: [ 'id', 'text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.text,
}));
}
};

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

@ -0,0 +1,419 @@
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,595 @@
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 Service_pricesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_prices = await db.service_prices.create(
{
id: data.id || undefined,
service_name: data.service_name
||
null
,
min_price: data.min_price
||
null
,
max_price: data.max_price
||
null
,
typical_price: data.typical_price
||
null
,
notes: data.notes
||
null
,
created_at_ts: data.created_at_ts
||
null
,
updated_at_ts: data.updated_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await service_prices.setBusiness( data.business || null, {
transaction,
});
return service_prices;
}
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 service_pricesData = data.map((item, index) => ({
id: item.id || undefined,
service_name: item.service_name
||
null
,
min_price: item.min_price
||
null
,
max_price: item.max_price
||
null
,
typical_price: item.typical_price
||
null
,
notes: item.notes
||
null
,
created_at_ts: item.created_at_ts
||
null
,
updated_at_ts: item.updated_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const service_prices = await db.service_prices.bulkCreate(service_pricesData, { transaction });
// For each item created, replace relation files
return service_prices;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const service_prices = await db.service_prices.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.service_name !== undefined) updatePayload.service_name = data.service_name;
if (data.min_price !== undefined) updatePayload.min_price = data.min_price;
if (data.max_price !== undefined) updatePayload.max_price = data.max_price;
if (data.typical_price !== undefined) updatePayload.typical_price = data.typical_price;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
updatePayload.updatedById = currentUser.id;
await service_prices.update(updatePayload, {transaction});
if (data.business !== undefined) {
await service_prices.setBusiness(
data.business,
{ transaction }
);
}
return service_prices;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_prices = await db.service_prices.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of service_prices) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of service_prices) {
await record.destroy({transaction});
}
});
return service_prices;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const service_prices = await db.service_prices.findByPk(id, options);
await service_prices.update({
deletedBy: currentUser.id
}, {
transaction,
});
await service_prices.destroy({
transaction
});
return service_prices;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const service_prices = await db.service_prices.findOne(
{ where },
{ transaction },
);
if (!service_prices) {
return service_prices;
}
const output = service_prices.get({plain: true});
output.business = await service_prices.getBusiness({
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.businesses,
as: 'business',
where: filter.business ? {
[Op.or]: [
{ id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.service_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_prices',
'service_name',
filter.service_name,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_prices',
'notes',
filter.notes,
),
};
}
if (filter.min_priceRange) {
const [start, end] = filter.min_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_price: {
...where.min_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_price: {
...where.min_price,
[Op.lte]: end,
},
};
}
}
if (filter.max_priceRange) {
const [start, end] = filter.max_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_price: {
...where.max_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_price: {
...where.max_price,
[Op.lte]: end,
},
};
}
}
if (filter.typical_priceRange) {
const [start, end] = filter.typical_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
typical_price: {
...where.typical_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
typical_price: {
...where.typical_price,
[Op.lte]: end,
},
};
}
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.updated_at_tsRange) {
const [start, end] = filter.updated_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[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.service_prices.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(
'service_prices',
'service_name',
query,
),
],
};
}
const records = await db.service_prices.findAll({
attributes: [ 'id', 'service_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['service_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.service_name,
}));
}
};

View File

@ -0,0 +1,497 @@
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 Trust_adjustmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trust_adjustments = await db.trust_adjustments.create(
{
id: data.id || undefined,
delta: data.delta
||
null
,
reason: data.reason
||
null
,
created_at_ts: data.created_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await trust_adjustments.setBusiness( data.business || null, {
transaction,
});
await trust_adjustments.setAdmin_user( data.admin_user || null, {
transaction,
});
return trust_adjustments;
}
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 trust_adjustmentsData = data.map((item, index) => ({
id: item.id || undefined,
delta: item.delta
||
null
,
reason: item.reason
||
null
,
created_at_ts: item.created_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const trust_adjustments = await db.trust_adjustments.bulkCreate(trust_adjustmentsData, { transaction });
// For each item created, replace relation files
return trust_adjustments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const trust_adjustments = await db.trust_adjustments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.delta !== undefined) updatePayload.delta = data.delta;
if (data.reason !== undefined) updatePayload.reason = data.reason;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
updatePayload.updatedById = currentUser.id;
await trust_adjustments.update(updatePayload, {transaction});
if (data.business !== undefined) {
await trust_adjustments.setBusiness(
data.business,
{ transaction }
);
}
if (data.admin_user !== undefined) {
await trust_adjustments.setAdmin_user(
data.admin_user,
{ transaction }
);
}
return trust_adjustments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const trust_adjustments = await db.trust_adjustments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of trust_adjustments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of trust_adjustments) {
await record.destroy({transaction});
}
});
return trust_adjustments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const trust_adjustments = await db.trust_adjustments.findByPk(id, options);
await trust_adjustments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await trust_adjustments.destroy({
transaction
});
return trust_adjustments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const trust_adjustments = await db.trust_adjustments.findOne(
{ where },
{ transaction },
);
if (!trust_adjustments) {
return trust_adjustments;
}
const output = trust_adjustments.get({plain: true});
output.business = await trust_adjustments.getBusiness({
transaction
});
output.admin_user = await trust_adjustments.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.businesses,
as: 'business',
where: filter.business ? {
[Op.or]: [
{ id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
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.reason) {
where = {
...where,
[Op.and]: Utils.ilike(
'trust_adjustments',
'reason',
filter.reason,
),
};
}
if (filter.deltaRange) {
const [start, end] = filter.deltaRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
delta: {
...where.delta,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
delta: {
...where.delta,
[Op.lte]: end,
},
};
}
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[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.trust_adjustments.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(
'trust_adjustments',
'reason',
query,
),
],
};
}
const records = await db.trust_adjustments.findAll({
attributes: [ 'id', 'reason' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reason', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reason,
}));
}
};

987
backend/src/db/api/users.js Normal file
View File

@ -0,0 +1,987 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const bcrypt = require('bcrypt');
const config = require('../../config');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class UsersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.create(
{
id: data.data.id || undefined,
firstName: data.data.firstName
||
null
,
lastName: data.data.lastName
||
null
,
phoneNumber: data.data.phoneNumber
||
null
,
email: data.data.email
||
null
,
disabled: data.data.disabled
||
false
,
password: data.data.password
||
null
,
emailVerified: data.data.emailVerified
||
true
,
emailVerificationToken: data.data.emailVerificationToken
||
null
,
emailVerificationTokenExpiresAt: data.data.emailVerificationTokenExpiresAt
||
null
,
passwordResetToken: data.data.passwordResetToken
||
null
,
passwordResetTokenExpiresAt: data.data.passwordResetTokenExpiresAt
||
null
,
provider: data.data.provider
||
null
,
importHash: data.data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
if (!data.data.app_role) {
const role = await db.roles.findOne({
where: { name: 'User' },
});
if (role) {
await users.setApp_role(role, {
transaction,
});
}
}else{
await users.setApp_role(data.data.app_role || null, {
transaction,
});
}
await users.setCustom_permissions(data.data.custom_permissions || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users.id,
},
data.data.avatar,
options,
);
return users;
}
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 usersData = data.map((item, index) => ({
id: item.id || undefined,
firstName: item.firstName
||
null
,
lastName: item.lastName
||
null
,
phoneNumber: item.phoneNumber
||
null
,
email: item.email
||
null
,
disabled: item.disabled
||
false
,
password: item.password
||
null
,
emailVerified: item.emailVerified
||
false
,
emailVerificationToken: item.emailVerificationToken
||
null
,
emailVerificationTokenExpiresAt: item.emailVerificationTokenExpiresAt
||
null
,
passwordResetToken: item.passwordResetToken
||
null
,
passwordResetTokenExpiresAt: item.passwordResetTokenExpiresAt
||
null
,
provider: item.provider
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const users = await db.users.bulkCreate(usersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < users.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users[i].id,
},
data[i].avatar,
options,
);
}
return users;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {}, {transaction});
if (!data?.app_role) {
data.app_role = users?.app_role?.id;
}
if (!data?.custom_permissions) {
data.custom_permissions = users?.custom_permissions?.map(item => item.id);
}
if (data.password) {
data.password = bcrypt.hashSync(
data.password,
config.bcrypt.saltRounds,
);
} else {
data.password = users.password;
}
const updatePayload = {};
if (data.firstName !== undefined) updatePayload.firstName = data.firstName;
if (data.lastName !== undefined) updatePayload.lastName = data.lastName;
if (data.phoneNumber !== undefined) updatePayload.phoneNumber = data.phoneNumber;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.disabled !== undefined) updatePayload.disabled = data.disabled;
if (data.password !== undefined) updatePayload.password = data.password;
if (data.emailVerified !== undefined) updatePayload.emailVerified = data.emailVerified;
else updatePayload.emailVerified = true;
if (data.emailVerificationToken !== undefined) updatePayload.emailVerificationToken = data.emailVerificationToken;
if (data.emailVerificationTokenExpiresAt !== undefined) updatePayload.emailVerificationTokenExpiresAt = data.emailVerificationTokenExpiresAt;
if (data.passwordResetToken !== undefined) updatePayload.passwordResetToken = data.passwordResetToken;
if (data.passwordResetTokenExpiresAt !== undefined) updatePayload.passwordResetTokenExpiresAt = data.passwordResetTokenExpiresAt;
if (data.provider !== undefined) updatePayload.provider = data.provider;
updatePayload.updatedById = currentUser.id;
await users.update(updatePayload, {transaction});
if (data.app_role !== undefined) {
await users.setApp_role(
data.app_role,
{ transaction }
);
}
if (data.custom_permissions !== undefined) {
await users.setCustom_permissions(data.custom_permissions, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users.id,
},
data.avatar,
options,
);
return users;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of users) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of users) {
await record.destroy({transaction});
}
});
return users;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, options);
await users.update({
deletedBy: currentUser.id
}, {
transaction,
});
await users.destroy({
transaction
});
return users;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findOne(
{ where },
{ transaction },
);
if (!users) {
return users;
}
const output = users.get({plain: true});
output.refresh_tokens_user = await users.getRefresh_tokens_user({
transaction
});
output.businesses_owner_user = await users.getBusinesses_owner_user({
transaction
});
output.leads_user = await users.getLeads_user({
transaction
});
output.messages_sender_user = await users.getMessages_sender_user({
transaction
});
output.messages_receiver_user = await users.getMessages_receiver_user({
transaction
});
output.lead_events_actor_user = await users.getLead_events_actor_user({
transaction
});
output.reviews_user = await users.getReviews_user({
transaction
});
output.disputes_opened_by_user = await users.getDisputes_opened_by_user({
transaction
});
output.audit_logs_actor_user = await users.getAudit_logs_actor_user({
transaction
});
output.trust_adjustments_admin_user = await users.getTrust_adjustments_admin_user({
transaction
});
output.avatar = await users.getAvatar({
transaction
});
output.app_role = await users.getApp_role({
transaction
});
if (output.app_role) {
output.app_role_permissions = await output.app_role.getPermissions({
transaction,
});
}
output.custom_permissions = await users.getCustom_permissions({
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.roles,
as: 'app_role',
where: filter.app_role ? {
[Op.or]: [
{ id: { [Op.in]: filter.app_role.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.app_role.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.permissions,
as: 'custom_permissions',
required: false,
},
{
model: db.file,
as: 'avatar',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.firstName) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'firstName',
filter.firstName,
),
};
}
if (filter.lastName) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'lastName',
filter.lastName,
),
};
}
if (filter.phoneNumber) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'phoneNumber',
filter.phoneNumber,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'email',
filter.email,
),
};
}
if (filter.password) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'password',
filter.password,
),
};
}
if (filter.emailVerificationToken) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'emailVerificationToken',
filter.emailVerificationToken,
),
};
}
if (filter.passwordResetToken) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'passwordResetToken',
filter.passwordResetToken,
),
};
}
if (filter.provider) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'provider',
filter.provider,
),
};
}
if (filter.emailVerificationTokenExpiresAtRange) {
const [start, end] = filter.emailVerificationTokenExpiresAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
emailVerificationTokenExpiresAt: {
...where.emailVerificationTokenExpiresAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
emailVerificationTokenExpiresAt: {
...where.emailVerificationTokenExpiresAt,
[Op.lte]: end,
},
};
}
}
if (filter.passwordResetTokenExpiresAtRange) {
const [start, end] = filter.passwordResetTokenExpiresAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
passwordResetTokenExpiresAt: {
...where.passwordResetTokenExpiresAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
passwordResetTokenExpiresAt: {
...where.passwordResetTokenExpiresAt,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.disabled) {
where = {
...where,
disabled: filter.disabled,
};
}
if (filter.emailVerified) {
where = {
...where,
emailVerified: filter.emailVerified,
};
}
if (filter.custom_permissions) {
const searchTerms = filter.custom_permissions.split('|');
include = [
{
model: db.permissions,
as: 'custom_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.users.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(
'users',
'firstName',
query,
),
],
};
}
const records = await db.users.findAll({
attributes: [ 'id', 'firstName' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['firstName', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.firstName,
}));
}
static async createFromAuth(data, options) {
const transaction = (options && options.transaction) || undefined;
const users = await db.users.create(
{
email: data.email,
firstName: data.firstName,
authenticationUid: data.authenticationUid,
password: data.password,
},
{ transaction },
);
const app_role = await db.roles.findOne({
where: { name: config.roles?.user || "User" },
});
if (app_role?.id) {
await users.setApp_role(app_role?.id || null, {
transaction,
});
}
await users.update(
{
authenticationUid: users.id,
},
{ transaction },
);
delete users.password;
return users;
}
static async updatePassword(id, password, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {
transaction,
});
await users.update(
{
password,
authenticationUid: id,
updatedById: currentUser.id,
},
{ transaction },
);
return users;
}
static async generateEmailVerificationToken(email, options) {
return this._generateToken(['emailVerificationToken', 'emailVerificationTokenExpiresAt'], email, options);
}
static async generatePasswordResetToken(email, options) {
return this._generateToken(['passwordResetToken', 'passwordResetTokenExpiresAt'], email, options);
}
static async findByPasswordResetToken(token, options) {
const transaction = (options && options.transaction) || undefined;
return db.users.findOne(
{
where: {
passwordResetToken: token,
passwordResetTokenExpiresAt: {
[db.Sequelize.Op.gt]: Date.now(),
},
},
},
{ transaction },
);
}
static async findByEmailVerificationToken(
token,
options,
) {
const transaction = (options && options.transaction) || undefined;
return db.users.findOne(
{
where: {
emailVerificationToken: token,
emailVerificationTokenExpiresAt: {
[db.Sequelize.Op.gt]: Date.now(),
},
},
},
{ transaction },
);
}
static async markEmailVerified(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {
transaction,
});
await users.update(
{
emailVerified: true,
updatedById: currentUser.id,
},
{ transaction },
);
return true;
}
static async _generateToken(keyNames, email, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findOne(
{
where: { email: email.toLowerCase() },
},
{
transaction,
},
);
const token = crypto
.randomBytes(20)
.toString('hex');
const tokenExpiresAt = Date.now() + 360000;
if(users){
await users.update(
{
[keyNames[0]]: token,
[keyNames[1]]: tokenExpiresAt,
updatedById: currentUser.id,
},
{transaction},
);
}
return token;
}
};

View File

@ -0,0 +1,485 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Verification_evidencesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const verification_evidences = await db.verification_evidences.create(
{
id: data.id || undefined,
evidence_type: data.evidence_type
||
null
,
url: data.url
||
null
,
created_at_ts: data.created_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await verification_evidences.setSubmission( data.submission || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.verification_evidences.getTableName(),
belongsToColumn: 'files',
belongsToId: verification_evidences.id,
},
data.files,
options,
);
return verification_evidences;
}
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 verification_evidencesData = data.map((item, index) => ({
id: item.id || undefined,
evidence_type: item.evidence_type
||
null
,
url: item.url
||
null
,
created_at_ts: item.created_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const verification_evidences = await db.verification_evidences.bulkCreate(verification_evidencesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < verification_evidences.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.verification_evidences.getTableName(),
belongsToColumn: 'files',
belongsToId: verification_evidences[i].id,
},
data[i].files,
options,
);
}
return verification_evidences;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const verification_evidences = await db.verification_evidences.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.evidence_type !== undefined) updatePayload.evidence_type = data.evidence_type;
if (data.url !== undefined) updatePayload.url = data.url;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
updatePayload.updatedById = currentUser.id;
await verification_evidences.update(updatePayload, {transaction});
if (data.submission !== undefined) {
await verification_evidences.setSubmission(
data.submission,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.verification_evidences.getTableName(),
belongsToColumn: 'files',
belongsToId: verification_evidences.id,
},
data.files,
options,
);
return verification_evidences;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const verification_evidences = await db.verification_evidences.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of verification_evidences) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of verification_evidences) {
await record.destroy({transaction});
}
});
return verification_evidences;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const verification_evidences = await db.verification_evidences.findByPk(id, options);
await verification_evidences.update({
deletedBy: currentUser.id
}, {
transaction,
});
await verification_evidences.destroy({
transaction
});
return verification_evidences;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const verification_evidences = await db.verification_evidences.findOne(
{ where },
{ transaction },
);
if (!verification_evidences) {
return verification_evidences;
}
const output = verification_evidences.get({plain: true});
output.submission = await verification_evidences.getSubmission({
transaction
});
output.files = await verification_evidences.getFiles({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.verification_submissions,
as: 'submission',
where: filter.submission ? {
[Op.or]: [
{ id: { [Op.in]: filter.submission.split('|').map(term => Utils.uuid(term)) } },
{
notes: {
[Op.or]: filter.submission.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.url) {
where = {
...where,
[Op.and]: Utils.ilike(
'verification_evidences',
'url',
filter.url,
),
};
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.evidence_type) {
where = {
...where,
evidence_type: filter.evidence_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.verification_evidences.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(
'verification_evidences',
'url',
query,
),
],
};
}
const records = await db.verification_evidences.findAll({
attributes: [ 'id', 'url' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['url', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.url,
}));
}
};

View File

@ -0,0 +1,528 @@
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 Verification_submissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const verification_submissions = await db.verification_submissions.create(
{
id: data.id || undefined,
badge_type: data.badge_type
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
admin_notes: data.admin_notes
||
null
,
created_at_ts: data.created_at_ts
||
null
,
updated_at_ts: data.updated_at_ts
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await verification_submissions.setBusiness( data.business || null, {
transaction,
});
return verification_submissions;
}
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 verification_submissionsData = data.map((item, index) => ({
id: item.id || undefined,
badge_type: item.badge_type
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
admin_notes: item.admin_notes
||
null
,
created_at_ts: item.created_at_ts
||
null
,
updated_at_ts: item.updated_at_ts
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const verification_submissions = await db.verification_submissions.bulkCreate(verification_submissionsData, { transaction });
// For each item created, replace relation files
return verification_submissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const verification_submissions = await db.verification_submissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.badge_type !== undefined) updatePayload.badge_type = data.badge_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.admin_notes !== undefined) updatePayload.admin_notes = data.admin_notes;
if (data.created_at_ts !== undefined) updatePayload.created_at_ts = data.created_at_ts;
if (data.updated_at_ts !== undefined) updatePayload.updated_at_ts = data.updated_at_ts;
updatePayload.updatedById = currentUser.id;
await verification_submissions.update(updatePayload, {transaction});
if (data.business !== undefined) {
await verification_submissions.setBusiness(
data.business,
{ transaction }
);
}
return verification_submissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const verification_submissions = await db.verification_submissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of verification_submissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of verification_submissions) {
await record.destroy({transaction});
}
});
return verification_submissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const verification_submissions = await db.verification_submissions.findByPk(id, options);
await verification_submissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await verification_submissions.destroy({
transaction
});
return verification_submissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const verification_submissions = await db.verification_submissions.findOne(
{ where },
{ transaction },
);
if (!verification_submissions) {
return verification_submissions;
}
const output = verification_submissions.get({plain: true});
output.verification_evidences_submission = await verification_submissions.getVerification_evidences_submission({
transaction
});
output.business = await verification_submissions.getBusiness({
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.businesses,
as: 'business',
where: filter.business ? {
[Op.or]: [
{ id: { [Op.in]: filter.business.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.business.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'verification_submissions',
'notes',
filter.notes,
),
};
}
if (filter.admin_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'verification_submissions',
'admin_notes',
filter.admin_notes,
),
};
}
if (filter.created_at_tsRange) {
const [start, end] = filter.created_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
created_at_ts: {
...where.created_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.updated_at_tsRange) {
const [start, end] = filter.updated_at_tsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
updated_at_ts: {
...where.updated_at_ts,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.badge_type) {
where = {
...where,
badge_type: filter.badge_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.verification_submissions.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(
'verification_submissions',
'notes',
query,
),
],
};
}
const records = await db.verification_submissions.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};

View File

@ -0,0 +1,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_crafted_network',
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,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 audit_logs = sequelize.define(
'audit_logs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
action: {
type: DataTypes.TEXT,
},
entity_type: {
type: DataTypes.TEXT,
},
entity_key: {
type: DataTypes.TEXT,
},
meta_json: {
type: DataTypes.TEXT,
},
tenant_key: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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.audit_logs.belongsTo(db.users, {
as: 'actor_user',
foreignKey: {
name: 'actor_userId',
},
constraints: false,
});
db.audit_logs.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_logs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_logs;
};

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 badge_rules = sequelize.define(
'badge_rules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
badge_type: {
type: DataTypes.ENUM,
values: [
"VERIFIED_BUSINESS",
"VERIFIED_LICENSE",
"VERIFIED_INSURANCE",
"VERIFIED_PRICING",
"FAST_RESPONDER",
"VERIFIED_JOBS"
],
},
required_evidence_json: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
tenant_key: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
updated_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
badge_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.badge_rules.belongsTo(db.users, {
as: 'createdBy',
});
db.badge_rules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return badge_rules;
};

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 business_badges = sequelize.define(
'business_badges',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
badge_type: {
type: DataTypes.ENUM,
values: [
"VERIFIED_BUSINESS",
"VERIFIED_LICENSE",
"VERIFIED_INSURANCE",
"VERIFIED_PRICING",
"FAST_RESPONDER",
"VERIFIED_JOBS"
],
},
status: {
type: DataTypes.ENUM,
values: [
"PENDING",
"APPROVED",
"REJECTED"
],
},
granted_at: {
type: DataTypes.DATE,
},
revoked_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
updated_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
business_badges.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.business_badges.belongsTo(db.businesses, {
as: 'business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.business_badges.belongsTo(db.users, {
as: 'createdBy',
});
db.business_badges.belongsTo(db.users, {
as: 'updatedBy',
});
};
return business_badges;
};

View File

@ -0,0 +1,104 @@
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 business_categories = sequelize.define(
'business_categories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
created_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
business_categories.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.business_categories.belongsTo(db.businesses, {
as: 'business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.business_categories.belongsTo(db.categories, {
as: 'category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
db.business_categories.belongsTo(db.users, {
as: 'createdBy',
});
db.business_categories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return business_categories;
};

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 business_photos = sequelize.define(
'business_photos',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
created_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
business_photos.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.business_photos.belongsTo(db.businesses, {
as: 'business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.business_photos.hasMany(db.file, {
as: 'photos',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.business_photos.getTableName(),
belongsToColumn: 'photos',
},
});
db.business_photos.belongsTo(db.users, {
as: 'createdBy',
});
db.business_photos.belongsTo(db.users, {
as: 'updatedBy',
});
};
return business_photos;
};

View File

@ -0,0 +1,315 @@
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 businesses = sequelize.define(
'businesses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
website: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state: {
type: DataTypes.TEXT,
},
zip: {
type: DataTypes.TEXT,
},
lat: {
type: DataTypes.DECIMAL,
},
lng: {
type: DataTypes.DECIMAL,
},
hours_json: {
type: DataTypes.TEXT,
},
availability_status: {
type: DataTypes.ENUM,
values: [
"AVAILABLE_TODAY",
"THIS_WEEK",
"BOOKED_OUT"
],
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
reliability_score: {
type: DataTypes.INTEGER,
},
reliability_breakdown_json: {
type: DataTypes.TEXT,
},
response_time_median_minutes: {
type: DataTypes.INTEGER,
},
tenant_key: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
updated_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
businesses.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.businesses.hasMany(db.business_photos, {
as: 'business_photos_business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.businesses.hasMany(db.business_categories, {
as: 'business_categories_business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.businesses.hasMany(db.service_prices, {
as: 'service_prices_business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.businesses.hasMany(db.business_badges, {
as: 'business_badges_business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.businesses.hasMany(db.verification_submissions, {
as: 'verification_submissions_business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.businesses.hasMany(db.lead_matches, {
as: 'lead_matches_business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.businesses.hasMany(db.reviews, {
as: 'reviews_business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.businesses.hasMany(db.trust_adjustments, {
as: 'trust_adjustments_business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
//end loop
db.businesses.belongsTo(db.users, {
as: 'owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.businesses.belongsTo(db.users, {
as: 'createdBy',
});
db.businesses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return businesses;
};

View File

@ -0,0 +1,156 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const categories = sequelize.define(
'categories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
icon: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
tenant_key: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
updated_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
categories.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.categories.hasMany(db.business_categories, {
as: 'business_categories_category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
db.categories.hasMany(db.leads, {
as: 'leads_category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
//end loop
db.categories.belongsTo(db.users, {
as: 'createdBy',
});
db.categories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return categories;
};

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 disputes = sequelize.define(
'disputes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
reason: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"OPEN",
"UNDER_REVIEW",
"RESOLVED",
"REJECTED"
],
},
resolution_notes: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
updated_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
disputes.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.disputes.belongsTo(db.leads, {
as: 'lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
db.disputes.belongsTo(db.users, {
as: 'opened_by_user',
foreignKey: {
name: 'opened_by_userId',
},
constraints: false,
});
db.disputes.belongsTo(db.users, {
as: 'createdBy',
});
db.disputes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return disputes;
};

View File

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

View File

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

View File

@ -0,0 +1,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 lead_events = sequelize.define(
'lead_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_type: {
type: DataTypes.ENUM,
values: [
"STATUS_CHANGED",
"MATCH_SENT",
"MATCH_VIEWED",
"MATCH_RESPONDED",
"MATCH_DECLINED",
"MATCH_SCHEDULED",
"MATCH_COMPLETED",
"NOTE_ADDED"
],
},
from_value: {
type: DataTypes.TEXT,
},
to_value: {
type: DataTypes.TEXT,
},
meta_json: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
lead_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.lead_events.belongsTo(db.leads, {
as: 'lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
db.lead_events.belongsTo(db.users, {
as: 'actor_user',
foreignKey: {
name: 'actor_userId',
},
constraints: false,
});
db.lead_events.belongsTo(db.users, {
as: 'createdBy',
});
db.lead_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return lead_events;
};

View File

@ -0,0 +1,188 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const lead_matches = sequelize.define(
'lead_matches',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
match_score: {
type: DataTypes.INTEGER,
},
status: {
type: DataTypes.ENUM,
values: [
"SENT",
"VIEWED",
"RESPONDED",
"DECLINED",
"SCHEDULED",
"COMPLETED"
],
},
sent_at: {
type: DataTypes.DATE,
},
viewed_at: {
type: DataTypes.DATE,
},
responded_at: {
type: DataTypes.DATE,
},
scheduled_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
declined_at: {
type: DataTypes.DATE,
},
created_at_ts: {
type: DataTypes.DATE,
},
updated_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
lead_matches.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.lead_matches.belongsTo(db.leads, {
as: 'lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
db.lead_matches.belongsTo(db.businesses, {
as: 'business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.lead_matches.belongsTo(db.users, {
as: 'createdBy',
});
db.lead_matches.belongsTo(db.users, {
as: 'updatedBy',
});
};
return lead_matches;
};

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 lead_photos = sequelize.define(
'lead_photos',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
created_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
lead_photos.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.lead_photos.belongsTo(db.leads, {
as: 'lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
db.lead_photos.hasMany(db.file, {
as: 'photos',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.lead_photos.getTableName(),
belongsToColumn: 'photos',
},
});
db.lead_photos.belongsTo(db.users, {
as: 'createdBy',
});
db.lead_photos.belongsTo(db.users, {
as: 'updatedBy',
});
};
return lead_photos;
};

View File

@ -0,0 +1,306 @@
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 leads = sequelize.define(
'leads',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
keyword: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
urgency: {
type: DataTypes.ENUM,
values: [
"EMERGENCY",
"TODAY",
"THIS_WEEK",
"FLEXIBLE"
],
},
status: {
type: DataTypes.ENUM,
values: [
"SUBMITTED",
"MATCHED",
"VIEWED",
"RESPONDED",
"SCHEDULED",
"COMPLETED",
"DECLINED",
"CANCELLED"
],
},
contact_name: {
type: DataTypes.TEXT,
},
contact_phone: {
type: DataTypes.TEXT,
},
contact_email: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state: {
type: DataTypes.TEXT,
},
zip: {
type: DataTypes.TEXT,
},
lat: {
type: DataTypes.DECIMAL,
},
lng: {
type: DataTypes.DECIMAL,
},
inferred_tags_json: {
type: DataTypes.TEXT,
},
tenant_key: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
updated_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
leads.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.leads.hasMany(db.lead_photos, {
as: 'lead_photos_lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
db.leads.hasMany(db.lead_matches, {
as: 'lead_matches_lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
db.leads.hasMany(db.messages, {
as: 'messages_lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
db.leads.hasMany(db.lead_events, {
as: 'lead_events_lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
db.leads.hasMany(db.reviews, {
as: 'reviews_lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
db.leads.hasMany(db.disputes, {
as: 'disputes_lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
//end loop
db.leads.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.leads.belongsTo(db.categories, {
as: 'category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
db.leads.belongsTo(db.users, {
as: 'createdBy',
});
db.leads.belongsTo(db.users, {
as: 'updatedBy',
});
};
return leads;
};

View File

@ -0,0 +1,137 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const locations = sequelize.define(
'locations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
label: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state: {
type: DataTypes.TEXT,
},
zip: {
type: DataTypes.TEXT,
},
lat: {
type: DataTypes.DECIMAL,
},
lng: {
type: DataTypes.DECIMAL,
},
tenant_key: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
locations.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.locations.belongsTo(db.users, {
as: 'createdBy',
});
db.locations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return locations;
};

View File

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

View File

@ -0,0 +1,88 @@
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,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 refresh_tokens = sequelize.define(
'refresh_tokens',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
token_hash: {
type: DataTypes.TEXT,
},
expires_at: {
type: DataTypes.DATE,
},
revoked_at: {
type: DataTypes.DATE,
},
ip_address: {
type: DataTypes.TEXT,
},
user_agent: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
refresh_tokens.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.refresh_tokens.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.refresh_tokens.belongsTo(db.users, {
as: 'createdBy',
});
db.refresh_tokens.belongsTo(db.users, {
as: 'updatedBy',
});
};
return refresh_tokens;
};

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 reviews = sequelize.define(
'reviews',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
rating: {
type: DataTypes.INTEGER,
},
text: {
type: DataTypes.TEXT,
},
is_verified_job: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
status: {
type: DataTypes.ENUM,
values: [
"PUBLISHED",
"PENDING",
"HIDDEN",
"REJECTED"
],
},
moderation_notes: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
updated_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
reviews.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.reviews.belongsTo(db.businesses, {
as: 'business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.reviews.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.reviews.belongsTo(db.leads, {
as: 'lead',
foreignKey: {
name: 'leadId',
},
constraints: false,
});
db.reviews.belongsTo(db.users, {
as: 'createdBy',
});
db.reviews.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reviews;
};

View File

@ -0,0 +1,121 @@
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,138 @@
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 service_prices = sequelize.define(
'service_prices',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
service_name: {
type: DataTypes.TEXT,
},
min_price: {
type: DataTypes.DECIMAL,
},
max_price: {
type: DataTypes.DECIMAL,
},
typical_price: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
updated_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
service_prices.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.service_prices.belongsTo(db.businesses, {
as: 'business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.service_prices.belongsTo(db.users, {
as: 'createdBy',
});
db.service_prices.belongsTo(db.users, {
as: 'updatedBy',
});
};
return service_prices;
};

View File

@ -0,0 +1,118 @@
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 trust_adjustments = sequelize.define(
'trust_adjustments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
delta: {
type: DataTypes.INTEGER,
},
reason: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
trust_adjustments.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.trust_adjustments.belongsTo(db.businesses, {
as: 'business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.trust_adjustments.belongsTo(db.users, {
as: 'admin_user',
foreignKey: {
name: 'admin_userId',
},
constraints: false,
});
db.trust_adjustments.belongsTo(db.users, {
as: 'createdBy',
});
db.trust_adjustments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return trust_adjustments;
};

View File

@ -0,0 +1,326 @@
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.refresh_tokens, {
as: 'refresh_tokens_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.businesses, {
as: 'businesses_owner_user',
foreignKey: {
name: 'owner_userId',
},
constraints: false,
});
db.users.hasMany(db.leads, {
as: 'leads_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.messages, {
as: 'messages_sender_user',
foreignKey: {
name: 'sender_userId',
},
constraints: false,
});
db.users.hasMany(db.messages, {
as: 'messages_receiver_user',
foreignKey: {
name: 'receiver_userId',
},
constraints: false,
});
db.users.hasMany(db.lead_events, {
as: 'lead_events_actor_user',
foreignKey: {
name: 'actor_userId',
},
constraints: false,
});
db.users.hasMany(db.reviews, {
as: 'reviews_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.disputes, {
as: 'disputes_opened_by_user',
foreignKey: {
name: 'opened_by_userId',
},
constraints: false,
});
db.users.hasMany(db.audit_logs, {
as: 'audit_logs_actor_user',
foreignKey: {
name: 'actor_userId',
},
constraints: false,
});
db.users.hasMany(db.trust_adjustments, {
as: 'trust_adjustments_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,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 verification_evidences = sequelize.define(
'verification_evidences',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
evidence_type: {
type: DataTypes.ENUM,
values: [
"LICENSE",
"INSURANCE",
"BUSINESS_REGISTRATION",
"INVOICE_REDACTED",
"BEFORE_PHOTO",
"AFTER_PHOTO",
"JOB_PROOF",
"OTHER"
],
},
url: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
verification_evidences.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.verification_evidences.belongsTo(db.verification_submissions, {
as: 'submission',
foreignKey: {
name: 'submissionId',
},
constraints: false,
});
db.verification_evidences.hasMany(db.file, {
as: 'files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.verification_evidences.getTableName(),
belongsToColumn: 'files',
},
});
db.verification_evidences.belongsTo(db.users, {
as: 'createdBy',
});
db.verification_evidences.belongsTo(db.users, {
as: 'updatedBy',
});
};
return verification_evidences;
};

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 verification_submissions = sequelize.define(
'verification_submissions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
badge_type: {
type: DataTypes.ENUM,
values: [
"VERIFIED_BUSINESS",
"VERIFIED_LICENSE",
"VERIFIED_INSURANCE",
"VERIFIED_PRICING",
"FAST_RESPONDER",
"VERIFIED_JOBS"
],
},
status: {
type: DataTypes.ENUM,
values: [
"PENDING",
"APPROVED",
"REJECTED"
],
},
notes: {
type: DataTypes.TEXT,
},
admin_notes: {
type: DataTypes.TEXT,
},
created_at_ts: {
type: DataTypes.DATE,
},
updated_at_ts: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
verification_submissions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.verification_submissions.hasMany(db.verification_evidences, {
as: 'verification_evidences_submission',
foreignKey: {
name: 'submissionId',
},
constraints: false,
});
//end loop
db.verification_submissions.belongsTo(db.businesses, {
as: 'business',
foreignKey: {
name: 'businessId',
},
constraints: false,
});
db.verification_submissions.belongsTo(db.users, {
as: 'createdBy',
});
db.verification_submissions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return verification_submissions;
};

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

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

@ -0,0 +1,218 @@
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 refresh_tokensRoutes = require('./routes/refresh_tokens');
const categoriesRoutes = require('./routes/categories');
const locationsRoutes = require('./routes/locations');
const businessesRoutes = require('./routes/businesses');
const business_photosRoutes = require('./routes/business_photos');
const business_categoriesRoutes = require('./routes/business_categories');
const service_pricesRoutes = require('./routes/service_prices');
const business_badgesRoutes = require('./routes/business_badges');
const verification_submissionsRoutes = require('./routes/verification_submissions');
const verification_evidencesRoutes = require('./routes/verification_evidences');
const leadsRoutes = require('./routes/leads');
const lead_photosRoutes = require('./routes/lead_photos');
const lead_matchesRoutes = require('./routes/lead_matches');
const messagesRoutes = require('./routes/messages');
const lead_eventsRoutes = require('./routes/lead_events');
const reviewsRoutes = require('./routes/reviews');
const disputesRoutes = require('./routes/disputes');
const audit_logsRoutes = require('./routes/audit_logs');
const badge_rulesRoutes = require('./routes/badge_rules');
const trust_adjustmentsRoutes = require('./routes/trust_adjustments');
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: "Crafted Network",
description: "Crafted Network 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/refresh_tokens', passport.authenticate('jwt', {session: false}), refresh_tokensRoutes);
app.use('/api/categories', passport.authenticate('jwt', {session: false}), categoriesRoutes);
app.use('/api/locations', passport.authenticate('jwt', {session: false}), locationsRoutes);
app.use('/api/businesses', passport.authenticate('jwt', {session: false}), businessesRoutes);
app.use('/api/business_photos', passport.authenticate('jwt', {session: false}), business_photosRoutes);
app.use('/api/business_categories', passport.authenticate('jwt', {session: false}), business_categoriesRoutes);
app.use('/api/service_prices', passport.authenticate('jwt', {session: false}), service_pricesRoutes);
app.use('/api/business_badges', passport.authenticate('jwt', {session: false}), business_badgesRoutes);
app.use('/api/verification_submissions', passport.authenticate('jwt', {session: false}), verification_submissionsRoutes);
app.use('/api/verification_evidences', passport.authenticate('jwt', {session: false}), verification_evidencesRoutes);
app.use('/api/leads', passport.authenticate('jwt', {session: false}), leadsRoutes);
app.use('/api/lead_photos', passport.authenticate('jwt', {session: false}), lead_photosRoutes);
app.use('/api/lead_matches', passport.authenticate('jwt', {session: false}), lead_matchesRoutes);
app.use('/api/messages', passport.authenticate('jwt', {session: false}), messagesRoutes);
app.use('/api/lead_events', passport.authenticate('jwt', {session: false}), lead_eventsRoutes);
app.use('/api/reviews', passport.authenticate('jwt', {session: false}), reviewsRoutes);
app.use('/api/disputes', passport.authenticate('jwt', {session: false}), disputesRoutes);
app.use('/api/audit_logs', passport.authenticate('jwt', {session: false}), audit_logsRoutes);
app.use('/api/badge_rules', passport.authenticate('jwt', {session: false}), badge_rulesRoutes);
app.use('/api/trust_adjustments', passport.authenticate('jwt', {session: false}), trust_adjustmentsRoutes);
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;
db.sequelize.sync().then(function () {
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,441 @@
const express = require('express');
const Audit_logsService = require('../services/audit_logs');
const Audit_logsDBApi = require('../db/api/audit_logs');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('audit_logs'));
/**
* @swagger
* components:
* schemas:
* Audit_logs:
* type: object
* properties:
* action:
* type: string
* default: action
* entity_type:
* type: string
* default: entity_type
* entity_key:
* type: string
* default: entity_key
* meta_json:
* type: string
* default: meta_json
* tenant_key:
* type: string
* default: tenant_key
*/
/**
* @swagger
* tags:
* name: Audit_logs
* description: The Audit_logs managing API
*/
/**
* @swagger
* /api/audit_logs:
* post:
* security:
* - bearerAuth: []
* tags: [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/Audit_logs"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/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 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: [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/Audit_logs"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/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 Audit_logsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [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/Audit_logs"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/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 Audit_logsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [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/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 Audit_logsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [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/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 Audit_logsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Get all audit_logs
* description: Get all audit_logs
* responses:
* 200:
* description: Audit_logs list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/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 Audit_logsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','action','entity_type','entity_key','meta_json','tenant_key',
'created_at_ts',
];
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/audit_logs/count:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Count all audit_logs
* description: Count all audit_logs
* responses:
* 200:
* description: Audit_logs count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/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 Audit_logsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Find all audit_logs that match search criteria
* description: Find all audit_logs that match search criteria
* responses:
* 200:
* description: Audit_logs list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/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 Audit_logsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/audit_logs/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [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/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 Audit_logsDBApi.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,433 @@
const express = require('express');
const Badge_rulesService = require('../services/badge_rules');
const Badge_rulesDBApi = require('../db/api/badge_rules');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('badge_rules'));
/**
* @swagger
* components:
* schemas:
* Badge_rules:
* type: object
* properties:
* required_evidence_json:
* type: string
* default: required_evidence_json
* tenant_key:
* type: string
* default: tenant_key
*
*/
/**
* @swagger
* tags:
* name: Badge_rules
* description: The Badge_rules managing API
*/
/**
* @swagger
* /api/badge_rules:
* post:
* security:
* - bearerAuth: []
* tags: [Badge_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/Badge_rules"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Badge_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 Badge_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: [Badge_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/Badge_rules"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Badge_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 Badge_rulesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/badge_rules/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Badge_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/Badge_rules"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Badge_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 Badge_rulesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/badge_rules/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Badge_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/Badge_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 Badge_rulesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/badge_rules/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Badge_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/Badge_rules"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Badge_rulesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/badge_rules:
* get:
* security:
* - bearerAuth: []
* tags: [Badge_rules]
* summary: Get all badge_rules
* description: Get all badge_rules
* responses:
* 200:
* description: Badge_rules list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Badge_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 Badge_rulesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','required_evidence_json','tenant_key',
'created_at_ts','updated_at_ts',
];
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/badge_rules/count:
* get:
* security:
* - bearerAuth: []
* tags: [Badge_rules]
* summary: Count all badge_rules
* description: Count all badge_rules
* responses:
* 200:
* description: Badge_rules count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Badge_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 Badge_rulesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/badge_rules/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Badge_rules]
* summary: Find all badge_rules that match search criteria
* description: Find all badge_rules that match search criteria
* responses:
* 200:
* description: Badge_rules list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Badge_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 Badge_rulesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/badge_rules/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Badge_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/Badge_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 Badge_rulesDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,431 @@
const express = require('express');
const Business_badgesService = require('../services/business_badges');
const Business_badgesDBApi = require('../db/api/business_badges');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('business_badges'));
/**
* @swagger
* components:
* schemas:
* Business_badges:
* type: object
* properties:
* notes:
* type: string
* default: notes
*
*
*/
/**
* @swagger
* tags:
* name: Business_badges
* description: The Business_badges managing API
*/
/**
* @swagger
* /api/business_badges:
* post:
* security:
* - bearerAuth: []
* tags: [Business_badges]
* 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/Business_badges"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Business_badges"
* 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 Business_badgesService.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: [Business_badges]
* 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/Business_badges"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Business_badges"
* 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 Business_badgesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_badges/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Business_badges]
* 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/Business_badges"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Business_badges"
* 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 Business_badgesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_badges/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Business_badges]
* 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/Business_badges"
* 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 Business_badgesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_badges/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Business_badges]
* 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/Business_badges"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Business_badgesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_badges:
* get:
* security:
* - bearerAuth: []
* tags: [Business_badges]
* summary: Get all business_badges
* description: Get all business_badges
* responses:
* 200:
* description: Business_badges list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Business_badges"
* 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 Business_badgesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','notes',
'granted_at','revoked_at','created_at_ts','updated_at_ts',
];
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/business_badges/count:
* get:
* security:
* - bearerAuth: []
* tags: [Business_badges]
* summary: Count all business_badges
* description: Count all business_badges
* responses:
* 200:
* description: Business_badges count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Business_badges"
* 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 Business_badgesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_badges/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Business_badges]
* summary: Find all business_badges that match search criteria
* description: Find all business_badges that match search criteria
* responses:
* 200:
* description: Business_badges list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Business_badges"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Business_badgesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/business_badges/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Business_badges]
* 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/Business_badges"
* 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 Business_badgesDBApi.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 Business_categoriesService = require('../services/business_categories');
const Business_categoriesDBApi = require('../db/api/business_categories');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('business_categories'));
/**
* @swagger
* components:
* schemas:
* Business_categories:
* type: object
* properties:
*/
/**
* @swagger
* tags:
* name: Business_categories
* description: The Business_categories managing API
*/
/**
* @swagger
* /api/business_categories:
* post:
* security:
* - bearerAuth: []
* tags: [Business_categories]
* 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/Business_categories"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Business_categories"
* 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 Business_categoriesService.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: [Business_categories]
* 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/Business_categories"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Business_categories"
* 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 Business_categoriesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_categories/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Business_categories]
* 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/Business_categories"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Business_categories"
* 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 Business_categoriesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_categories/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Business_categories]
* 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/Business_categories"
* 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 Business_categoriesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_categories/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Business_categories]
* 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/Business_categories"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Business_categoriesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_categories:
* get:
* security:
* - bearerAuth: []
* tags: [Business_categories]
* summary: Get all business_categories
* description: Get all business_categories
* responses:
* 200:
* description: Business_categories list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Business_categories"
* 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 Business_categoriesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id',
'created_at_ts',
];
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/business_categories/count:
* get:
* security:
* - bearerAuth: []
* tags: [Business_categories]
* summary: Count all business_categories
* description: Count all business_categories
* responses:
* 200:
* description: Business_categories count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Business_categories"
* 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 Business_categoriesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_categories/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Business_categories]
* summary: Find all business_categories that match search criteria
* description: Find all business_categories that match search criteria
* responses:
* 200:
* description: Business_categories list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Business_categories"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Business_categoriesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/business_categories/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Business_categories]
* 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/Business_categories"
* 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 Business_categoriesDBApi.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 Business_photosService = require('../services/business_photos');
const Business_photosDBApi = require('../db/api/business_photos');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('business_photos'));
/**
* @swagger
* components:
* schemas:
* Business_photos:
* type: object
* properties:
*/
/**
* @swagger
* tags:
* name: Business_photos
* description: The Business_photos managing API
*/
/**
* @swagger
* /api/business_photos:
* post:
* security:
* - bearerAuth: []
* tags: [Business_photos]
* 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/Business_photos"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Business_photos"
* 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 Business_photosService.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: [Business_photos]
* 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/Business_photos"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Business_photos"
* 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 Business_photosService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_photos/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Business_photos]
* 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/Business_photos"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Business_photos"
* 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 Business_photosService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_photos/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Business_photos]
* 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/Business_photos"
* 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 Business_photosService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_photos/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Business_photos]
* 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/Business_photos"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Business_photosService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_photos:
* get:
* security:
* - bearerAuth: []
* tags: [Business_photos]
* summary: Get all business_photos
* description: Get all business_photos
* responses:
* 200:
* description: Business_photos list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Business_photos"
* 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 Business_photosDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id',
'created_at_ts',
];
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/business_photos/count:
* get:
* security:
* - bearerAuth: []
* tags: [Business_photos]
* summary: Count all business_photos
* description: Count all business_photos
* responses:
* 200:
* description: Business_photos count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Business_photos"
* 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 Business_photosDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/business_photos/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Business_photos]
* summary: Find all business_photos that match search criteria
* description: Find all business_photos that match search criteria
* responses:
* 200:
* description: Business_photos list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Business_photos"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Business_photosDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/business_photos/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Business_photos]
* 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/Business_photos"
* 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 Business_photosDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,478 @@
const express = require('express');
const BusinessesService = require('../services/businesses');
const BusinessesDBApi = require('../db/api/businesses');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('businesses'));
/**
* @swagger
* components:
* schemas:
* Businesses:
* type: object
* properties:
* name:
* type: string
* default: name
* slug:
* type: string
* default: slug
* description:
* type: string
* default: description
* phone:
* type: string
* default: phone
* email:
* type: string
* default: email
* website:
* type: string
* default: website
* address:
* type: string
* default: address
* city:
* type: string
* default: city
* state:
* type: string
* default: state
* zip:
* type: string
* default: zip
* hours_json:
* type: string
* default: hours_json
* reliability_breakdown_json:
* type: string
* default: reliability_breakdown_json
* tenant_key:
* type: string
* default: tenant_key
* reliability_score:
* type: integer
* format: int64
* response_time_median_minutes:
* type: integer
* format: int64
* lat:
* type: integer
* format: int64
* lng:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Businesses
* description: The Businesses managing API
*/
/**
* @swagger
* /api/businesses:
* post:
* security:
* - bearerAuth: []
* tags: [Businesses]
* 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/Businesses"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Businesses"
* 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 BusinessesService.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: [Businesses]
* 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/Businesses"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Businesses"
* 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 BusinessesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/businesses/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Businesses]
* 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/Businesses"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Businesses"
* 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 BusinessesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/businesses/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Businesses]
* 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/Businesses"
* 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 BusinessesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/businesses/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Businesses]
* 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/Businesses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await BusinessesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/businesses:
* get:
* security:
* - bearerAuth: []
* tags: [Businesses]
* summary: Get all businesses
* description: Get all businesses
* responses:
* 200:
* description: Businesses list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Businesses"
* 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 BusinessesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','slug','description','phone','email','website','address','city','state','zip','hours_json','reliability_breakdown_json','tenant_key',
'reliability_score','response_time_median_minutes',
'lat','lng',
'created_at_ts','updated_at_ts',
];
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/businesses/count:
* get:
* security:
* - bearerAuth: []
* tags: [Businesses]
* summary: Count all businesses
* description: Count all businesses
* responses:
* 200:
* description: Businesses count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Businesses"
* 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 BusinessesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/businesses/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Businesses]
* summary: Find all businesses that match search criteria
* description: Find all businesses that match search criteria
* responses:
* 200:
* description: Businesses list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Businesses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await BusinessesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/businesses/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Businesses]
* 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/Businesses"
* 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 BusinessesDBApi.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 CategoriesService = require('../services/categories');
const CategoriesDBApi = require('../db/api/categories');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('categories'));
/**
* @swagger
* components:
* schemas:
* Categories:
* type: object
* properties:
* name:
* type: string
* default: name
* slug:
* type: string
* default: slug
* icon:
* type: string
* default: icon
* description:
* type: string
* default: description
* tenant_key:
* type: string
* default: tenant_key
*/
/**
* @swagger
* tags:
* name: Categories
* description: The Categories managing API
*/
/**
* @swagger
* /api/categories:
* post:
* security:
* - bearerAuth: []
* tags: [Categories]
* 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/Categories"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Categories"
* 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 CategoriesService.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: [Categories]
* 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/Categories"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Categories"
* 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 CategoriesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/categories/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Categories]
* 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/Categories"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Categories"
* 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 CategoriesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/categories/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Categories]
* 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/Categories"
* 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 CategoriesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/categories/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Categories]
* 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/Categories"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await CategoriesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/categories:
* get:
* security:
* - bearerAuth: []
* tags: [Categories]
* summary: Get all categories
* description: Get all categories
* responses:
* 200:
* description: Categories list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Categories"
* 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 CategoriesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','slug','icon','description','tenant_key',
'created_at_ts','updated_at_ts',
];
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/categories/count:
* get:
* security:
* - bearerAuth: []
* tags: [Categories]
* summary: Count all categories
* description: Count all categories
* responses:
* 200:
* description: Categories count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Categories"
* 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 CategoriesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/categories/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Categories]
* summary: Find all categories that match search criteria
* description: Find all categories that match search criteria
* responses:
* 200:
* description: Categories list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Categories"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await CategoriesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/categories/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Categories]
* 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/Categories"
* 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 CategoriesDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

View File

@ -0,0 +1,433 @@
const express = require('express');
const DisputesService = require('../services/disputes');
const DisputesDBApi = require('../db/api/disputes');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('disputes'));
/**
* @swagger
* components:
* schemas:
* Disputes:
* type: object
* properties:
* reason:
* type: string
* default: reason
* resolution_notes:
* type: string
* default: resolution_notes
*
*/
/**
* @swagger
* tags:
* name: Disputes
* description: The Disputes managing API
*/
/**
* @swagger
* /api/disputes:
* post:
* security:
* - bearerAuth: []
* tags: [Disputes]
* 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/Disputes"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Disputes"
* 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 DisputesService.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: [Disputes]
* 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/Disputes"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Disputes"
* 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 DisputesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/disputes/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Disputes]
* 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/Disputes"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Disputes"
* 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 DisputesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/disputes/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Disputes]
* 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/Disputes"
* 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 DisputesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/disputes/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Disputes]
* 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/Disputes"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await DisputesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/disputes:
* get:
* security:
* - bearerAuth: []
* tags: [Disputes]
* summary: Get all disputes
* description: Get all disputes
* responses:
* 200:
* description: Disputes list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Disputes"
* 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 DisputesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','reason','resolution_notes',
'created_at_ts','updated_at_ts',
];
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/disputes/count:
* get:
* security:
* - bearerAuth: []
* tags: [Disputes]
* summary: Count all disputes
* description: Count all disputes
* responses:
* 200:
* description: Disputes count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Disputes"
* 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 DisputesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/disputes/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Disputes]
* summary: Find all disputes that match search criteria
* description: Find all disputes that match search criteria
* responses:
* 200:
* description: Disputes list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Disputes"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await DisputesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/disputes/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Disputes]
* 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/Disputes"
* 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 DisputesDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

@ -0,0 +1,436 @@
const express = require('express');
const Lead_eventsService = require('../services/lead_events');
const Lead_eventsDBApi = require('../db/api/lead_events');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('lead_events'));
/**
* @swagger
* components:
* schemas:
* Lead_events:
* type: object
* properties:
* from_value:
* type: string
* default: from_value
* to_value:
* type: string
* default: to_value
* meta_json:
* type: string
* default: meta_json
*
*/
/**
* @swagger
* tags:
* name: Lead_events
* description: The Lead_events managing API
*/
/**
* @swagger
* /api/lead_events:
* post:
* security:
* - bearerAuth: []
* tags: [Lead_events]
* 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/Lead_events"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Lead_events"
* 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 Lead_eventsService.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: [Lead_events]
* 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/Lead_events"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Lead_events"
* 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 Lead_eventsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_events/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Lead_events]
* 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/Lead_events"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Lead_events"
* 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 Lead_eventsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_events/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Lead_events]
* 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/Lead_events"
* 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 Lead_eventsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_events/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Lead_events]
* 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/Lead_events"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Lead_eventsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_events:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_events]
* summary: Get all lead_events
* description: Get all lead_events
* responses:
* 200:
* description: Lead_events list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Lead_events"
* 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 Lead_eventsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','from_value','to_value','meta_json',
'created_at_ts',
];
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/lead_events/count:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_events]
* summary: Count all lead_events
* description: Count all lead_events
* responses:
* 200:
* description: Lead_events count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Lead_events"
* 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 Lead_eventsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_events/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_events]
* summary: Find all lead_events that match search criteria
* description: Find all lead_events that match search criteria
* responses:
* 200:
* description: Lead_events list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Lead_events"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Lead_eventsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/lead_events/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_events]
* 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/Lead_events"
* 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 Lead_eventsDBApi.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 Lead_matchesService = require('../services/lead_matches');
const Lead_matchesDBApi = require('../db/api/lead_matches');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('lead_matches'));
/**
* @swagger
* components:
* schemas:
* Lead_matches:
* type: object
* properties:
* match_score:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Lead_matches
* description: The Lead_matches managing API
*/
/**
* @swagger
* /api/lead_matches:
* post:
* security:
* - bearerAuth: []
* tags: [Lead_matches]
* 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/Lead_matches"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Lead_matches"
* 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 Lead_matchesService.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: [Lead_matches]
* 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/Lead_matches"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Lead_matches"
* 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 Lead_matchesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_matches/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Lead_matches]
* 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/Lead_matches"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Lead_matches"
* 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 Lead_matchesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_matches/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Lead_matches]
* 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/Lead_matches"
* 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 Lead_matchesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_matches/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Lead_matches]
* 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/Lead_matches"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Lead_matchesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_matches:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_matches]
* summary: Get all lead_matches
* description: Get all lead_matches
* responses:
* 200:
* description: Lead_matches list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Lead_matches"
* 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 Lead_matchesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id',
'match_score',
'sent_at','viewed_at','responded_at','scheduled_at','completed_at','declined_at','created_at_ts','updated_at_ts',
];
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/lead_matches/count:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_matches]
* summary: Count all lead_matches
* description: Count all lead_matches
* responses:
* 200:
* description: Lead_matches count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Lead_matches"
* 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 Lead_matchesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_matches/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_matches]
* summary: Find all lead_matches that match search criteria
* description: Find all lead_matches that match search criteria
* responses:
* 200:
* description: Lead_matches list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Lead_matches"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Lead_matchesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/lead_matches/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_matches]
* 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/Lead_matches"
* 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 Lead_matchesDBApi.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 Lead_photosService = require('../services/lead_photos');
const Lead_photosDBApi = require('../db/api/lead_photos');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('lead_photos'));
/**
* @swagger
* components:
* schemas:
* Lead_photos:
* type: object
* properties:
*/
/**
* @swagger
* tags:
* name: Lead_photos
* description: The Lead_photos managing API
*/
/**
* @swagger
* /api/lead_photos:
* post:
* security:
* - bearerAuth: []
* tags: [Lead_photos]
* 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/Lead_photos"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Lead_photos"
* 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 Lead_photosService.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: [Lead_photos]
* 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/Lead_photos"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Lead_photos"
* 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 Lead_photosService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_photos/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Lead_photos]
* 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/Lead_photos"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Lead_photos"
* 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 Lead_photosService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_photos/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Lead_photos]
* 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/Lead_photos"
* 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 Lead_photosService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_photos/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Lead_photos]
* 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/Lead_photos"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Lead_photosService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_photos:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_photos]
* summary: Get all lead_photos
* description: Get all lead_photos
* responses:
* 200:
* description: Lead_photos list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Lead_photos"
* 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 Lead_photosDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id',
'created_at_ts',
];
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/lead_photos/count:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_photos]
* summary: Count all lead_photos
* description: Count all lead_photos
* responses:
* 200:
* description: Lead_photos count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Lead_photos"
* 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 Lead_photosDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/lead_photos/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_photos]
* summary: Find all lead_photos that match search criteria
* description: Find all lead_photos that match search criteria
* responses:
* 200:
* description: Lead_photos list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Lead_photos"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Lead_photosDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/lead_photos/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Lead_photos]
* 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/Lead_photos"
* 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 Lead_photosDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

467
backend/src/routes/leads.js Normal file
View File

@ -0,0 +1,467 @@
const express = require('express');
const LeadsService = require('../services/leads');
const LeadsDBApi = require('../db/api/leads');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('leads'));
/**
* @swagger
* components:
* schemas:
* Leads:
* type: object
* properties:
* keyword:
* type: string
* default: keyword
* description:
* type: string
* default: description
* contact_name:
* type: string
* default: contact_name
* contact_phone:
* type: string
* default: contact_phone
* contact_email:
* type: string
* default: contact_email
* address:
* type: string
* default: address
* city:
* type: string
* default: city
* state:
* type: string
* default: state
* zip:
* type: string
* default: zip
* inferred_tags_json:
* type: string
* default: inferred_tags_json
* tenant_key:
* type: string
* default: tenant_key
* lat:
* type: integer
* format: int64
* lng:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Leads
* description: The Leads managing API
*/
/**
* @swagger
* /api/leads:
* post:
* security:
* - bearerAuth: []
* tags: [Leads]
* 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/Leads"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Leads"
* 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 LeadsService.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: [Leads]
* 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/Leads"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Leads"
* 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 LeadsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/leads/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Leads]
* 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/Leads"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Leads"
* 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 LeadsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/leads/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Leads]
* 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/Leads"
* 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 LeadsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/leads/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Leads]
* 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/Leads"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await LeadsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/leads:
* get:
* security:
* - bearerAuth: []
* tags: [Leads]
* summary: Get all leads
* description: Get all leads
* responses:
* 200:
* description: Leads list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Leads"
* 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 LeadsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','keyword','description','contact_name','contact_phone','contact_email','address','city','state','zip','inferred_tags_json','tenant_key',
'lat','lng',
'created_at_ts','updated_at_ts',
];
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/leads/count:
* get:
* security:
* - bearerAuth: []
* tags: [Leads]
* summary: Count all leads
* description: Count all leads
* responses:
* 200:
* description: Leads count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Leads"
* 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 LeadsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/leads/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Leads]
* summary: Find all leads that match search criteria
* description: Find all leads that match search criteria
* responses:
* 200:
* description: Leads list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Leads"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await LeadsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/leads/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Leads]
* 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/Leads"
* 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 LeadsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,447 @@
const express = require('express');
const LocationsService = require('../services/locations');
const LocationsDBApi = require('../db/api/locations');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('locations'));
/**
* @swagger
* components:
* schemas:
* Locations:
* type: object
* properties:
* label:
* type: string
* default: label
* city:
* type: string
* default: city
* state:
* type: string
* default: state
* zip:
* type: string
* default: zip
* tenant_key:
* type: string
* default: tenant_key
* lat:
* type: integer
* format: int64
* lng:
* type: integer
* format: int64
*/
/**
* @swagger
* tags:
* name: Locations
* description: The Locations managing API
*/
/**
* @swagger
* /api/locations:
* post:
* security:
* - bearerAuth: []
* tags: [Locations]
* 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/Locations"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Locations"
* 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 LocationsService.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: [Locations]
* 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/Locations"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Locations"
* 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 LocationsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/locations/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Locations]
* 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/Locations"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Locations"
* 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 LocationsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/locations/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Locations]
* 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/Locations"
* 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 LocationsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/locations/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Locations]
* 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/Locations"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await LocationsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/locations:
* get:
* security:
* - bearerAuth: []
* tags: [Locations]
* summary: Get all locations
* description: Get all locations
* responses:
* 200:
* description: Locations list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Locations"
* 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 LocationsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','label','city','state','zip','tenant_key',
'lat','lng',
'created_at_ts',
];
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/locations/count:
* get:
* security:
* - bearerAuth: []
* tags: [Locations]
* summary: Count all locations
* description: Count all locations
* responses:
* 200:
* description: Locations count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Locations"
* 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 LocationsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/locations/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Locations]
* summary: Find all locations that match search criteria
* description: Find all locations that match search criteria
* responses:
* 200:
* description: Locations list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Locations"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await LocationsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/locations/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Locations]
* 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/Locations"
* 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 LocationsDBApi.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 MessagesService = require('../services/messages');
const MessagesDBApi = require('../db/api/messages');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('messages'));
/**
* @swagger
* components:
* schemas:
* Messages:
* type: object
* properties:
* body:
* type: string
* default: body
*/
/**
* @swagger
* tags:
* name: Messages
* description: The Messages managing API
*/
/**
* @swagger
* /api/messages:
* post:
* security:
* - bearerAuth: []
* tags: [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/Messages"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/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 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: [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/Messages"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/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 MessagesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/messages/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [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/Messages"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/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 MessagesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/messages/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [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/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 MessagesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/messages/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [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/Messages"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await MessagesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/messages:
* get:
* security:
* - bearerAuth: []
* tags: [Messages]
* summary: Get all messages
* description: Get all messages
* responses:
* 200:
* description: Messages list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/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 MessagesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','body',
'read_at','created_at_ts',
];
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/messages/count:
* get:
* security:
* - bearerAuth: []
* tags: [Messages]
* summary: Count all messages
* description: Count all messages
* responses:
* 200:
* description: Messages count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/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 MessagesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/messages/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Messages]
* summary: Find all messages that match search criteria
* description: Find all messages that match search criteria
* responses:
* 200:
* description: Messages list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/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 MessagesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/messages/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [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/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 MessagesDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,328 @@
const express = require('express');
const db = require('../db/models');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const sjs = require('sequelize-json-schema');
const { getWidget, askGpt } = require('../services/openai');
const { LocalAIApi } = require('../ai/LocalAIApi');
const loadRolesModules = () => {
try {
return {
RolesService: require('../services/roles'),
RolesDBApi: require('../db/api/roles'),
};
} catch (error) {
console.error('Roles modules are missing. Advanced roles are required for this endpoint.', error);
const err = new Error('Roles modules are missing. Advanced roles are required for this endpoint.');
err.originalError = error;
throw err;
}
};
/**
* @swagger
* /api/roles/roles-info/{infoId}:
* delete:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Remove role information by ID
* description: Remove specific role information by ID
* parameters:
* - in: path
* name: infoId
* description: ID of role information to remove
* required: true
* schema:
* type: string
* - in: query
* name: userId
* description: ID of the user
* required: true
* schema:
* type: string
* - in: query
* name: key
* description: Key of the role information to remove
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Role information successfully removed
* content:
* application/json:
* schema:
* type: object
* properties:
* user:
* type: string
* description: The user information
* 400:
* description: Invalid ID or key supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Role not found
* 500:
* description: Some server error
*/
router.delete(
'/roles-info/:infoId',
wrapAsync(async (req, res) => {
const { RolesService } = loadRolesModules();
const role = await RolesService.removeRoleInfoById(
req.query.infoId,
req.query.roleId,
req.query.key,
req.currentUser,
);
res.status(200).send(role);
}),
);
/**
* @swagger
* /api/roles/role-info/{roleId}:
* get:
* security:
* - bearerAuth: []
* tags: [Roles]
* summary: Get role information by key
* description: Get specific role information by key
* parameters:
* - in: path
* name: roleId
* description: ID of role to get information for
* required: true
* schema:
* type: string
* - in: query
* name: key
* description: Key of the role information to retrieve
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Role information successfully received
* content:
* application/json:
* schema:
* type: object
* properties:
* info:
* type: string
* description: The role information
* 400:
* description: Invalid ID or key supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Role not found
* 500:
* description: Some server error
*/
router.get(
'/info-by-key',
wrapAsync(async (req, res) => {
const { RolesService, RolesDBApi } = loadRolesModules();
const roleId = req.query.roleId;
const key = req.query.key;
const currentUser = req.currentUser;
let info = await RolesService.getRoleInfoByKey(
key,
roleId,
currentUser,
);
const role = await RolesDBApi.findBy({ id: roleId });
if (!role?.role_customization) {
await Promise.all(["pie", "bar"].map(async (e) => {
const schema = await sjs.getSequelizeSchema(db.sequelize, {});
const payload = {
description: `Create some cool ${e} chart`,
modelDefinition: schema.definitions,
};
const widgetId = await getWidget(payload, currentUser?.id, roleId);
if (widgetId) {
await RolesService.addRoleInfo(
roleId,
currentUser?.id,
'widgets',
widgetId,
req.currentUser,
);
}
}))
info = await RolesService.getRoleInfoByKey(
key,
roleId,
currentUser,
);
}
res.status(200).send(info);
}),
);
router.post(
'/create_widget',
wrapAsync(async (req, res) => {
const { RolesService } = loadRolesModules();
const { description, userId, roleId } = req.body;
const currentUser = req.currentUser;
const schema = await sjs.getSequelizeSchema(db.sequelize, {});
const payload = {
description,
modelDefinition: schema.definitions,
};
const widgetId = await getWidget(payload, userId, roleId);
if (widgetId) {
await RolesService.addRoleInfo(
roleId,
userId,
'widgets',
widgetId,
currentUser,
);
return res.status(200).send(widgetId);
} else {
return res.status(400).send(widgetId);
}
}),
);
/**
* @swagger
* /api/openai/response:
* post:
* security:
* - bearerAuth: []
* tags: [OpenAI]
* summary: Proxy a Responses API request
* description: Sends the payload to the Flatlogic AI proxy and returns the response.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* input:
* type: array
* description: List of messages with roles and content.
* items:
* type: object
* properties:
* role:
* type: string
* content:
* type: string
* options:
* type: object
* description: Optional polling controls.
* properties:
* poll_interval:
* type: number
* poll_timeout:
* type: number
* responses:
* 200:
* description: AI response received
* 400:
* description: Invalid request
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 502:
* description: Proxy error
*/
router.post(
'/response',
wrapAsync(async (req, res) => {
const body = req.body || {};
const options = body.options || {};
const payload = { ...body };
delete payload.options;
const response = await LocalAIApi.createResponse(payload, options);
if (response.success) {
return res.status(200).send(response);
}
console.error('AI proxy error:', response);
const status = response.error === 'input_missing' ? 400 : 502;
return res.status(status).send(response);
}),
);
/**
* @swagger
* /api/openai/ask:
* post:
* security:
* - bearerAuth: []
* tags: [OpenAI]
* summary: Ask a question to ChatGPT
* description: Send a question through the Flatlogic AI proxy and get a response
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* prompt:
* type: string
* description: The question to ask ChatGPT
* responses:
* 200:
* description: Question successfully answered
* content:
* application/json:
* schema:
* type: object
* properties:
* success:
* type: boolean
* description: Whether the request was successful
* data:
* type: string
* description: The answer from ChatGPT
* 400:
* description: Invalid request
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 500:
* description: Some server error
*/
router.post(
'/ask-gpt',
wrapAsync(async (req, res) => {
const { prompt } = req.body;
if (!prompt) {
return res.status(400).send({
success: false,
error: 'Prompt is required',
});
}
const response = await askGpt(prompt);
if (response.success) {
return res.status(200).send(response);
} else {
return res.status(500).send(response);
}
}),
);
module.exports = router;

View File

@ -0,0 +1,2 @@

View File

@ -0,0 +1,429 @@
const express = require('express');
const PermissionsService = require('../services/permissions');
const PermissionsDBApi = require('../db/api/permissions');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('permissions'));
/**
* @swagger
* components:
* schemas:
* Permissions:
* type: object
* properties:
* name:
* type: string
* default: name
*/
/**
* @swagger
* tags:
* name: Permissions
* description: The Permissions managing API
*/
/**
* @swagger
* /api/permissions:
* post:
* security:
* - bearerAuth: []
* tags: [Permissions]
* 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/Permissions"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Permissions"
* 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 PermissionsService.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: [Permissions]
* 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/Permissions"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Permissions"
* 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 PermissionsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/permissions/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Permissions]
* 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/Permissions"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Permissions"
* 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 PermissionsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/permissions/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Permissions]
* 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/Permissions"
* 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 PermissionsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/permissions/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Permissions]
* 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/Permissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await PermissionsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/permissions:
* get:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Get all permissions
* description: Get all permissions
* responses:
* 200:
* description: Permissions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Permissions"
* 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 PermissionsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name',
];
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/permissions/count:
* get:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Count all permissions
* description: Count all permissions
* responses:
* 200:
* description: Permissions count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Permissions"
* 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 PermissionsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/permissions/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Permissions]
* summary: Find all permissions that match search criteria
* description: Find all permissions that match search criteria
* responses:
* 200:
* description: Permissions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Permissions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await PermissionsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/permissions/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Permissions]
* 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/Permissions"
* 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 PermissionsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,104 @@
const express = require('express');
const router = express.Router();
const { pexelsKey, pexelsQuery } = require('../config');
const fetch = require('node-fetch');
const KEY = pexelsKey;
router.get('/image', async (req, res) => {
const headers = {
Authorization: `${KEY}`,
};
const query = pexelsQuery || 'nature';
const orientation = 'portrait';
const perPage = 1;
const url = `https://api.pexels.com/v1/search?query=${query}&orientation=${orientation}&per_page=${perPage}&page=1`;
try {
const response = await fetch(url, { headers });
const data = await response.json();
res.status(200).json(data.photos[0]);
} catch (error) {
res.status(200).json({ error: 'Failed to fetch image' });
}
});
router.get('/video', async (req, res) => {
const headers = {
Authorization: `${KEY}`,
};
const query = pexelsQuery || 'nature';
const orientation = 'portrait';
const perPage = 1;
const url = `https://api.pexels.com/videos/search?query=${query}&orientation=${orientation}&per_page=${perPage}&page=1`;
try {
const response = await fetch(url, { headers });
const data = await response.json();
res.status(200).json(data.videos[0]);
} catch (error) {
res.status(200).json({ error: 'Failed to fetch video' });
}
});
router.get('/multiple-images', async (req, res) => {
const headers = {
Authorization: `${KEY}`,
};
const queries = req.query.queries
? req.query.queries.split(',')
: ['home', 'apple', 'pizza', 'mountains', 'cat'];
const orientation = 'square';
const perPage = 1;
const fallbackImage = {
src: 'https://images.pexels.com/photos/8199252/pexels-photo-8199252.jpeg',
photographer: 'Yan Krukau',
photographer_url: 'https://www.pexels.com/@yankrukov',
};
const fetchFallbackImage = async () => {
try {
const response = await fetch('https://picsum.photos/600');
return {
src: response.url,
photographer: 'Random Picsum',
photographer_url: 'https://picsum.photos/',
};
} catch (error) {
return fallbackImage;
}
};
const fetchImage = async (query) => {
const url = `https://api.pexels.com/v1/search?query=${query}&orientation=${orientation}&per_page=${perPage}&page=1`;
const response = await fetch(url, { headers });
const data = await response.json();
return data.photos[0] || null;
};
const imagePromises = queries.map((query) => fetchImage(query));
const imagesResults = await Promise.allSettled(imagePromises);
const formattedImages = await Promise.all(imagesResults.map(async (result) => {
if (result.status === 'fulfilled' && result.value) {
const image = result.value;
return {
src: image.src?.original || fallbackImage.src,
photographer: image.photographer || fallbackImage.photographer,
photographer_url: image.photographer_url || fallbackImage.photographer_url,
};
} else {
const fallback = await fetchFallbackImage();
return {
src: fallback.src || '',
photographer: fallback.photographer || 'Unknown',
photographer_url: fallback.photographer_url || '',
};
}
}));
res.json(formattedImages);
});
module.exports = router;

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