Initial version

This commit is contained in:
Flatlogic Bot 2026-02-22 15:41:40 +00:00
commit ede4c56765
509 changed files with 148184 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>AI Customer Success Guardian</h2>
<p>AI-powered omnichannel support with RAG answers, auto tickets, escalation alerts, and customer health scoring.</p>
</div>
<div class="loader-container">
<img src="https://flatlogic.com/blog/wp-content/uploads/2025/05/logo-bot-1.png" alt="App Logo"
class="app-logo">
<div class="loader"></div>
</div>
<div class="panel">
<video width="100%" height="315" controls loop>
<source
src="https://flatlogic.com/blog/wp-content/uploads/2025/04/20250430_1336_professional_dynamo_spinner_simple_compose_01jt349yvtenxt7xhg8hhr85j8.mp4"
type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
<script>
function checkAvailability() {
fetch('/')
.then(response => {
if (response.ok) {
window.location.reload();
} else {
setTimeout(checkAvailability, 5000);
}
})
.catch(() => {
setTimeout(checkAvailability, 5000);
});
}
document.addEventListener('DOMContentLoaded', checkAvailability);
document.addEventListener('DOMContentLoaded', function () {
const appTitle = document.querySelector('#status-heading');
const panel = document.querySelector('.panel');
const video = panel.querySelector('video');
let clickCount = 0;
appTitle.addEventListener('click', function () {
clickCount++;
if (clickCount === 5) {
panel.classList.toggle('show');
if (panel.classList.contains('show')) {
video.play();
} else {
video.pause();
}
clickCount = 0;
}
});
});
</script>
</body>
</html>

21
Dockerfile Normal file
View File

@ -0,0 +1,21 @@
FROM node:20.15.1-alpine AS builder
RUN apk add --no-cache git
WORKDIR /app
COPY frontend/package.json frontend/yarn.lock ./
RUN yarn install --pure-lockfile
COPY frontend .
RUN yarn build
FROM node:20.15.1-alpine
WORKDIR /app
COPY backend/package.json backend/yarn.lock ./
RUN yarn install --pure-lockfile
COPY backend .
COPY --from=builder /app/build /app/public
CMD ["yarn", "start"]

85
Dockerfile.dev Normal file
View File

@ -0,0 +1,85 @@
# Base image for Node.js dependencies
FROM node:20.15.1-alpine AS frontend-deps
RUN apk add --no-cache git
WORKDIR /app/frontend
COPY frontend/package.json frontend/yarn.lock ./
RUN yarn install --pure-lockfile
FROM node:20.15.1-alpine AS backend-deps
RUN apk add --no-cache git
WORKDIR /app/backend
COPY backend/package.json backend/yarn.lock ./
RUN yarn install --pure-lockfile
FROM node:20.15.1-alpine AS app-shell-deps
RUN apk add --no-cache git
WORKDIR /app/app-shell
COPY app-shell/package.json app-shell/yarn.lock ./
RUN yarn install --pure-lockfile
# Nginx setup and application build
FROM node:20.15.1-alpine AS build
RUN apk add --no-cache git nginx curl
RUN apk add --no-cache lsof procps
RUN yarn global add concurrently
RUN apk add --no-cache \
chromium \
nss \
freetype \
harfbuzz \
ttf-freefont \
fontconfig
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
RUN mkdir -p /app/pids
# Make sure to add yarn global bin to PATH
ENV PATH /root/.yarn/bin:/root/.config/yarn/global/node_modules/.bin:$PATH
# Copy dependencies
WORKDIR /app
COPY --from=frontend-deps /app/frontend /app/frontend
COPY --from=backend-deps /app/backend /app/backend
COPY --from=app-shell-deps /app/app-shell /app/app-shell
COPY frontend /app/frontend
COPY backend /app/backend
COPY app-shell /app/app-shell
COPY docker /app/docker
# Copy all files from root to /app
COPY . /app
# Copy Nginx configuration
COPY nginx.conf /etc/nginx/nginx.conf
# Copy custom error page
COPY 502.html /usr/share/nginx/html/502.html
# Change owner and permissions of the error page
RUN chown nginx:nginx /usr/share/nginx/html/502.html && \
chmod 644 /usr/share/nginx/html/502.html
# Expose the port the app runs on
EXPOSE 8080
ENV NODE_ENV=dev_stage
ENV FRONT_PORT=3001
ENV BACKEND_PORT=3000
ENV APP_SHELL_PORT=4000
CMD ["sh", "-c", "\
yarn --cwd /app/frontend dev & echo $! > /app/pids/frontend.pid && \
yarn --cwd /app/backend start & echo $! > /app/pids/backend.pid && \
sleep 10 && nginx -g 'daemon off;' & \
NGINX_PID=$! && \
echo 'Waiting for backend (port 3000) to be available...' && \
while ! nc -z localhost ${BACKEND_PORT}; do \
sleep 2; \
done && \
echo 'Backend is up. Starting app_shell for Git check...' && \
yarn --cwd /app/app-shell start && \
wait $NGINX_PID"]

1
LICENSE Normal file
View File

@ -0,0 +1 @@
https://flatlogic.com/

244
README.md Normal file
View File

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

14
backend/.env Normal file
View File

@ -0,0 +1,14 @@
DB_NAME=app_38689
DB_USER=app_38689
DB_PASS=694e8975-f096-4d84-b402-2b6b731d0ad6
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 @@
#AI Customer Success Guardian - 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_ai_customer_success_guardian;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_ai_customer_success_guardian 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": "aicustomersuccessguardian",
"description": "AI Customer Success Guardian - 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: "694e8975",
user_pass: "2b6b731d0ad6",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '694e8975-f096-4d84-b402-2b6b731d0ad6',
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: 'AI Customer Success Guardian <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: 'Customer',
},
project_uuid: '694e8975-f096-4d84-b402-2b6b731d0ad6',
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 = 'Lighthouse guiding ships at night';
config.host = process.env.NODE_ENV === "production" ? config.remote : "http://localhost";
config.apiUrl = `${config.host}${config.port ? `:${config.port}` : ``}/api`;
config.swaggerUrl = `${config.swaggerUI}${config.swaggerPort}`;
config.uiUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}/#`;
config.backUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}`;
module.exports = config;

View File

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

View File

@ -0,0 +1,700 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Ai_runsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_runs = await db.ai_runs.create(
{
id: data.id || undefined,
run_type: data.run_type
||
null
,
started_at: data.started_at
||
null
,
finished_at: data.finished_at
||
null
,
status: data.status
||
null
,
prompt_preview: data.prompt_preview
||
null
,
response_preview: data.response_preview
||
null
,
prompt_tokens: data.prompt_tokens
||
null
,
completion_tokens: data.completion_tokens
||
null
,
total_cost: data.total_cost
||
null
,
error_message: data.error_message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_runs.setConversation( data.conversation || null, {
transaction,
});
await ai_runs.setModel( data.model || null, {
transaction,
});
return ai_runs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const ai_runsData = data.map((item, index) => ({
id: item.id || undefined,
run_type: item.run_type
||
null
,
started_at: item.started_at
||
null
,
finished_at: item.finished_at
||
null
,
status: item.status
||
null
,
prompt_preview: item.prompt_preview
||
null
,
response_preview: item.response_preview
||
null
,
prompt_tokens: item.prompt_tokens
||
null
,
completion_tokens: item.completion_tokens
||
null
,
total_cost: item.total_cost
||
null
,
error_message: item.error_message
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ai_runs = await db.ai_runs.bulkCreate(ai_runsData, { transaction });
// For each item created, replace relation files
return ai_runs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_runs = await db.ai_runs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.run_type !== undefined) updatePayload.run_type = data.run_type;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.prompt_preview !== undefined) updatePayload.prompt_preview = data.prompt_preview;
if (data.response_preview !== undefined) updatePayload.response_preview = data.response_preview;
if (data.prompt_tokens !== undefined) updatePayload.prompt_tokens = data.prompt_tokens;
if (data.completion_tokens !== undefined) updatePayload.completion_tokens = data.completion_tokens;
if (data.total_cost !== undefined) updatePayload.total_cost = data.total_cost;
if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
updatePayload.updatedById = currentUser.id;
await ai_runs.update(updatePayload, {transaction});
if (data.conversation !== undefined) {
await ai_runs.setConversation(
data.conversation,
{ transaction }
);
}
if (data.model !== undefined) {
await ai_runs.setModel(
data.model,
{ transaction }
);
}
return ai_runs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_runs = await db.ai_runs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ai_runs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ai_runs) {
await record.destroy({transaction});
}
});
return ai_runs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_runs = await db.ai_runs.findByPk(id, options);
await ai_runs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ai_runs.destroy({
transaction
});
return ai_runs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ai_runs = await db.ai_runs.findOne(
{ where },
{ transaction },
);
if (!ai_runs) {
return ai_runs;
}
const output = ai_runs.get({plain: true});
output.conversation_messages_ai_run = await ai_runs.getConversation_messages_ai_run({
transaction
});
output.rag_queries_ai_run = await ai_runs.getRag_queries_ai_run({
transaction
});
output.conversation = await ai_runs.getConversation({
transaction
});
output.model = await ai_runs.getModel({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.conversations,
as: 'conversation',
where: filter.conversation ? {
[Op.or]: [
{ id: { [Op.in]: filter.conversation.split('|').map(term => Utils.uuid(term)) } },
{
case_reference: {
[Op.or]: filter.conversation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.ai_models,
as: 'model',
where: filter.model ? {
[Op.or]: [
{ id: { [Op.in]: filter.model.split('|').map(term => Utils.uuid(term)) } },
{
model_name: {
[Op.or]: filter.model.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.prompt_preview) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_runs',
'prompt_preview',
filter.prompt_preview,
),
};
}
if (filter.response_preview) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_runs',
'response_preview',
filter.response_preview,
),
};
}
if (filter.error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_runs',
'error_message',
filter.error_message,
),
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.finished_atRange) {
const [start, end] = filter.finished_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.lte]: end,
},
};
}
}
if (filter.prompt_tokensRange) {
const [start, end] = filter.prompt_tokensRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
prompt_tokens: {
...where.prompt_tokens,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
prompt_tokens: {
...where.prompt_tokens,
[Op.lte]: end,
},
};
}
}
if (filter.completion_tokensRange) {
const [start, end] = filter.completion_tokensRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completion_tokens: {
...where.completion_tokens,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completion_tokens: {
...where.completion_tokens,
[Op.lte]: end,
},
};
}
}
if (filter.total_costRange) {
const [start, end] = filter.total_costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_cost: {
...where.total_cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_cost: {
...where.total_cost,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.run_type) {
where = {
...where,
run_type: filter.run_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.ai_runs.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(
'ai_runs',
'run_type',
query,
),
],
};
}
const records = await db.ai_runs.findAll({
attributes: [ 'id', 'run_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['run_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.run_type,
}));
}
};

View File

@ -0,0 +1,730 @@
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 Conversation_messagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const conversation_messages = await db.conversation_messages.create(
{
id: data.id || undefined,
sender_type: data.sender_type
||
null
,
sent_at: data.sent_at
||
null
,
message_kind: data.message_kind
||
null
,
content: data.content
||
null
,
sentiment_score: data.sentiment_score
||
null
,
sentiment_label: data.sentiment_label
||
null
,
toxicity_score: data.toxicity_score
||
null
,
detected_intent: data.detected_intent
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await conversation_messages.setConversation( data.conversation || null, {
transaction,
});
await conversation_messages.setSender_user( data.sender_user || null, {
transaction,
});
await conversation_messages.setKnowledge_article_used( data.knowledge_article_used || null, {
transaction,
});
await conversation_messages.setAi_run( data.ai_run || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.conversation_messages.getTableName(),
belongsToColumn: 'attachments',
belongsToId: conversation_messages.id,
},
data.attachments,
options,
);
return conversation_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 conversation_messagesData = data.map((item, index) => ({
id: item.id || undefined,
sender_type: item.sender_type
||
null
,
sent_at: item.sent_at
||
null
,
message_kind: item.message_kind
||
null
,
content: item.content
||
null
,
sentiment_score: item.sentiment_score
||
null
,
sentiment_label: item.sentiment_label
||
null
,
toxicity_score: item.toxicity_score
||
null
,
detected_intent: item.detected_intent
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const conversation_messages = await db.conversation_messages.bulkCreate(conversation_messagesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < conversation_messages.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.conversation_messages.getTableName(),
belongsToColumn: 'attachments',
belongsToId: conversation_messages[i].id,
},
data[i].attachments,
options,
);
}
return conversation_messages;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const conversation_messages = await db.conversation_messages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.sender_type !== undefined) updatePayload.sender_type = data.sender_type;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.message_kind !== undefined) updatePayload.message_kind = data.message_kind;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.sentiment_score !== undefined) updatePayload.sentiment_score = data.sentiment_score;
if (data.sentiment_label !== undefined) updatePayload.sentiment_label = data.sentiment_label;
if (data.toxicity_score !== undefined) updatePayload.toxicity_score = data.toxicity_score;
if (data.detected_intent !== undefined) updatePayload.detected_intent = data.detected_intent;
updatePayload.updatedById = currentUser.id;
await conversation_messages.update(updatePayload, {transaction});
if (data.conversation !== undefined) {
await conversation_messages.setConversation(
data.conversation,
{ transaction }
);
}
if (data.sender_user !== undefined) {
await conversation_messages.setSender_user(
data.sender_user,
{ transaction }
);
}
if (data.knowledge_article_used !== undefined) {
await conversation_messages.setKnowledge_article_used(
data.knowledge_article_used,
{ transaction }
);
}
if (data.ai_run !== undefined) {
await conversation_messages.setAi_run(
data.ai_run,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.conversation_messages.getTableName(),
belongsToColumn: 'attachments',
belongsToId: conversation_messages.id,
},
data.attachments,
options,
);
return conversation_messages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const conversation_messages = await db.conversation_messages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of conversation_messages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of conversation_messages) {
await record.destroy({transaction});
}
});
return conversation_messages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const conversation_messages = await db.conversation_messages.findByPk(id, options);
await conversation_messages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await conversation_messages.destroy({
transaction
});
return conversation_messages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const conversation_messages = await db.conversation_messages.findOne(
{ where },
{ transaction },
);
if (!conversation_messages) {
return conversation_messages;
}
const output = conversation_messages.get({plain: true});
output.conversation = await conversation_messages.getConversation({
transaction
});
output.sender_user = await conversation_messages.getSender_user({
transaction
});
output.attachments = await conversation_messages.getAttachments({
transaction
});
output.knowledge_article_used = await conversation_messages.getKnowledge_article_used({
transaction
});
output.ai_run = await conversation_messages.getAi_run({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.conversations,
as: 'conversation',
where: filter.conversation ? {
[Op.or]: [
{ id: { [Op.in]: filter.conversation.split('|').map(term => Utils.uuid(term)) } },
{
case_reference: {
[Op.or]: filter.conversation.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.knowledge_articles,
as: 'knowledge_article_used',
where: filter.knowledge_article_used ? {
[Op.or]: [
{ id: { [Op.in]: filter.knowledge_article_used.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.knowledge_article_used.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.ai_runs,
as: 'ai_run',
where: filter.ai_run ? {
[Op.or]: [
{ id: { [Op.in]: filter.ai_run.split('|').map(term => Utils.uuid(term)) } },
{
run_type: {
[Op.or]: filter.ai_run.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'conversation_messages',
'content',
filter.content,
),
};
}
if (filter.detected_intent) {
where = {
...where,
[Op.and]: Utils.ilike(
'conversation_messages',
'detected_intent',
filter.detected_intent,
),
};
}
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.sentiment_scoreRange) {
const [start, end] = filter.sentiment_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sentiment_score: {
...where.sentiment_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sentiment_score: {
...where.sentiment_score,
[Op.lte]: end,
},
};
}
}
if (filter.toxicity_scoreRange) {
const [start, end] = filter.toxicity_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
toxicity_score: {
...where.toxicity_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
toxicity_score: {
...where.toxicity_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.sender_type) {
where = {
...where,
sender_type: filter.sender_type,
};
}
if (filter.message_kind) {
where = {
...where,
message_kind: filter.message_kind,
};
}
if (filter.sentiment_label) {
where = {
...where,
sentiment_label: filter.sentiment_label,
};
}
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.conversation_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(
'conversation_messages',
'content',
query,
),
],
};
}
const records = await db.conversation_messages.findAll({
attributes: [ 'id', 'content' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['content', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.content,
}));
}
};

View File

@ -0,0 +1,837 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ConversationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const conversations = await db.conversations.create(
{
id: data.id || undefined,
case_reference: data.case_reference
||
null
,
state: data.state
||
null
,
priority: data.priority
||
null
,
started_at: data.started_at
||
null
,
ended_at: data.ended_at
||
null
,
current_sentiment_score: data.current_sentiment_score
||
null
,
sentiment_label: data.sentiment_label
||
null
,
frustration_score: data.frustration_score
||
null
,
escalated: data.escalated
||
false
,
last_message_at: data.last_message_at
||
null
,
customer_intent: data.customer_intent
||
null
,
topic: data.topic
||
null
,
resolution_summary: data.resolution_summary
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await conversations.setChannel( data.channel || null, {
transaction,
});
await conversations.setCustomer_account( data.customer_account || null, {
transaction,
});
await conversations.setCustomer_user( data.customer_user || null, {
transaction,
});
return conversations;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const conversationsData = data.map((item, index) => ({
id: item.id || undefined,
case_reference: item.case_reference
||
null
,
state: item.state
||
null
,
priority: item.priority
||
null
,
started_at: item.started_at
||
null
,
ended_at: item.ended_at
||
null
,
current_sentiment_score: item.current_sentiment_score
||
null
,
sentiment_label: item.sentiment_label
||
null
,
frustration_score: item.frustration_score
||
null
,
escalated: item.escalated
||
false
,
last_message_at: item.last_message_at
||
null
,
customer_intent: item.customer_intent
||
null
,
topic: item.topic
||
null
,
resolution_summary: item.resolution_summary
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const conversations = await db.conversations.bulkCreate(conversationsData, { transaction });
// For each item created, replace relation files
return conversations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const conversations = await db.conversations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.case_reference !== undefined) updatePayload.case_reference = data.case_reference;
if (data.state !== undefined) updatePayload.state = data.state;
if (data.priority !== undefined) updatePayload.priority = data.priority;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.current_sentiment_score !== undefined) updatePayload.current_sentiment_score = data.current_sentiment_score;
if (data.sentiment_label !== undefined) updatePayload.sentiment_label = data.sentiment_label;
if (data.frustration_score !== undefined) updatePayload.frustration_score = data.frustration_score;
if (data.escalated !== undefined) updatePayload.escalated = data.escalated;
if (data.last_message_at !== undefined) updatePayload.last_message_at = data.last_message_at;
if (data.customer_intent !== undefined) updatePayload.customer_intent = data.customer_intent;
if (data.topic !== undefined) updatePayload.topic = data.topic;
if (data.resolution_summary !== undefined) updatePayload.resolution_summary = data.resolution_summary;
updatePayload.updatedById = currentUser.id;
await conversations.update(updatePayload, {transaction});
if (data.channel !== undefined) {
await conversations.setChannel(
data.channel,
{ transaction }
);
}
if (data.customer_account !== undefined) {
await conversations.setCustomer_account(
data.customer_account,
{ transaction }
);
}
if (data.customer_user !== undefined) {
await conversations.setCustomer_user(
data.customer_user,
{ transaction }
);
}
return conversations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const conversations = await db.conversations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of conversations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of conversations) {
await record.destroy({transaction});
}
});
return conversations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const conversations = await db.conversations.findByPk(id, options);
await conversations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await conversations.destroy({
transaction
});
return conversations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const conversations = await db.conversations.findOne(
{ where },
{ transaction },
);
if (!conversations) {
return conversations;
}
const output = conversations.get({plain: true});
output.conversation_messages_conversation = await conversations.getConversation_messages_conversation({
transaction
});
output.voice_calls_conversation = await conversations.getVoice_calls_conversation({
transaction
});
output.tickets_conversation = await conversations.getTickets_conversation({
transaction
});
output.escalation_alerts_conversation = await conversations.getEscalation_alerts_conversation({
transaction
});
output.ai_runs_conversation = await conversations.getAi_runs_conversation({
transaction
});
output.rag_queries_conversation = await conversations.getRag_queries_conversation({
transaction
});
output.channel = await conversations.getChannel({
transaction
});
output.customer_account = await conversations.getCustomer_account({
transaction
});
output.customer_user = await conversations.getCustomer_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.support_channels,
as: 'channel',
where: filter.channel ? {
[Op.or]: [
{ id: { [Op.in]: filter.channel.split('|').map(term => Utils.uuid(term)) } },
{
channel_name: {
[Op.or]: filter.channel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customer_accounts,
as: 'customer_account',
where: filter.customer_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer_account.split('|').map(term => Utils.uuid(term)) } },
{
account_name: {
[Op.or]: filter.customer_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'customer_user',
where: filter.customer_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.customer_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.case_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'conversations',
'case_reference',
filter.case_reference,
),
};
}
if (filter.customer_intent) {
where = {
...where,
[Op.and]: Utils.ilike(
'conversations',
'customer_intent',
filter.customer_intent,
),
};
}
if (filter.topic) {
where = {
...where,
[Op.and]: Utils.ilike(
'conversations',
'topic',
filter.topic,
),
};
}
if (filter.resolution_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'conversations',
'resolution_summary',
filter.resolution_summary,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
started_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ended_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.ended_atRange) {
const [start, end] = filter.ended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.lte]: end,
},
};
}
}
if (filter.current_sentiment_scoreRange) {
const [start, end] = filter.current_sentiment_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_sentiment_score: {
...where.current_sentiment_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_sentiment_score: {
...where.current_sentiment_score,
[Op.lte]: end,
},
};
}
}
if (filter.frustration_scoreRange) {
const [start, end] = filter.frustration_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
frustration_score: {
...where.frustration_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
frustration_score: {
...where.frustration_score,
[Op.lte]: end,
},
};
}
}
if (filter.last_message_atRange) {
const [start, end] = filter.last_message_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_message_at: {
...where.last_message_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_message_at: {
...where.last_message_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.state) {
where = {
...where,
state: filter.state,
};
}
if (filter.priority) {
where = {
...where,
priority: filter.priority,
};
}
if (filter.sentiment_label) {
where = {
...where,
sentiment_label: filter.sentiment_label,
};
}
if (filter.escalated) {
where = {
...where,
escalated: filter.escalated,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.conversations.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'conversations',
'case_reference',
query,
),
],
};
}
const records = await db.conversations.findAll({
attributes: [ 'id', 'case_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['case_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.case_reference,
}));
}
};

View File

@ -0,0 +1,650 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Customer_accountsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const customer_accounts = await db.customer_accounts.create(
{
id: data.id || undefined,
account_name: data.account_name
||
null
,
domain: data.domain
||
null
,
segment: data.segment
||
null
,
lifecycle_stage: data.lifecycle_stage
||
null
,
primary_contact_name: data.primary_contact_name
||
null
,
primary_contact_email: data.primary_contact_email
||
null
,
primary_contact_phone: data.primary_contact_phone
||
null
,
mrr: data.mrr
||
null
,
contract_start_at: data.contract_start_at
||
null
,
contract_end_at: data.contract_end_at
||
null
,
vip: data.vip
||
false
,
crm_account_ref: data.crm_account_ref
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return customer_accounts;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const customer_accountsData = data.map((item, index) => ({
id: item.id || undefined,
account_name: item.account_name
||
null
,
domain: item.domain
||
null
,
segment: item.segment
||
null
,
lifecycle_stage: item.lifecycle_stage
||
null
,
primary_contact_name: item.primary_contact_name
||
null
,
primary_contact_email: item.primary_contact_email
||
null
,
primary_contact_phone: item.primary_contact_phone
||
null
,
mrr: item.mrr
||
null
,
contract_start_at: item.contract_start_at
||
null
,
contract_end_at: item.contract_end_at
||
null
,
vip: item.vip
||
false
,
crm_account_ref: item.crm_account_ref
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const customer_accounts = await db.customer_accounts.bulkCreate(customer_accountsData, { transaction });
// For each item created, replace relation files
return customer_accounts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const customer_accounts = await db.customer_accounts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.account_name !== undefined) updatePayload.account_name = data.account_name;
if (data.domain !== undefined) updatePayload.domain = data.domain;
if (data.segment !== undefined) updatePayload.segment = data.segment;
if (data.lifecycle_stage !== undefined) updatePayload.lifecycle_stage = data.lifecycle_stage;
if (data.primary_contact_name !== undefined) updatePayload.primary_contact_name = data.primary_contact_name;
if (data.primary_contact_email !== undefined) updatePayload.primary_contact_email = data.primary_contact_email;
if (data.primary_contact_phone !== undefined) updatePayload.primary_contact_phone = data.primary_contact_phone;
if (data.mrr !== undefined) updatePayload.mrr = data.mrr;
if (data.contract_start_at !== undefined) updatePayload.contract_start_at = data.contract_start_at;
if (data.contract_end_at !== undefined) updatePayload.contract_end_at = data.contract_end_at;
if (data.vip !== undefined) updatePayload.vip = data.vip;
if (data.crm_account_ref !== undefined) updatePayload.crm_account_ref = data.crm_account_ref;
updatePayload.updatedById = currentUser.id;
await customer_accounts.update(updatePayload, {transaction});
return customer_accounts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const customer_accounts = await db.customer_accounts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of customer_accounts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of customer_accounts) {
await record.destroy({transaction});
}
});
return customer_accounts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const customer_accounts = await db.customer_accounts.findByPk(id, options);
await customer_accounts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await customer_accounts.destroy({
transaction
});
return customer_accounts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const customer_accounts = await db.customer_accounts.findOne(
{ where },
{ transaction },
);
if (!customer_accounts) {
return customer_accounts;
}
const output = customer_accounts.get({plain: true});
output.conversations_customer_account = await customer_accounts.getConversations_customer_account({
transaction
});
output.tickets_customer_account = await customer_accounts.getTickets_customer_account({
transaction
});
output.customer_health_snapshots_customer_account = await customer_accounts.getCustomer_health_snapshots_customer_account({
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.account_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'customer_accounts',
'account_name',
filter.account_name,
),
};
}
if (filter.domain) {
where = {
...where,
[Op.and]: Utils.ilike(
'customer_accounts',
'domain',
filter.domain,
),
};
}
if (filter.primary_contact_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'customer_accounts',
'primary_contact_name',
filter.primary_contact_name,
),
};
}
if (filter.primary_contact_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'customer_accounts',
'primary_contact_email',
filter.primary_contact_email,
),
};
}
if (filter.primary_contact_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'customer_accounts',
'primary_contact_phone',
filter.primary_contact_phone,
),
};
}
if (filter.crm_account_ref) {
where = {
...where,
[Op.and]: Utils.ilike(
'customer_accounts',
'crm_account_ref',
filter.crm_account_ref,
),
};
}
if (filter.mrrRange) {
const [start, end] = filter.mrrRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
mrr: {
...where.mrr,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
mrr: {
...where.mrr,
[Op.lte]: end,
},
};
}
}
if (filter.contract_start_atRange) {
const [start, end] = filter.contract_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
contract_start_at: {
...where.contract_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
contract_start_at: {
...where.contract_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.contract_end_atRange) {
const [start, end] = filter.contract_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
contract_end_at: {
...where.contract_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
contract_end_at: {
...where.contract_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.segment) {
where = {
...where,
segment: filter.segment,
};
}
if (filter.lifecycle_stage) {
where = {
...where,
lifecycle_stage: filter.lifecycle_stage,
};
}
if (filter.vip) {
where = {
...where,
vip: filter.vip,
};
}
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.customer_accounts.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'customer_accounts',
'account_name',
query,
),
],
};
}
const records = await db.customer_accounts.findAll({
attributes: [ 'id', 'account_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['account_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.account_name,
}));
}
};

View File

@ -0,0 +1,718 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Customer_health_snapshotsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const customer_health_snapshots = await db.customer_health_snapshots.create(
{
id: data.id || undefined,
calculated_at: data.calculated_at
||
null
,
health_score: data.health_score
||
null
,
health_label: data.health_label
||
null
,
churn_risk_score: data.churn_risk_score
||
null
,
churn_risk_label: data.churn_risk_label
||
null
,
sentiment_trend: data.sentiment_trend
||
null
,
ticket_volume_30d: data.ticket_volume_30d
||
null
,
repeat_issue_count_30d: data.repeat_issue_count_30d
||
null
,
avg_first_response_minutes_30d: data.avg_first_response_minutes_30d
||
null
,
avg_resolution_hours_30d: data.avg_resolution_hours_30d
||
null
,
drivers_summary: data.drivers_summary
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await customer_health_snapshots.setCustomer_account( data.customer_account || null, {
transaction,
});
return customer_health_snapshots;
}
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 customer_health_snapshotsData = data.map((item, index) => ({
id: item.id || undefined,
calculated_at: item.calculated_at
||
null
,
health_score: item.health_score
||
null
,
health_label: item.health_label
||
null
,
churn_risk_score: item.churn_risk_score
||
null
,
churn_risk_label: item.churn_risk_label
||
null
,
sentiment_trend: item.sentiment_trend
||
null
,
ticket_volume_30d: item.ticket_volume_30d
||
null
,
repeat_issue_count_30d: item.repeat_issue_count_30d
||
null
,
avg_first_response_minutes_30d: item.avg_first_response_minutes_30d
||
null
,
avg_resolution_hours_30d: item.avg_resolution_hours_30d
||
null
,
drivers_summary: item.drivers_summary
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const customer_health_snapshots = await db.customer_health_snapshots.bulkCreate(customer_health_snapshotsData, { transaction });
// For each item created, replace relation files
return customer_health_snapshots;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const customer_health_snapshots = await db.customer_health_snapshots.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.calculated_at !== undefined) updatePayload.calculated_at = data.calculated_at;
if (data.health_score !== undefined) updatePayload.health_score = data.health_score;
if (data.health_label !== undefined) updatePayload.health_label = data.health_label;
if (data.churn_risk_score !== undefined) updatePayload.churn_risk_score = data.churn_risk_score;
if (data.churn_risk_label !== undefined) updatePayload.churn_risk_label = data.churn_risk_label;
if (data.sentiment_trend !== undefined) updatePayload.sentiment_trend = data.sentiment_trend;
if (data.ticket_volume_30d !== undefined) updatePayload.ticket_volume_30d = data.ticket_volume_30d;
if (data.repeat_issue_count_30d !== undefined) updatePayload.repeat_issue_count_30d = data.repeat_issue_count_30d;
if (data.avg_first_response_minutes_30d !== undefined) updatePayload.avg_first_response_minutes_30d = data.avg_first_response_minutes_30d;
if (data.avg_resolution_hours_30d !== undefined) updatePayload.avg_resolution_hours_30d = data.avg_resolution_hours_30d;
if (data.drivers_summary !== undefined) updatePayload.drivers_summary = data.drivers_summary;
updatePayload.updatedById = currentUser.id;
await customer_health_snapshots.update(updatePayload, {transaction});
if (data.customer_account !== undefined) {
await customer_health_snapshots.setCustomer_account(
data.customer_account,
{ transaction }
);
}
return customer_health_snapshots;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const customer_health_snapshots = await db.customer_health_snapshots.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of customer_health_snapshots) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of customer_health_snapshots) {
await record.destroy({transaction});
}
});
return customer_health_snapshots;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const customer_health_snapshots = await db.customer_health_snapshots.findByPk(id, options);
await customer_health_snapshots.update({
deletedBy: currentUser.id
}, {
transaction,
});
await customer_health_snapshots.destroy({
transaction
});
return customer_health_snapshots;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const customer_health_snapshots = await db.customer_health_snapshots.findOne(
{ where },
{ transaction },
);
if (!customer_health_snapshots) {
return customer_health_snapshots;
}
const output = customer_health_snapshots.get({plain: true});
output.customer_account = await customer_health_snapshots.getCustomer_account({
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.customer_accounts,
as: 'customer_account',
where: filter.customer_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer_account.split('|').map(term => Utils.uuid(term)) } },
{
account_name: {
[Op.or]: filter.customer_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.drivers_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'customer_health_snapshots',
'drivers_summary',
filter.drivers_summary,
),
};
}
if (filter.calculated_atRange) {
const [start, end] = filter.calculated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
calculated_at: {
...where.calculated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
calculated_at: {
...where.calculated_at,
[Op.lte]: end,
},
};
}
}
if (filter.health_scoreRange) {
const [start, end] = filter.health_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
health_score: {
...where.health_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
health_score: {
...where.health_score,
[Op.lte]: end,
},
};
}
}
if (filter.churn_risk_scoreRange) {
const [start, end] = filter.churn_risk_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
churn_risk_score: {
...where.churn_risk_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
churn_risk_score: {
...where.churn_risk_score,
[Op.lte]: end,
},
};
}
}
if (filter.sentiment_trendRange) {
const [start, end] = filter.sentiment_trendRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sentiment_trend: {
...where.sentiment_trend,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sentiment_trend: {
...where.sentiment_trend,
[Op.lte]: end,
},
};
}
}
if (filter.ticket_volume_30dRange) {
const [start, end] = filter.ticket_volume_30dRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ticket_volume_30d: {
...where.ticket_volume_30d,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ticket_volume_30d: {
...where.ticket_volume_30d,
[Op.lte]: end,
},
};
}
}
if (filter.repeat_issue_count_30dRange) {
const [start, end] = filter.repeat_issue_count_30dRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
repeat_issue_count_30d: {
...where.repeat_issue_count_30d,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
repeat_issue_count_30d: {
...where.repeat_issue_count_30d,
[Op.lte]: end,
},
};
}
}
if (filter.avg_first_response_minutes_30dRange) {
const [start, end] = filter.avg_first_response_minutes_30dRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
avg_first_response_minutes_30d: {
...where.avg_first_response_minutes_30d,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
avg_first_response_minutes_30d: {
...where.avg_first_response_minutes_30d,
[Op.lte]: end,
},
};
}
}
if (filter.avg_resolution_hours_30dRange) {
const [start, end] = filter.avg_resolution_hours_30dRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
avg_resolution_hours_30d: {
...where.avg_resolution_hours_30d,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
avg_resolution_hours_30d: {
...where.avg_resolution_hours_30d,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.health_label) {
where = {
...where,
health_label: filter.health_label,
};
}
if (filter.churn_risk_label) {
where = {
...where,
churn_risk_label: filter.churn_risk_label,
};
}
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.customer_health_snapshots.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(
'customer_health_snapshots',
'health_label',
query,
),
],
};
}
const records = await db.customer_health_snapshots.findAll({
attributes: [ 'id', 'health_label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['health_label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.health_label,
}));
}
};

View File

@ -0,0 +1,592 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Escalation_alertsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const escalation_alerts = await db.escalation_alerts.create(
{
id: data.id || undefined,
severity: data.severity
||
null
,
reason: data.reason
||
null
,
message: data.message
||
null
,
acknowledged: data.acknowledged
||
false
,
acknowledged_at: data.acknowledged_at
||
null
,
triggered_at: data.triggered_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await escalation_alerts.setConversation( data.conversation || null, {
transaction,
});
await escalation_alerts.setTicket( data.ticket || null, {
transaction,
});
await escalation_alerts.setAcknowledged_by( data.acknowledged_by || null, {
transaction,
});
return escalation_alerts;
}
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 escalation_alertsData = data.map((item, index) => ({
id: item.id || undefined,
severity: item.severity
||
null
,
reason: item.reason
||
null
,
message: item.message
||
null
,
acknowledged: item.acknowledged
||
false
,
acknowledged_at: item.acknowledged_at
||
null
,
triggered_at: item.triggered_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const escalation_alerts = await db.escalation_alerts.bulkCreate(escalation_alertsData, { transaction });
// For each item created, replace relation files
return escalation_alerts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const escalation_alerts = await db.escalation_alerts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.severity !== undefined) updatePayload.severity = data.severity;
if (data.reason !== undefined) updatePayload.reason = data.reason;
if (data.message !== undefined) updatePayload.message = data.message;
if (data.acknowledged !== undefined) updatePayload.acknowledged = data.acknowledged;
if (data.acknowledged_at !== undefined) updatePayload.acknowledged_at = data.acknowledged_at;
if (data.triggered_at !== undefined) updatePayload.triggered_at = data.triggered_at;
updatePayload.updatedById = currentUser.id;
await escalation_alerts.update(updatePayload, {transaction});
if (data.conversation !== undefined) {
await escalation_alerts.setConversation(
data.conversation,
{ transaction }
);
}
if (data.ticket !== undefined) {
await escalation_alerts.setTicket(
data.ticket,
{ transaction }
);
}
if (data.acknowledged_by !== undefined) {
await escalation_alerts.setAcknowledged_by(
data.acknowledged_by,
{ transaction }
);
}
return escalation_alerts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const escalation_alerts = await db.escalation_alerts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of escalation_alerts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of escalation_alerts) {
await record.destroy({transaction});
}
});
return escalation_alerts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const escalation_alerts = await db.escalation_alerts.findByPk(id, options);
await escalation_alerts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await escalation_alerts.destroy({
transaction
});
return escalation_alerts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const escalation_alerts = await db.escalation_alerts.findOne(
{ where },
{ transaction },
);
if (!escalation_alerts) {
return escalation_alerts;
}
const output = escalation_alerts.get({plain: true});
output.conversation = await escalation_alerts.getConversation({
transaction
});
output.ticket = await escalation_alerts.getTicket({
transaction
});
output.acknowledged_by = await escalation_alerts.getAcknowledged_by({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.conversations,
as: 'conversation',
where: filter.conversation ? {
[Op.or]: [
{ id: { [Op.in]: filter.conversation.split('|').map(term => Utils.uuid(term)) } },
{
case_reference: {
[Op.or]: filter.conversation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.tickets,
as: 'ticket',
where: filter.ticket ? {
[Op.or]: [
{ id: { [Op.in]: filter.ticket.split('|').map(term => Utils.uuid(term)) } },
{
subject: {
[Op.or]: filter.ticket.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'acknowledged_by',
where: filter.acknowledged_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.acknowledged_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.acknowledged_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'escalation_alerts',
'message',
filter.message,
),
};
}
if (filter.acknowledged_atRange) {
const [start, end] = filter.acknowledged_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
acknowledged_at: {
...where.acknowledged_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
acknowledged_at: {
...where.acknowledged_at,
[Op.lte]: end,
},
};
}
}
if (filter.triggered_atRange) {
const [start, end] = filter.triggered_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
triggered_at: {
...where.triggered_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
triggered_at: {
...where.triggered_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.severity) {
where = {
...where,
severity: filter.severity,
};
}
if (filter.reason) {
where = {
...where,
reason: filter.reason,
};
}
if (filter.acknowledged) {
where = {
...where,
acknowledged: filter.acknowledged,
};
}
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.escalation_alerts.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(
'escalation_alerts',
'message',
query,
),
],
};
}
const records = await db.escalation_alerts.findAll({
attributes: [ 'id', 'message' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['message', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.message,
}));
}
};

View File

@ -0,0 +1,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,435 @@
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 Issue_taxonomyDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const issue_taxonomy = await db.issue_taxonomy.create(
{
id: data.id || undefined,
issue_name: data.issue_name
||
null
,
issue_type: data.issue_type
||
null
,
description: data.description
||
null
,
severity_default: data.severity_default
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return issue_taxonomy;
}
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 issue_taxonomyData = data.map((item, index) => ({
id: item.id || undefined,
issue_name: item.issue_name
||
null
,
issue_type: item.issue_type
||
null
,
description: item.description
||
null
,
severity_default: item.severity_default
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const issue_taxonomy = await db.issue_taxonomy.bulkCreate(issue_taxonomyData, { transaction });
// For each item created, replace relation files
return issue_taxonomy;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const issue_taxonomy = await db.issue_taxonomy.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.issue_name !== undefined) updatePayload.issue_name = data.issue_name;
if (data.issue_type !== undefined) updatePayload.issue_type = data.issue_type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.severity_default !== undefined) updatePayload.severity_default = data.severity_default;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await issue_taxonomy.update(updatePayload, {transaction});
return issue_taxonomy;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const issue_taxonomy = await db.issue_taxonomy.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of issue_taxonomy) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of issue_taxonomy) {
await record.destroy({transaction});
}
});
return issue_taxonomy;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const issue_taxonomy = await db.issue_taxonomy.findByPk(id, options);
await issue_taxonomy.update({
deletedBy: currentUser.id
}, {
transaction,
});
await issue_taxonomy.destroy({
transaction
});
return issue_taxonomy;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const issue_taxonomy = await db.issue_taxonomy.findOne(
{ where },
{ transaction },
);
if (!issue_taxonomy) {
return issue_taxonomy;
}
const output = issue_taxonomy.get({plain: true});
output.recurring_issue_signals_issue = await issue_taxonomy.getRecurring_issue_signals_issue({
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.issue_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'issue_taxonomy',
'issue_name',
filter.issue_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'issue_taxonomy',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.issue_type) {
where = {
...where,
issue_type: filter.issue_type,
};
}
if (filter.severity_default) {
where = {
...where,
severity_default: filter.severity_default,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.issue_taxonomy.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(
'issue_taxonomy',
'issue_name',
query,
),
],
};
}
const records = await db.issue_taxonomy.findAll({
attributes: [ 'id', 'issue_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['issue_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.issue_name,
}));
}
};

View File

@ -0,0 +1,617 @@
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 Knowledge_articlesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const knowledge_articles = await db.knowledge_articles.create(
{
id: data.id || undefined,
title: data.title
||
null
,
slug: data.slug
||
null
,
visibility: data.visibility
||
null
,
content: data.content
||
null
,
tags: data.tags
||
null
,
external_ref: data.external_ref
||
null
,
quality_score: data.quality_score
||
null
,
published_at: data.published_at
||
null
,
last_reviewed_at: data.last_reviewed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await knowledge_articles.setKnowledge_source( data.knowledge_source || null, {
transaction,
});
return knowledge_articles;
}
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 knowledge_articlesData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
slug: item.slug
||
null
,
visibility: item.visibility
||
null
,
content: item.content
||
null
,
tags: item.tags
||
null
,
external_ref: item.external_ref
||
null
,
quality_score: item.quality_score
||
null
,
published_at: item.published_at
||
null
,
last_reviewed_at: item.last_reviewed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const knowledge_articles = await db.knowledge_articles.bulkCreate(knowledge_articlesData, { transaction });
// For each item created, replace relation files
return knowledge_articles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const knowledge_articles = await db.knowledge_articles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.tags !== undefined) updatePayload.tags = data.tags;
if (data.external_ref !== undefined) updatePayload.external_ref = data.external_ref;
if (data.quality_score !== undefined) updatePayload.quality_score = data.quality_score;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
if (data.last_reviewed_at !== undefined) updatePayload.last_reviewed_at = data.last_reviewed_at;
updatePayload.updatedById = currentUser.id;
await knowledge_articles.update(updatePayload, {transaction});
if (data.knowledge_source !== undefined) {
await knowledge_articles.setKnowledge_source(
data.knowledge_source,
{ transaction }
);
}
return knowledge_articles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const knowledge_articles = await db.knowledge_articles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of knowledge_articles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of knowledge_articles) {
await record.destroy({transaction});
}
});
return knowledge_articles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const knowledge_articles = await db.knowledge_articles.findByPk(id, options);
await knowledge_articles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await knowledge_articles.destroy({
transaction
});
return knowledge_articles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const knowledge_articles = await db.knowledge_articles.findOne(
{ where },
{ transaction },
);
if (!knowledge_articles) {
return knowledge_articles;
}
const output = knowledge_articles.get({plain: true});
output.conversation_messages_knowledge_article_used = await knowledge_articles.getConversation_messages_knowledge_article_used({
transaction
});
output.rag_results_knowledge_article = await knowledge_articles.getRag_results_knowledge_article({
transaction
});
output.knowledge_source = await knowledge_articles.getKnowledge_source({
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.knowledge_sources,
as: 'knowledge_source',
where: filter.knowledge_source ? {
[Op.or]: [
{ id: { [Op.in]: filter.knowledge_source.split('|').map(term => Utils.uuid(term)) } },
{
source_name: {
[Op.or]: filter.knowledge_source.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'knowledge_articles',
'title',
filter.title,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'knowledge_articles',
'slug',
filter.slug,
),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'knowledge_articles',
'content',
filter.content,
),
};
}
if (filter.tags) {
where = {
...where,
[Op.and]: Utils.ilike(
'knowledge_articles',
'tags',
filter.tags,
),
};
}
if (filter.external_ref) {
where = {
...where,
[Op.and]: Utils.ilike(
'knowledge_articles',
'external_ref',
filter.external_ref,
),
};
}
if (filter.quality_scoreRange) {
const [start, end] = filter.quality_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quality_score: {
...where.quality_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quality_score: {
...where.quality_score,
[Op.lte]: end,
},
};
}
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.last_reviewed_atRange) {
const [start, end] = filter.last_reviewed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_reviewed_at: {
...where.last_reviewed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_reviewed_at: {
...where.last_reviewed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.knowledge_articles.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(
'knowledge_articles',
'title',
query,
),
],
};
}
const records = await db.knowledge_articles.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,516 @@
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 Knowledge_sourcesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const knowledge_sources = await db.knowledge_sources.create(
{
id: data.id || undefined,
source_name: data.source_name
||
null
,
source_type: data.source_type
||
null
,
status: data.status
||
null
,
source_uri: data.source_uri
||
null
,
last_ingested_at: data.last_ingested_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.knowledge_sources.getTableName(),
belongsToColumn: 'source_files',
belongsToId: knowledge_sources.id,
},
data.source_files,
options,
);
return knowledge_sources;
}
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 knowledge_sourcesData = data.map((item, index) => ({
id: item.id || undefined,
source_name: item.source_name
||
null
,
source_type: item.source_type
||
null
,
status: item.status
||
null
,
source_uri: item.source_uri
||
null
,
last_ingested_at: item.last_ingested_at
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const knowledge_sources = await db.knowledge_sources.bulkCreate(knowledge_sourcesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < knowledge_sources.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.knowledge_sources.getTableName(),
belongsToColumn: 'source_files',
belongsToId: knowledge_sources[i].id,
},
data[i].source_files,
options,
);
}
return knowledge_sources;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const knowledge_sources = await db.knowledge_sources.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.source_name !== undefined) updatePayload.source_name = data.source_name;
if (data.source_type !== undefined) updatePayload.source_type = data.source_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.source_uri !== undefined) updatePayload.source_uri = data.source_uri;
if (data.last_ingested_at !== undefined) updatePayload.last_ingested_at = data.last_ingested_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await knowledge_sources.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.knowledge_sources.getTableName(),
belongsToColumn: 'source_files',
belongsToId: knowledge_sources.id,
},
data.source_files,
options,
);
return knowledge_sources;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const knowledge_sources = await db.knowledge_sources.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of knowledge_sources) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of knowledge_sources) {
await record.destroy({transaction});
}
});
return knowledge_sources;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const knowledge_sources = await db.knowledge_sources.findByPk(id, options);
await knowledge_sources.update({
deletedBy: currentUser.id
}, {
transaction,
});
await knowledge_sources.destroy({
transaction
});
return knowledge_sources;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const knowledge_sources = await db.knowledge_sources.findOne(
{ where },
{ transaction },
);
if (!knowledge_sources) {
return knowledge_sources;
}
const output = knowledge_sources.get({plain: true});
output.knowledge_articles_knowledge_source = await knowledge_sources.getKnowledge_articles_knowledge_source({
transaction
});
output.source_files = await knowledge_sources.getSource_files({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.file,
as: 'source_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.source_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'knowledge_sources',
'source_name',
filter.source_name,
),
};
}
if (filter.source_uri) {
where = {
...where,
[Op.and]: Utils.ilike(
'knowledge_sources',
'source_uri',
filter.source_uri,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'knowledge_sources',
'notes',
filter.notes,
),
};
}
if (filter.last_ingested_atRange) {
const [start, end] = filter.last_ingested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_ingested_at: {
...where.last_ingested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_ingested_at: {
...where.last_ingested_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.source_type) {
where = {
...where,
source_type: filter.source_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.knowledge_sources.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(
'knowledge_sources',
'source_name',
query,
),
],
};
}
const records = await db.knowledge_sources.findAll({
attributes: [ 'id', 'source_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['source_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.source_name,
}));
}
};

View File

@ -0,0 +1,345 @@
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,578 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Rag_queriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const rag_queries = await db.rag_queries.create(
{
id: data.id || undefined,
query_text: data.query_text
||
null
,
retrieval_strategy: data.retrieval_strategy
||
null
,
top_k: data.top_k
||
null
,
min_score_threshold: data.min_score_threshold
||
null
,
filters_json: data.filters_json
||
null
,
queried_at: data.queried_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await rag_queries.setAi_run( data.ai_run || null, {
transaction,
});
await rag_queries.setConversation( data.conversation || null, {
transaction,
});
return rag_queries;
}
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 rag_queriesData = data.map((item, index) => ({
id: item.id || undefined,
query_text: item.query_text
||
null
,
retrieval_strategy: item.retrieval_strategy
||
null
,
top_k: item.top_k
||
null
,
min_score_threshold: item.min_score_threshold
||
null
,
filters_json: item.filters_json
||
null
,
queried_at: item.queried_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const rag_queries = await db.rag_queries.bulkCreate(rag_queriesData, { transaction });
// For each item created, replace relation files
return rag_queries;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const rag_queries = await db.rag_queries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.query_text !== undefined) updatePayload.query_text = data.query_text;
if (data.retrieval_strategy !== undefined) updatePayload.retrieval_strategy = data.retrieval_strategy;
if (data.top_k !== undefined) updatePayload.top_k = data.top_k;
if (data.min_score_threshold !== undefined) updatePayload.min_score_threshold = data.min_score_threshold;
if (data.filters_json !== undefined) updatePayload.filters_json = data.filters_json;
if (data.queried_at !== undefined) updatePayload.queried_at = data.queried_at;
updatePayload.updatedById = currentUser.id;
await rag_queries.update(updatePayload, {transaction});
if (data.ai_run !== undefined) {
await rag_queries.setAi_run(
data.ai_run,
{ transaction }
);
}
if (data.conversation !== undefined) {
await rag_queries.setConversation(
data.conversation,
{ transaction }
);
}
return rag_queries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const rag_queries = await db.rag_queries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of rag_queries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of rag_queries) {
await record.destroy({transaction});
}
});
return rag_queries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const rag_queries = await db.rag_queries.findByPk(id, options);
await rag_queries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await rag_queries.destroy({
transaction
});
return rag_queries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const rag_queries = await db.rag_queries.findOne(
{ where },
{ transaction },
);
if (!rag_queries) {
return rag_queries;
}
const output = rag_queries.get({plain: true});
output.rag_results_rag_query = await rag_queries.getRag_results_rag_query({
transaction
});
output.ai_run = await rag_queries.getAi_run({
transaction
});
output.conversation = await rag_queries.getConversation({
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.ai_runs,
as: 'ai_run',
where: filter.ai_run ? {
[Op.or]: [
{ id: { [Op.in]: filter.ai_run.split('|').map(term => Utils.uuid(term)) } },
{
run_type: {
[Op.or]: filter.ai_run.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.conversations,
as: 'conversation',
where: filter.conversation ? {
[Op.or]: [
{ id: { [Op.in]: filter.conversation.split('|').map(term => Utils.uuid(term)) } },
{
case_reference: {
[Op.or]: filter.conversation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.query_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'rag_queries',
'query_text',
filter.query_text,
),
};
}
if (filter.filters_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'rag_queries',
'filters_json',
filter.filters_json,
),
};
}
if (filter.top_kRange) {
const [start, end] = filter.top_kRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
top_k: {
...where.top_k,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
top_k: {
...where.top_k,
[Op.lte]: end,
},
};
}
}
if (filter.min_score_thresholdRange) {
const [start, end] = filter.min_score_thresholdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_score_threshold: {
...where.min_score_threshold,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_score_threshold: {
...where.min_score_threshold,
[Op.lte]: end,
},
};
}
}
if (filter.queried_atRange) {
const [start, end] = filter.queried_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
queried_at: {
...where.queried_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
queried_at: {
...where.queried_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.retrieval_strategy) {
where = {
...where,
retrieval_strategy: filter.retrieval_strategy,
};
}
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.rag_queries.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(
'rag_queries',
'query_text',
query,
),
],
};
}
const records = await db.rag_queries.findAll({
attributes: [ 'id', 'query_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['query_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.query_text,
}));
}
};

View File

@ -0,0 +1,493 @@
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 Rag_resultsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const rag_results = await db.rag_results.create(
{
id: data.id || undefined,
score: data.score
||
null
,
rank: data.rank
||
null
,
snippet: data.snippet
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await rag_results.setRag_query( data.rag_query || null, {
transaction,
});
await rag_results.setKnowledge_article( data.knowledge_article || null, {
transaction,
});
return rag_results;
}
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 rag_resultsData = data.map((item, index) => ({
id: item.id || undefined,
score: item.score
||
null
,
rank: item.rank
||
null
,
snippet: item.snippet
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const rag_results = await db.rag_results.bulkCreate(rag_resultsData, { transaction });
// For each item created, replace relation files
return rag_results;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const rag_results = await db.rag_results.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.score !== undefined) updatePayload.score = data.score;
if (data.rank !== undefined) updatePayload.rank = data.rank;
if (data.snippet !== undefined) updatePayload.snippet = data.snippet;
updatePayload.updatedById = currentUser.id;
await rag_results.update(updatePayload, {transaction});
if (data.rag_query !== undefined) {
await rag_results.setRag_query(
data.rag_query,
{ transaction }
);
}
if (data.knowledge_article !== undefined) {
await rag_results.setKnowledge_article(
data.knowledge_article,
{ transaction }
);
}
return rag_results;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const rag_results = await db.rag_results.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of rag_results) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of rag_results) {
await record.destroy({transaction});
}
});
return rag_results;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const rag_results = await db.rag_results.findByPk(id, options);
await rag_results.update({
deletedBy: currentUser.id
}, {
transaction,
});
await rag_results.destroy({
transaction
});
return rag_results;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const rag_results = await db.rag_results.findOne(
{ where },
{ transaction },
);
if (!rag_results) {
return rag_results;
}
const output = rag_results.get({plain: true});
output.rag_query = await rag_results.getRag_query({
transaction
});
output.knowledge_article = await rag_results.getKnowledge_article({
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.rag_queries,
as: 'rag_query',
where: filter.rag_query ? {
[Op.or]: [
{ id: { [Op.in]: filter.rag_query.split('|').map(term => Utils.uuid(term)) } },
{
query_text: {
[Op.or]: filter.rag_query.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.knowledge_articles,
as: 'knowledge_article',
where: filter.knowledge_article ? {
[Op.or]: [
{ id: { [Op.in]: filter.knowledge_article.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.knowledge_article.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.snippet) {
where = {
...where,
[Op.and]: Utils.ilike(
'rag_results',
'snippet',
filter.snippet,
),
};
}
if (filter.scoreRange) {
const [start, end] = filter.scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score: {
...where.score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score: {
...where.score,
[Op.lte]: end,
},
};
}
}
if (filter.rankRange) {
const [start, end] = filter.rankRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rank: {
...where.rank,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rank: {
...where.rank,
[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.rag_results.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(
'rag_results',
'snippet',
query,
),
],
};
}
const records = await db.rag_results.findAll({
attributes: [ 'id', 'snippet' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['snippet', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.snippet,
}));
}
};

View File

@ -0,0 +1,607 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Recurring_issue_signalsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const recurring_issue_signals = await db.recurring_issue_signals.create(
{
id: data.id || undefined,
window_start_at: data.window_start_at
||
null
,
window_end_at: data.window_end_at
||
null
,
occurrence_count: data.occurrence_count
||
null
,
impact_score: data.impact_score
||
null
,
avg_sentiment_score: data.avg_sentiment_score
||
null
,
example_case_references: data.example_case_references
||
null
,
needs_attention: data.needs_attention
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await recurring_issue_signals.setIssue( data.issue || null, {
transaction,
});
return recurring_issue_signals;
}
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 recurring_issue_signalsData = data.map((item, index) => ({
id: item.id || undefined,
window_start_at: item.window_start_at
||
null
,
window_end_at: item.window_end_at
||
null
,
occurrence_count: item.occurrence_count
||
null
,
impact_score: item.impact_score
||
null
,
avg_sentiment_score: item.avg_sentiment_score
||
null
,
example_case_references: item.example_case_references
||
null
,
needs_attention: item.needs_attention
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const recurring_issue_signals = await db.recurring_issue_signals.bulkCreate(recurring_issue_signalsData, { transaction });
// For each item created, replace relation files
return recurring_issue_signals;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const recurring_issue_signals = await db.recurring_issue_signals.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.window_start_at !== undefined) updatePayload.window_start_at = data.window_start_at;
if (data.window_end_at !== undefined) updatePayload.window_end_at = data.window_end_at;
if (data.occurrence_count !== undefined) updatePayload.occurrence_count = data.occurrence_count;
if (data.impact_score !== undefined) updatePayload.impact_score = data.impact_score;
if (data.avg_sentiment_score !== undefined) updatePayload.avg_sentiment_score = data.avg_sentiment_score;
if (data.example_case_references !== undefined) updatePayload.example_case_references = data.example_case_references;
if (data.needs_attention !== undefined) updatePayload.needs_attention = data.needs_attention;
updatePayload.updatedById = currentUser.id;
await recurring_issue_signals.update(updatePayload, {transaction});
if (data.issue !== undefined) {
await recurring_issue_signals.setIssue(
data.issue,
{ transaction }
);
}
return recurring_issue_signals;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const recurring_issue_signals = await db.recurring_issue_signals.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of recurring_issue_signals) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of recurring_issue_signals) {
await record.destroy({transaction});
}
});
return recurring_issue_signals;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const recurring_issue_signals = await db.recurring_issue_signals.findByPk(id, options);
await recurring_issue_signals.update({
deletedBy: currentUser.id
}, {
transaction,
});
await recurring_issue_signals.destroy({
transaction
});
return recurring_issue_signals;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const recurring_issue_signals = await db.recurring_issue_signals.findOne(
{ where },
{ transaction },
);
if (!recurring_issue_signals) {
return recurring_issue_signals;
}
const output = recurring_issue_signals.get({plain: true});
output.issue = await recurring_issue_signals.getIssue({
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.issue_taxonomy,
as: 'issue',
where: filter.issue ? {
[Op.or]: [
{ id: { [Op.in]: filter.issue.split('|').map(term => Utils.uuid(term)) } },
{
issue_name: {
[Op.or]: filter.issue.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.example_case_references) {
where = {
...where,
[Op.and]: Utils.ilike(
'recurring_issue_signals',
'example_case_references',
filter.example_case_references,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
window_start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
window_end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.window_start_atRange) {
const [start, end] = filter.window_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
window_start_at: {
...where.window_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
window_start_at: {
...where.window_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.window_end_atRange) {
const [start, end] = filter.window_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
window_end_at: {
...where.window_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
window_end_at: {
...where.window_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.occurrence_countRange) {
const [start, end] = filter.occurrence_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occurrence_count: {
...where.occurrence_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occurrence_count: {
...where.occurrence_count,
[Op.lte]: end,
},
};
}
}
if (filter.impact_scoreRange) {
const [start, end] = filter.impact_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
impact_score: {
...where.impact_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
impact_score: {
...where.impact_score,
[Op.lte]: end,
},
};
}
}
if (filter.avg_sentiment_scoreRange) {
const [start, end] = filter.avg_sentiment_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
avg_sentiment_score: {
...where.avg_sentiment_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
avg_sentiment_score: {
...where.avg_sentiment_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.needs_attention) {
where = {
...where,
needs_attention: filter.needs_attention,
};
}
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.recurring_issue_signals.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(
'recurring_issue_signals',
'impact_score',
query,
),
],
};
}
const records = await db.recurring_issue_signals.findAll({
attributes: [ 'id', 'impact_score' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['impact_score', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.impact_score,
}));
}
};

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

@ -0,0 +1,415 @@
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,437 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Support_channelsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const support_channels = await db.support_channels.create(
{
id: data.id || undefined,
channel_name: data.channel_name
||
null
,
channel_type: data.channel_type
||
null
,
status: data.status
||
null
,
provider: data.provider
||
null
,
provider_config_hint: data.provider_config_hint
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return support_channels;
}
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 support_channelsData = data.map((item, index) => ({
id: item.id || undefined,
channel_name: item.channel_name
||
null
,
channel_type: item.channel_type
||
null
,
status: item.status
||
null
,
provider: item.provider
||
null
,
provider_config_hint: item.provider_config_hint
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const support_channels = await db.support_channels.bulkCreate(support_channelsData, { transaction });
// For each item created, replace relation files
return support_channels;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const support_channels = await db.support_channels.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.channel_name !== undefined) updatePayload.channel_name = data.channel_name;
if (data.channel_type !== undefined) updatePayload.channel_type = data.channel_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.provider !== undefined) updatePayload.provider = data.provider;
if (data.provider_config_hint !== undefined) updatePayload.provider_config_hint = data.provider_config_hint;
updatePayload.updatedById = currentUser.id;
await support_channels.update(updatePayload, {transaction});
return support_channels;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const support_channels = await db.support_channels.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of support_channels) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of support_channels) {
await record.destroy({transaction});
}
});
return support_channels;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const support_channels = await db.support_channels.findByPk(id, options);
await support_channels.update({
deletedBy: currentUser.id
}, {
transaction,
});
await support_channels.destroy({
transaction
});
return support_channels;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const support_channels = await db.support_channels.findOne(
{ where },
{ transaction },
);
if (!support_channels) {
return support_channels;
}
const output = support_channels.get({plain: true});
output.conversations_channel = await support_channels.getConversations_channel({
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.channel_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'support_channels',
'channel_name',
filter.channel_name,
),
};
}
if (filter.provider) {
where = {
...where,
[Op.and]: Utils.ilike(
'support_channels',
'provider',
filter.provider,
),
};
}
if (filter.provider_config_hint) {
where = {
...where,
[Op.and]: Utils.ilike(
'support_channels',
'provider_config_hint',
filter.provider_config_hint,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.channel_type) {
where = {
...where,
channel_type: filter.channel_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.support_channels.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(
'support_channels',
'channel_name',
query,
),
],
};
}
const records = await db.support_channels.findAll({
attributes: [ 'id', 'channel_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['channel_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.channel_name,
}));
}
};

View File

@ -0,0 +1,847 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class TicketsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tickets = await db.tickets.create(
{
id: data.id || undefined,
ticket_number: data.ticket_number
||
null
,
status: data.status
||
null
,
priority: data.priority
||
null
,
category: data.category
||
null
,
subject: data.subject
||
null
,
description: data.description
||
null
,
ai_summary: data.ai_summary
||
null
,
next_best_action: data.next_best_action
||
null
,
sentiment_at_creation: data.sentiment_at_creation
||
null
,
frustration_at_creation: data.frustration_at_creation
||
null
,
escalation_required: data.escalation_required
||
false
,
opened_at: data.opened_at
||
null
,
closed_at: data.closed_at
||
null
,
external_crm_ticket_ref: data.external_crm_ticket_ref
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tickets.setConversation( data.conversation || null, {
transaction,
});
await tickets.setCustomer_account( data.customer_account || null, {
transaction,
});
await tickets.setRequester_user( data.requester_user || null, {
transaction,
});
await tickets.setAssigned_agent( data.assigned_agent || null, {
transaction,
});
return tickets;
}
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 ticketsData = data.map((item, index) => ({
id: item.id || undefined,
ticket_number: item.ticket_number
||
null
,
status: item.status
||
null
,
priority: item.priority
||
null
,
category: item.category
||
null
,
subject: item.subject
||
null
,
description: item.description
||
null
,
ai_summary: item.ai_summary
||
null
,
next_best_action: item.next_best_action
||
null
,
sentiment_at_creation: item.sentiment_at_creation
||
null
,
frustration_at_creation: item.frustration_at_creation
||
null
,
escalation_required: item.escalation_required
||
false
,
opened_at: item.opened_at
||
null
,
closed_at: item.closed_at
||
null
,
external_crm_ticket_ref: item.external_crm_ticket_ref
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tickets = await db.tickets.bulkCreate(ticketsData, { transaction });
// For each item created, replace relation files
return tickets;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tickets = await db.tickets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.ticket_number !== undefined) updatePayload.ticket_number = data.ticket_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.priority !== undefined) updatePayload.priority = data.priority;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.subject !== undefined) updatePayload.subject = data.subject;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.ai_summary !== undefined) updatePayload.ai_summary = data.ai_summary;
if (data.next_best_action !== undefined) updatePayload.next_best_action = data.next_best_action;
if (data.sentiment_at_creation !== undefined) updatePayload.sentiment_at_creation = data.sentiment_at_creation;
if (data.frustration_at_creation !== undefined) updatePayload.frustration_at_creation = data.frustration_at_creation;
if (data.escalation_required !== undefined) updatePayload.escalation_required = data.escalation_required;
if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
if (data.external_crm_ticket_ref !== undefined) updatePayload.external_crm_ticket_ref = data.external_crm_ticket_ref;
updatePayload.updatedById = currentUser.id;
await tickets.update(updatePayload, {transaction});
if (data.conversation !== undefined) {
await tickets.setConversation(
data.conversation,
{ transaction }
);
}
if (data.customer_account !== undefined) {
await tickets.setCustomer_account(
data.customer_account,
{ transaction }
);
}
if (data.requester_user !== undefined) {
await tickets.setRequester_user(
data.requester_user,
{ transaction }
);
}
if (data.assigned_agent !== undefined) {
await tickets.setAssigned_agent(
data.assigned_agent,
{ transaction }
);
}
return tickets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tickets = await db.tickets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tickets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tickets) {
await record.destroy({transaction});
}
});
return tickets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tickets = await db.tickets.findByPk(id, options);
await tickets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tickets.destroy({
transaction
});
return tickets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tickets = await db.tickets.findOne(
{ where },
{ transaction },
);
if (!tickets) {
return tickets;
}
const output = tickets.get({plain: true});
output.escalation_alerts_ticket = await tickets.getEscalation_alerts_ticket({
transaction
});
output.conversation = await tickets.getConversation({
transaction
});
output.customer_account = await tickets.getCustomer_account({
transaction
});
output.requester_user = await tickets.getRequester_user({
transaction
});
output.assigned_agent = await tickets.getAssigned_agent({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.conversations,
as: 'conversation',
where: filter.conversation ? {
[Op.or]: [
{ id: { [Op.in]: filter.conversation.split('|').map(term => Utils.uuid(term)) } },
{
case_reference: {
[Op.or]: filter.conversation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customer_accounts,
as: 'customer_account',
where: filter.customer_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer_account.split('|').map(term => Utils.uuid(term)) } },
{
account_name: {
[Op.or]: filter.customer_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'requester_user',
where: filter.requester_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.requester_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requester_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assigned_agent',
where: filter.assigned_agent ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_agent.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assigned_agent.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.ticket_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'tickets',
'ticket_number',
filter.ticket_number,
),
};
}
if (filter.subject) {
where = {
...where,
[Op.and]: Utils.ilike(
'tickets',
'subject',
filter.subject,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'tickets',
'description',
filter.description,
),
};
}
if (filter.ai_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'tickets',
'ai_summary',
filter.ai_summary,
),
};
}
if (filter.next_best_action) {
where = {
...where,
[Op.and]: Utils.ilike(
'tickets',
'next_best_action',
filter.next_best_action,
),
};
}
if (filter.external_crm_ticket_ref) {
where = {
...where,
[Op.and]: Utils.ilike(
'tickets',
'external_crm_ticket_ref',
filter.external_crm_ticket_ref,
),
};
}
if (filter.sentiment_at_creationRange) {
const [start, end] = filter.sentiment_at_creationRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sentiment_at_creation: {
...where.sentiment_at_creation,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sentiment_at_creation: {
...where.sentiment_at_creation,
[Op.lte]: end,
},
};
}
}
if (filter.frustration_at_creationRange) {
const [start, end] = filter.frustration_at_creationRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
frustration_at_creation: {
...where.frustration_at_creation,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
frustration_at_creation: {
...where.frustration_at_creation,
[Op.lte]: end,
},
};
}
}
if (filter.opened_atRange) {
const [start, end] = filter.opened_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.lte]: end,
},
};
}
}
if (filter.closed_atRange) {
const [start, end] = filter.closed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.priority) {
where = {
...where,
priority: filter.priority,
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.escalation_required) {
where = {
...where,
escalation_required: filter.escalation_required,
};
}
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.tickets.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(
'tickets',
'subject',
query,
),
],
};
}
const records = await db.tickets.findAll({
attributes: [ 'id', 'subject' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['subject', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.subject,
}));
}
};

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

@ -0,0 +1,963 @@
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.conversations_customer_user = await users.getConversations_customer_user({
transaction
});
output.conversation_messages_sender_user = await users.getConversation_messages_sender_user({
transaction
});
output.tickets_requester_user = await users.getTickets_requester_user({
transaction
});
output.tickets_assigned_agent = await users.getTickets_assigned_agent({
transaction
});
output.escalation_alerts_acknowledged_by = await users.getEscalation_alerts_acknowledged_by({
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,695 @@
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 Voice_callsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const voice_calls = await db.voice_calls.create(
{
id: data.id || undefined,
call_status: data.call_status
||
null
,
from_number: data.from_number
||
null
,
to_number: data.to_number
||
null
,
started_at: data.started_at
||
null
,
ended_at: data.ended_at
||
null
,
duration_seconds: data.duration_seconds
||
null
,
transcript: data.transcript
||
null
,
avg_sentiment_score: data.avg_sentiment_score
||
null
,
avg_frustration_score: data.avg_frustration_score
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await voice_calls.setConversation( data.conversation || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.voice_calls.getTableName(),
belongsToColumn: 'recording_file',
belongsToId: voice_calls.id,
},
data.recording_file,
options,
);
return voice_calls;
}
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 voice_callsData = data.map((item, index) => ({
id: item.id || undefined,
call_status: item.call_status
||
null
,
from_number: item.from_number
||
null
,
to_number: item.to_number
||
null
,
started_at: item.started_at
||
null
,
ended_at: item.ended_at
||
null
,
duration_seconds: item.duration_seconds
||
null
,
transcript: item.transcript
||
null
,
avg_sentiment_score: item.avg_sentiment_score
||
null
,
avg_frustration_score: item.avg_frustration_score
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const voice_calls = await db.voice_calls.bulkCreate(voice_callsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < voice_calls.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.voice_calls.getTableName(),
belongsToColumn: 'recording_file',
belongsToId: voice_calls[i].id,
},
data[i].recording_file,
options,
);
}
return voice_calls;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const voice_calls = await db.voice_calls.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.call_status !== undefined) updatePayload.call_status = data.call_status;
if (data.from_number !== undefined) updatePayload.from_number = data.from_number;
if (data.to_number !== undefined) updatePayload.to_number = data.to_number;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
if (data.transcript !== undefined) updatePayload.transcript = data.transcript;
if (data.avg_sentiment_score !== undefined) updatePayload.avg_sentiment_score = data.avg_sentiment_score;
if (data.avg_frustration_score !== undefined) updatePayload.avg_frustration_score = data.avg_frustration_score;
updatePayload.updatedById = currentUser.id;
await voice_calls.update(updatePayload, {transaction});
if (data.conversation !== undefined) {
await voice_calls.setConversation(
data.conversation,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.voice_calls.getTableName(),
belongsToColumn: 'recording_file',
belongsToId: voice_calls.id,
},
data.recording_file,
options,
);
return voice_calls;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const voice_calls = await db.voice_calls.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of voice_calls) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of voice_calls) {
await record.destroy({transaction});
}
});
return voice_calls;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const voice_calls = await db.voice_calls.findByPk(id, options);
await voice_calls.update({
deletedBy: currentUser.id
}, {
transaction,
});
await voice_calls.destroy({
transaction
});
return voice_calls;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const voice_calls = await db.voice_calls.findOne(
{ where },
{ transaction },
);
if (!voice_calls) {
return voice_calls;
}
const output = voice_calls.get({plain: true});
output.conversation = await voice_calls.getConversation({
transaction
});
output.recording_file = await voice_calls.getRecording_file({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.conversations,
as: 'conversation',
where: filter.conversation ? {
[Op.or]: [
{ id: { [Op.in]: filter.conversation.split('|').map(term => Utils.uuid(term)) } },
{
case_reference: {
[Op.or]: filter.conversation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'recording_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.from_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'voice_calls',
'from_number',
filter.from_number,
),
};
}
if (filter.to_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'voice_calls',
'to_number',
filter.to_number,
),
};
}
if (filter.transcript) {
where = {
...where,
[Op.and]: Utils.ilike(
'voice_calls',
'transcript',
filter.transcript,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
started_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ended_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.ended_atRange) {
const [start, end] = filter.ended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.lte]: end,
},
};
}
}
if (filter.duration_secondsRange) {
const [start, end] = filter.duration_secondsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.lte]: end,
},
};
}
}
if (filter.avg_sentiment_scoreRange) {
const [start, end] = filter.avg_sentiment_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
avg_sentiment_score: {
...where.avg_sentiment_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
avg_sentiment_score: {
...where.avg_sentiment_score,
[Op.lte]: end,
},
};
}
}
if (filter.avg_frustration_scoreRange) {
const [start, end] = filter.avg_frustration_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
avg_frustration_score: {
...where.avg_frustration_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
avg_frustration_score: {
...where.avg_frustration_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.call_status) {
where = {
...where,
call_status: filter.call_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.voice_calls.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(
'voice_calls',
'from_number',
query,
),
],
};
}
const records = await db.voice_calls.findAll({
attributes: [ 'id', 'from_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['from_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.from_number,
}));
}
};

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_ai_customer_success_guardian',
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,182 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ai_models = sequelize.define(
'ai_models',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
model_name: {
type: DataTypes.TEXT,
},
provider: {
type: DataTypes.ENUM,
values: [
"openai",
"azure_openai",
"anthropic",
"google",
"local",
"other"
],
},
model_type: {
type: DataTypes.ENUM,
values: [
"chat",
"embeddings",
"speech_to_text",
"text_to_speech",
"reranker"
],
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"inactive"
],
},
default_temperature: {
type: DataTypes.TEXT,
},
max_tokens: {
type: DataTypes.INTEGER,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ai_models.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.ai_models.hasMany(db.ai_runs, {
as: 'ai_runs_model',
foreignKey: {
name: 'modelId',
},
constraints: false,
});
//end loop
db.ai_models.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_models.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_models;
};

View File

@ -0,0 +1,218 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ai_runs = sequelize.define(
'ai_runs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
run_type: {
type: DataTypes.ENUM,
values: [
"chat_response",
"rag_retrieval",
"ticket_summary",
"sentiment_analysis",
"health_scoring",
"voice_transcription"
],
},
started_at: {
type: DataTypes.DATE,
},
finished_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"succeeded",
"failed",
"canceled"
],
},
prompt_preview: {
type: DataTypes.TEXT,
},
response_preview: {
type: DataTypes.TEXT,
},
prompt_tokens: {
type: DataTypes.INTEGER,
},
completion_tokens: {
type: DataTypes.INTEGER,
},
total_cost: {
type: DataTypes.DECIMAL,
},
error_message: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ai_runs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.ai_runs.hasMany(db.conversation_messages, {
as: 'conversation_messages_ai_run',
foreignKey: {
name: 'ai_runId',
},
constraints: false,
});
db.ai_runs.hasMany(db.rag_queries, {
as: 'rag_queries_ai_run',
foreignKey: {
name: 'ai_runId',
},
constraints: false,
});
//end loop
db.ai_runs.belongsTo(db.conversations, {
as: 'conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.ai_runs.belongsTo(db.ai_models, {
as: 'model',
foreignKey: {
name: 'modelId',
},
constraints: false,
});
db.ai_runs.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_runs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_runs;
};

View File

@ -0,0 +1,220 @@
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 conversation_messages = sequelize.define(
'conversation_messages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
sender_type: {
type: DataTypes.ENUM,
values: [
"customer",
"agent",
"ai",
"system"
],
},
sent_at: {
type: DataTypes.DATE,
},
message_kind: {
type: DataTypes.ENUM,
values: [
"text",
"voice_transcript",
"attachment",
"event"
],
},
content: {
type: DataTypes.TEXT,
},
sentiment_score: {
type: DataTypes.DECIMAL,
},
sentiment_label: {
type: DataTypes.ENUM,
values: [
"positive",
"neutral",
"negative",
"frustrated"
],
},
toxicity_score: {
type: DataTypes.DECIMAL,
},
detected_intent: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
conversation_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.conversation_messages.belongsTo(db.conversations, {
as: 'conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.conversation_messages.belongsTo(db.users, {
as: 'sender_user',
foreignKey: {
name: 'sender_userId',
},
constraints: false,
});
db.conversation_messages.belongsTo(db.knowledge_articles, {
as: 'knowledge_article_used',
foreignKey: {
name: 'knowledge_article_usedId',
},
constraints: false,
});
db.conversation_messages.belongsTo(db.ai_runs, {
as: 'ai_run',
foreignKey: {
name: 'ai_runId',
},
constraints: false,
});
db.conversation_messages.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.conversation_messages.getTableName(),
belongsToColumn: 'attachments',
},
});
db.conversation_messages.belongsTo(db.users, {
as: 'createdBy',
});
db.conversation_messages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return conversation_messages;
};

View File

@ -0,0 +1,291 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const conversations = sequelize.define(
'conversations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
case_reference: {
type: DataTypes.TEXT,
},
state: {
type: DataTypes.ENUM,
values: [
"open",
"waiting_on_customer",
"waiting_on_agent",
"resolved",
"closed"
],
},
priority: {
type: DataTypes.ENUM,
values: [
"low",
"normal",
"high",
"urgent"
],
},
started_at: {
type: DataTypes.DATE,
},
ended_at: {
type: DataTypes.DATE,
},
current_sentiment_score: {
type: DataTypes.DECIMAL,
},
sentiment_label: {
type: DataTypes.ENUM,
values: [
"positive",
"neutral",
"negative",
"frustrated"
],
},
frustration_score: {
type: DataTypes.DECIMAL,
},
escalated: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
last_message_at: {
type: DataTypes.DATE,
},
customer_intent: {
type: DataTypes.TEXT,
},
topic: {
type: DataTypes.TEXT,
},
resolution_summary: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
conversations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.conversations.hasMany(db.conversation_messages, {
as: 'conversation_messages_conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.conversations.hasMany(db.voice_calls, {
as: 'voice_calls_conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.conversations.hasMany(db.tickets, {
as: 'tickets_conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.conversations.hasMany(db.escalation_alerts, {
as: 'escalation_alerts_conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.conversations.hasMany(db.ai_runs, {
as: 'ai_runs_conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.conversations.hasMany(db.rag_queries, {
as: 'rag_queries_conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
//end loop
db.conversations.belongsTo(db.support_channels, {
as: 'channel',
foreignKey: {
name: 'channelId',
},
constraints: false,
});
db.conversations.belongsTo(db.customer_accounts, {
as: 'customer_account',
foreignKey: {
name: 'customer_accountId',
},
constraints: false,
});
db.conversations.belongsTo(db.users, {
as: 'customer_user',
foreignKey: {
name: 'customer_userId',
},
constraints: false,
});
db.conversations.belongsTo(db.users, {
as: 'createdBy',
});
db.conversations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return conversations;
};

View File

@ -0,0 +1,215 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const customer_accounts = sequelize.define(
'customer_accounts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
account_name: {
type: DataTypes.TEXT,
},
domain: {
type: DataTypes.TEXT,
},
segment: {
type: DataTypes.ENUM,
values: [
"smb",
"mid_market",
"enterprise"
],
},
lifecycle_stage: {
type: DataTypes.ENUM,
values: [
"trial",
"active",
"at_risk",
"churned"
],
},
primary_contact_name: {
type: DataTypes.TEXT,
},
primary_contact_email: {
type: DataTypes.TEXT,
},
primary_contact_phone: {
type: DataTypes.TEXT,
},
mrr: {
type: DataTypes.DECIMAL,
},
contract_start_at: {
type: DataTypes.DATE,
},
contract_end_at: {
type: DataTypes.DATE,
},
vip: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
crm_account_ref: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
customer_accounts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.customer_accounts.hasMany(db.conversations, {
as: 'conversations_customer_account',
foreignKey: {
name: 'customer_accountId',
},
constraints: false,
});
db.customer_accounts.hasMany(db.tickets, {
as: 'tickets_customer_account',
foreignKey: {
name: 'customer_accountId',
},
constraints: false,
});
db.customer_accounts.hasMany(db.customer_health_snapshots, {
as: 'customer_health_snapshots_customer_account',
foreignKey: {
name: 'customer_accountId',
},
constraints: false,
});
//end loop
db.customer_accounts.belongsTo(db.users, {
as: 'createdBy',
});
db.customer_accounts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return customer_accounts;
};

View File

@ -0,0 +1,192 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const customer_health_snapshots = sequelize.define(
'customer_health_snapshots',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
calculated_at: {
type: DataTypes.DATE,
},
health_score: {
type: DataTypes.DECIMAL,
},
health_label: {
type: DataTypes.ENUM,
values: [
"healthy",
"monitor",
"at_risk",
"critical"
],
},
churn_risk_score: {
type: DataTypes.DECIMAL,
},
churn_risk_label: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high",
"critical"
],
},
sentiment_trend: {
type: DataTypes.DECIMAL,
},
ticket_volume_30d: {
type: DataTypes.INTEGER,
},
repeat_issue_count_30d: {
type: DataTypes.INTEGER,
},
avg_first_response_minutes_30d: {
type: DataTypes.DECIMAL,
},
avg_resolution_hours_30d: {
type: DataTypes.DECIMAL,
},
drivers_summary: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
customer_health_snapshots.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.customer_health_snapshots.belongsTo(db.customer_accounts, {
as: 'customer_account',
foreignKey: {
name: 'customer_accountId',
},
constraints: false,
});
db.customer_health_snapshots.belongsTo(db.users, {
as: 'createdBy',
});
db.customer_health_snapshots.belongsTo(db.users, {
as: 'updatedBy',
});
};
return customer_health_snapshots;
};

View File

@ -0,0 +1,185 @@
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 escalation_alerts = sequelize.define(
'escalation_alerts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
severity: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high",
"critical"
],
},
reason: {
type: DataTypes.ENUM,
values: [
"high_frustration",
"negative_sentiment_trend",
"churn_risk_spike",
"compliance_risk",
"vip_customer",
"repeated_contacts",
"no_answer_found"
],
},
message: {
type: DataTypes.TEXT,
},
acknowledged: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
acknowledged_at: {
type: DataTypes.DATE,
},
triggered_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
escalation_alerts.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.escalation_alerts.belongsTo(db.conversations, {
as: 'conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.escalation_alerts.belongsTo(db.tickets, {
as: 'ticket',
foreignKey: {
name: 'ticketId',
},
constraints: false,
});
db.escalation_alerts.belongsTo(db.users, {
as: 'acknowledged_by',
foreignKey: {
name: 'acknowledged_byId',
},
constraints: false,
});
db.escalation_alerts.belongsTo(db.users, {
as: 'createdBy',
});
db.escalation_alerts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return escalation_alerts;
};

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,165 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const issue_taxonomy = sequelize.define(
'issue_taxonomy',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
issue_name: {
type: DataTypes.TEXT,
},
issue_type: {
type: DataTypes.ENUM,
values: [
"product_bug",
"usability",
"billing",
"outage",
"integration",
"performance",
"documentation",
"other"
],
},
description: {
type: DataTypes.TEXT,
},
severity_default: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high",
"critical"
],
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
issue_taxonomy.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.issue_taxonomy.hasMany(db.recurring_issue_signals, {
as: 'recurring_issue_signals_issue',
foreignKey: {
name: 'issueId',
},
constraints: false,
});
//end loop
db.issue_taxonomy.belongsTo(db.users, {
as: 'createdBy',
});
db.issue_taxonomy.belongsTo(db.users, {
as: 'updatedBy',
});
};
return issue_taxonomy;
};

View File

@ -0,0 +1,173 @@
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 knowledge_articles = sequelize.define(
'knowledge_articles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
visibility: {
type: DataTypes.ENUM,
values: [
"internal",
"public"
],
},
content: {
type: DataTypes.TEXT,
},
tags: {
type: DataTypes.TEXT,
},
external_ref: {
type: DataTypes.TEXT,
},
quality_score: {
type: DataTypes.DECIMAL,
},
published_at: {
type: DataTypes.DATE,
},
last_reviewed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
knowledge_articles.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.knowledge_articles.hasMany(db.conversation_messages, {
as: 'conversation_messages_knowledge_article_used',
foreignKey: {
name: 'knowledge_article_usedId',
},
constraints: false,
});
db.knowledge_articles.hasMany(db.rag_results, {
as: 'rag_results_knowledge_article',
foreignKey: {
name: 'knowledge_articleId',
},
constraints: false,
});
//end loop
db.knowledge_articles.belongsTo(db.knowledge_sources, {
as: 'knowledge_source',
foreignKey: {
name: 'knowledge_sourceId',
},
constraints: false,
});
db.knowledge_articles.belongsTo(db.users, {
as: 'createdBy',
});
db.knowledge_articles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return knowledge_articles;
};

View File

@ -0,0 +1,170 @@
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 knowledge_sources = sequelize.define(
'knowledge_sources',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
source_name: {
type: DataTypes.TEXT,
},
source_type: {
type: DataTypes.ENUM,
values: [
"faq",
"product_manual",
"past_tickets",
"policy",
"website",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"paused",
"archived"
],
},
source_uri: {
type: DataTypes.TEXT,
},
last_ingested_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
knowledge_sources.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.knowledge_sources.hasMany(db.knowledge_articles, {
as: 'knowledge_articles_knowledge_source',
foreignKey: {
name: 'knowledge_sourceId',
},
constraints: false,
});
//end loop
db.knowledge_sources.hasMany(db.file, {
as: 'source_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.knowledge_sources.getTableName(),
belongsToColumn: 'source_files',
},
});
db.knowledge_sources.belongsTo(db.users, {
as: 'createdBy',
});
db.knowledge_sources.belongsTo(db.users, {
as: 'updatedBy',
});
};
return knowledge_sources;
};

View File

@ -0,0 +1,84 @@
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,155 @@
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 rag_queries = sequelize.define(
'rag_queries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
query_text: {
type: DataTypes.TEXT,
},
retrieval_strategy: {
type: DataTypes.ENUM,
values: [
"semantic",
"hybrid",
"keyword"
],
},
top_k: {
type: DataTypes.INTEGER,
},
min_score_threshold: {
type: DataTypes.DECIMAL,
},
filters_json: {
type: DataTypes.TEXT,
},
queried_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
rag_queries.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.rag_queries.hasMany(db.rag_results, {
as: 'rag_results_rag_query',
foreignKey: {
name: 'rag_queryId',
},
constraints: false,
});
//end loop
db.rag_queries.belongsTo(db.ai_runs, {
as: 'ai_run',
foreignKey: {
name: 'ai_runId',
},
constraints: false,
});
db.rag_queries.belongsTo(db.conversations, {
as: 'conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.rag_queries.belongsTo(db.users, {
as: 'createdBy',
});
db.rag_queries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return rag_queries;
};

View File

@ -0,0 +1,114 @@
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 rag_results = sequelize.define(
'rag_results',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
score: {
type: DataTypes.DECIMAL,
},
rank: {
type: DataTypes.INTEGER,
},
snippet: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
rag_results.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.rag_results.belongsTo(db.rag_queries, {
as: 'rag_query',
foreignKey: {
name: 'rag_queryId',
},
constraints: false,
});
db.rag_results.belongsTo(db.knowledge_articles, {
as: 'knowledge_article',
foreignKey: {
name: 'knowledge_articleId',
},
constraints: false,
});
db.rag_results.belongsTo(db.users, {
as: 'createdBy',
});
db.rag_results.belongsTo(db.users, {
as: 'updatedBy',
});
};
return rag_results;
};

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 recurring_issue_signals = sequelize.define(
'recurring_issue_signals',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
window_start_at: {
type: DataTypes.DATE,
},
window_end_at: {
type: DataTypes.DATE,
},
occurrence_count: {
type: DataTypes.INTEGER,
},
impact_score: {
type: DataTypes.DECIMAL,
},
avg_sentiment_score: {
type: DataTypes.DECIMAL,
},
example_case_references: {
type: DataTypes.TEXT,
},
needs_attention: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
recurring_issue_signals.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.recurring_issue_signals.belongsTo(db.issue_taxonomy, {
as: 'issue',
foreignKey: {
name: 'issueId',
},
constraints: false,
});
db.recurring_issue_signals.belongsTo(db.users, {
as: 'createdBy',
});
db.recurring_issue_signals.belongsTo(db.users, {
as: 'updatedBy',
});
};
return recurring_issue_signals;
};

View File

@ -0,0 +1,117 @@
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,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 support_channels = sequelize.define(
'support_channels',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
channel_name: {
type: DataTypes.TEXT,
},
channel_type: {
type: DataTypes.ENUM,
values: [
"web_chat",
"voice",
"email",
"sms",
"whatsapp",
"slack",
"teams",
"api"
],
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"inactive"
],
},
provider: {
type: DataTypes.TEXT,
},
provider_config_hint: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
support_channels.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.support_channels.hasMany(db.conversations, {
as: 'conversations_channel',
foreignKey: {
name: 'channelId',
},
constraints: false,
});
//end loop
db.support_channels.belongsTo(db.users, {
as: 'createdBy',
});
db.support_channels.belongsTo(db.users, {
as: 'updatedBy',
});
};
return support_channels;
};

View File

@ -0,0 +1,281 @@
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 tickets = sequelize.define(
'tickets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
ticket_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"new",
"open",
"pending",
"on_hold",
"solved",
"closed"
],
},
priority: {
type: DataTypes.ENUM,
values: [
"low",
"normal",
"high",
"urgent"
],
},
category: {
type: DataTypes.ENUM,
values: [
"how_to",
"bug",
"billing",
"account",
"integration",
"performance",
"feature_request",
"other"
],
},
subject: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
ai_summary: {
type: DataTypes.TEXT,
},
next_best_action: {
type: DataTypes.TEXT,
},
sentiment_at_creation: {
type: DataTypes.DECIMAL,
},
frustration_at_creation: {
type: DataTypes.DECIMAL,
},
escalation_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
opened_at: {
type: DataTypes.DATE,
},
closed_at: {
type: DataTypes.DATE,
},
external_crm_ticket_ref: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tickets.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.tickets.hasMany(db.escalation_alerts, {
as: 'escalation_alerts_ticket',
foreignKey: {
name: 'ticketId',
},
constraints: false,
});
//end loop
db.tickets.belongsTo(db.conversations, {
as: 'conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.tickets.belongsTo(db.customer_accounts, {
as: 'customer_account',
foreignKey: {
name: 'customer_accountId',
},
constraints: false,
});
db.tickets.belongsTo(db.users, {
as: 'requester_user',
foreignKey: {
name: 'requester_userId',
},
constraints: false,
});
db.tickets.belongsTo(db.users, {
as: 'assigned_agent',
foreignKey: {
name: 'assigned_agentId',
},
constraints: false,
});
db.tickets.belongsTo(db.users, {
as: 'createdBy',
});
db.tickets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tickets;
};

View File

@ -0,0 +1,282 @@
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.conversations, {
as: 'conversations_customer_user',
foreignKey: {
name: 'customer_userId',
},
constraints: false,
});
db.users.hasMany(db.conversation_messages, {
as: 'conversation_messages_sender_user',
foreignKey: {
name: 'sender_userId',
},
constraints: false,
});
db.users.hasMany(db.tickets, {
as: 'tickets_requester_user',
foreignKey: {
name: 'requester_userId',
},
constraints: false,
});
db.users.hasMany(db.tickets, {
as: 'tickets_assigned_agent',
foreignKey: {
name: 'assigned_agentId',
},
constraints: false,
});
db.users.hasMany(db.escalation_alerts, {
as: 'escalation_alerts_acknowledged_by',
foreignKey: {
name: 'acknowledged_byId',
},
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,173 @@
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 voice_calls = sequelize.define(
'voice_calls',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
call_status: {
type: DataTypes.ENUM,
values: [
"initiated",
"in_progress",
"completed",
"failed"
],
},
from_number: {
type: DataTypes.TEXT,
},
to_number: {
type: DataTypes.TEXT,
},
started_at: {
type: DataTypes.DATE,
},
ended_at: {
type: DataTypes.DATE,
},
duration_seconds: {
type: DataTypes.INTEGER,
},
transcript: {
type: DataTypes.TEXT,
},
avg_sentiment_score: {
type: DataTypes.DECIMAL,
},
avg_frustration_score: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
voice_calls.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.voice_calls.belongsTo(db.conversations, {
as: 'conversation',
foreignKey: {
name: 'conversationId',
},
constraints: false,
});
db.voice_calls.hasMany(db.file, {
as: 'recording_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.voice_calls.getTableName(),
belongsToColumn: 'recording_file',
},
});
db.voice_calls.belongsTo(db.users, {
as: 'createdBy',
});
db.voice_calls.belongsTo(db.users, {
as: 'updatedBy',
});
};
return voice_calls;
};

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

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

@ -0,0 +1,202 @@
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 customer_accountsRoutes = require('./routes/customer_accounts');
const support_channelsRoutes = require('./routes/support_channels');
const conversationsRoutes = require('./routes/conversations');
const conversation_messagesRoutes = require('./routes/conversation_messages');
const voice_callsRoutes = require('./routes/voice_calls');
const ticketsRoutes = require('./routes/tickets');
const escalation_alertsRoutes = require('./routes/escalation_alerts');
const knowledge_sourcesRoutes = require('./routes/knowledge_sources');
const knowledge_articlesRoutes = require('./routes/knowledge_articles');
const ai_modelsRoutes = require('./routes/ai_models');
const ai_runsRoutes = require('./routes/ai_runs');
const rag_queriesRoutes = require('./routes/rag_queries');
const rag_resultsRoutes = require('./routes/rag_results');
const customer_health_snapshotsRoutes = require('./routes/customer_health_snapshots');
const issue_taxonomyRoutes = require('./routes/issue_taxonomy');
const recurring_issue_signalsRoutes = require('./routes/recurring_issue_signals');
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: "AI Customer Success Guardian",
description: "AI Customer Success Guardian 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/customer_accounts', passport.authenticate('jwt', {session: false}), customer_accountsRoutes);
app.use('/api/support_channels', passport.authenticate('jwt', {session: false}), support_channelsRoutes);
app.use('/api/conversations', passport.authenticate('jwt', {session: false}), conversationsRoutes);
app.use('/api/conversation_messages', passport.authenticate('jwt', {session: false}), conversation_messagesRoutes);
app.use('/api/voice_calls', passport.authenticate('jwt', {session: false}), voice_callsRoutes);
app.use('/api/tickets', passport.authenticate('jwt', {session: false}), ticketsRoutes);
app.use('/api/escalation_alerts', passport.authenticate('jwt', {session: false}), escalation_alertsRoutes);
app.use('/api/knowledge_sources', passport.authenticate('jwt', {session: false}), knowledge_sourcesRoutes);
app.use('/api/knowledge_articles', passport.authenticate('jwt', {session: false}), knowledge_articlesRoutes);
app.use('/api/ai_models', passport.authenticate('jwt', {session: false}), ai_modelsRoutes);
app.use('/api/ai_runs', passport.authenticate('jwt', {session: false}), ai_runsRoutes);
app.use('/api/rag_queries', passport.authenticate('jwt', {session: false}), rag_queriesRoutes);
app.use('/api/rag_results', passport.authenticate('jwt', {session: false}), rag_resultsRoutes);
app.use('/api/customer_health_snapshots', passport.authenticate('jwt', {session: false}), customer_health_snapshotsRoutes);
app.use('/api/issue_taxonomy', passport.authenticate('jwt', {session: false}), issue_taxonomyRoutes);
app.use('/api/recurring_issue_signals', passport.authenticate('jwt', {session: false}), recurring_issue_signalsRoutes);
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 Ai_modelsService = require('../services/ai_models');
const Ai_modelsDBApi = require('../db/api/ai_models');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('ai_models'));
/**
* @swagger
* components:
* schemas:
* Ai_models:
* type: object
* properties:
* model_name:
* type: string
* default: model_name
* default_temperature:
* type: string
* default: default_temperature
* notes:
* type: string
* default: notes
* max_tokens:
* type: integer
* format: int64
*
*
*
*/
/**
* @swagger
* tags:
* name: Ai_models
* description: The Ai_models managing API
*/
/**
* @swagger
* /api/ai_models:
* post:
* security:
* - bearerAuth: []
* tags: [Ai_models]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Ai_models"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_models"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Ai_modelsService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Ai_models]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Ai_models"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_models"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Ai_modelsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_models/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Ai_models]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Ai_models"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_models"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await Ai_modelsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_models/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Ai_models]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_models"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await Ai_modelsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_models/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Ai_models]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_models"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Ai_modelsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_models:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_models]
* summary: Get all ai_models
* description: Get all ai_models
* responses:
* 200:
* description: Ai_models list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Ai_models"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const currentUser = req.currentUser;
const payload = await Ai_modelsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','model_name','default_temperature','notes',
'max_tokens',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/ai_models/count:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_models]
* summary: Count all ai_models
* description: Count all ai_models
* responses:
* 200:
* description: Ai_models count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Ai_models"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const currentUser = req.currentUser;
const payload = await Ai_modelsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_models/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_models]
* summary: Find all ai_models that match search criteria
* description: Find all ai_models that match search criteria
* responses:
* 200:
* description: Ai_models list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Ai_models"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Ai_modelsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/ai_models/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_models]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_models"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await Ai_modelsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

@ -0,0 +1,441 @@
const express = require('express');
const Conversation_messagesService = require('../services/conversation_messages');
const Conversation_messagesDBApi = require('../db/api/conversation_messages');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('conversation_messages'));
/**
* @swagger
* components:
* schemas:
* Conversation_messages:
* type: object
* properties:
* content:
* type: string
* default: content
* detected_intent:
* type: string
* default: detected_intent
* sentiment_score:
* type: integer
* format: int64
* toxicity_score:
* type: integer
* format: int64
*
*
*
*/
/**
* @swagger
* tags:
* name: Conversation_messages
* description: The Conversation_messages managing API
*/
/**
* @swagger
* /api/conversation_messages:
* post:
* security:
* - bearerAuth: []
* tags: [Conversation_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/Conversation_messages"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Conversation_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 Conversation_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: [Conversation_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/Conversation_messages"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Conversation_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 Conversation_messagesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/conversation_messages/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Conversation_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/Conversation_messages"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Conversation_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 Conversation_messagesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/conversation_messages/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Conversation_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/Conversation_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 Conversation_messagesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/conversation_messages/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Conversation_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/Conversation_messages"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Conversation_messagesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/conversation_messages:
* get:
* security:
* - bearerAuth: []
* tags: [Conversation_messages]
* summary: Get all conversation_messages
* description: Get all conversation_messages
* responses:
* 200:
* description: Conversation_messages list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Conversation_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 Conversation_messagesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','content','detected_intent',
'sentiment_score','toxicity_score',
'sent_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/conversation_messages/count:
* get:
* security:
* - bearerAuth: []
* tags: [Conversation_messages]
* summary: Count all conversation_messages
* description: Count all conversation_messages
* responses:
* 200:
* description: Conversation_messages count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Conversation_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 Conversation_messagesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/conversation_messages/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Conversation_messages]
* summary: Find all conversation_messages that match search criteria
* description: Find all conversation_messages that match search criteria
* responses:
* 200:
* description: Conversation_messages list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Conversation_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 Conversation_messagesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/conversation_messages/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Conversation_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/Conversation_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 Conversation_messagesDBApi.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 ConversationsService = require('../services/conversations');
const ConversationsDBApi = require('../db/api/conversations');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('conversations'));
/**
* @swagger
* components:
* schemas:
* Conversations:
* type: object
* properties:
* case_reference:
* type: string
* default: case_reference
* customer_intent:
* type: string
* default: customer_intent
* topic:
* type: string
* default: topic
* resolution_summary:
* type: string
* default: resolution_summary
* current_sentiment_score:
* type: integer
* format: int64
* frustration_score:
* type: integer
* format: int64
*
*
*
*/
/**
* @swagger
* tags:
* name: Conversations
* description: The Conversations managing API
*/
/**
* @swagger
* /api/conversations:
* post:
* security:
* - bearerAuth: []
* tags: [Conversations]
* 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/Conversations"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Conversations"
* 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 ConversationsService.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: [Conversations]
* 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/Conversations"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Conversations"
* 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 ConversationsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/conversations/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Conversations]
* 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/Conversations"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Conversations"
* 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 ConversationsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/conversations/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Conversations]
* 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/Conversations"
* 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 ConversationsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/conversations/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Conversations]
* 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/Conversations"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await ConversationsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/conversations:
* get:
* security:
* - bearerAuth: []
* tags: [Conversations]
* summary: Get all conversations
* description: Get all conversations
* responses:
* 200:
* description: Conversations list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Conversations"
* 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 ConversationsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','case_reference','customer_intent','topic','resolution_summary',
'current_sentiment_score','frustration_score',
'started_at','ended_at','last_message_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/conversations/count:
* get:
* security:
* - bearerAuth: []
* tags: [Conversations]
* summary: Count all conversations
* description: Count all conversations
* responses:
* 200:
* description: Conversations count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Conversations"
* 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 ConversationsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/conversations/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Conversations]
* summary: Find all conversations that match search criteria
* description: Find all conversations that match search criteria
* responses:
* 200:
* description: Conversations list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Conversations"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await ConversationsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/conversations/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Conversations]
* 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/Conversations"
* 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 ConversationsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

@ -0,0 +1,452 @@
const express = require('express');
const Customer_health_snapshotsService = require('../services/customer_health_snapshots');
const Customer_health_snapshotsDBApi = require('../db/api/customer_health_snapshots');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('customer_health_snapshots'));
/**
* @swagger
* components:
* schemas:
* Customer_health_snapshots:
* type: object
* properties:
* drivers_summary:
* type: string
* default: drivers_summary
* ticket_volume_30d:
* type: integer
* format: int64
* repeat_issue_count_30d:
* type: integer
* format: int64
* health_score:
* type: integer
* format: int64
* churn_risk_score:
* type: integer
* format: int64
* sentiment_trend:
* type: integer
* format: int64
* avg_first_response_minutes_30d:
* type: integer
* format: int64
* avg_resolution_hours_30d:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Customer_health_snapshots
* description: The Customer_health_snapshots managing API
*/
/**
* @swagger
* /api/customer_health_snapshots:
* post:
* security:
* - bearerAuth: []
* tags: [Customer_health_snapshots]
* 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/Customer_health_snapshots"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Customer_health_snapshots"
* 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 Customer_health_snapshotsService.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: [Customer_health_snapshots]
* 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/Customer_health_snapshots"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Customer_health_snapshots"
* 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 Customer_health_snapshotsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/customer_health_snapshots/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Customer_health_snapshots]
* 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/Customer_health_snapshots"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Customer_health_snapshots"
* 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 Customer_health_snapshotsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/customer_health_snapshots/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Customer_health_snapshots]
* 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/Customer_health_snapshots"
* 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 Customer_health_snapshotsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/customer_health_snapshots/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Customer_health_snapshots]
* 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/Customer_health_snapshots"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Customer_health_snapshotsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/customer_health_snapshots:
* get:
* security:
* - bearerAuth: []
* tags: [Customer_health_snapshots]
* summary: Get all customer_health_snapshots
* description: Get all customer_health_snapshots
* responses:
* 200:
* description: Customer_health_snapshots list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Customer_health_snapshots"
* 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 Customer_health_snapshotsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','drivers_summary',
'ticket_volume_30d','repeat_issue_count_30d',
'health_score','churn_risk_score','sentiment_trend','avg_first_response_minutes_30d','avg_resolution_hours_30d',
'calculated_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/customer_health_snapshots/count:
* get:
* security:
* - bearerAuth: []
* tags: [Customer_health_snapshots]
* summary: Count all customer_health_snapshots
* description: Count all customer_health_snapshots
* responses:
* 200:
* description: Customer_health_snapshots count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Customer_health_snapshots"
* 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 Customer_health_snapshotsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/customer_health_snapshots/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Customer_health_snapshots]
* summary: Find all customer_health_snapshots that match search criteria
* description: Find all customer_health_snapshots that match search criteria
* responses:
* 200:
* description: Customer_health_snapshots list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Customer_health_snapshots"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Customer_health_snapshotsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/customer_health_snapshots/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Customer_health_snapshots]
* 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/Customer_health_snapshots"
* 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 Customer_health_snapshotsDBApi.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 Escalation_alertsService = require('../services/escalation_alerts');
const Escalation_alertsDBApi = require('../db/api/escalation_alerts');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('escalation_alerts'));
/**
* @swagger
* components:
* schemas:
* Escalation_alerts:
* type: object
* properties:
* message:
* type: string
* default: message
*
*
*/
/**
* @swagger
* tags:
* name: Escalation_alerts
* description: The Escalation_alerts managing API
*/
/**
* @swagger
* /api/escalation_alerts:
* post:
* security:
* - bearerAuth: []
* tags: [Escalation_alerts]
* 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/Escalation_alerts"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Escalation_alerts"
* 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 Escalation_alertsService.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: [Escalation_alerts]
* 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/Escalation_alerts"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Escalation_alerts"
* 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 Escalation_alertsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/escalation_alerts/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Escalation_alerts]
* 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/Escalation_alerts"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Escalation_alerts"
* 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 Escalation_alertsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/escalation_alerts/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Escalation_alerts]
* 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/Escalation_alerts"
* 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 Escalation_alertsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/escalation_alerts/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Escalation_alerts]
* 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/Escalation_alerts"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Escalation_alertsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/escalation_alerts:
* get:
* security:
* - bearerAuth: []
* tags: [Escalation_alerts]
* summary: Get all escalation_alerts
* description: Get all escalation_alerts
* responses:
* 200:
* description: Escalation_alerts list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Escalation_alerts"
* 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 Escalation_alertsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','message',
'acknowledged_at','triggered_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/escalation_alerts/count:
* get:
* security:
* - bearerAuth: []
* tags: [Escalation_alerts]
* summary: Count all escalation_alerts
* description: Count all escalation_alerts
* responses:
* 200:
* description: Escalation_alerts count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Escalation_alerts"
* 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 Escalation_alertsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/escalation_alerts/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Escalation_alerts]
* summary: Find all escalation_alerts that match search criteria
* description: Find all escalation_alerts that match search criteria
* responses:
* 200:
* description: Escalation_alerts list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Escalation_alerts"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Escalation_alertsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/escalation_alerts/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Escalation_alerts]
* 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/Escalation_alerts"
* 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 Escalation_alertsDBApi.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,434 @@
const express = require('express');
const Issue_taxonomyService = require('../services/issue_taxonomy');
const Issue_taxonomyDBApi = require('../db/api/issue_taxonomy');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('issue_taxonomy'));
/**
* @swagger
* components:
* schemas:
* Issue_taxonomy:
* type: object
* properties:
* issue_name:
* type: string
* default: issue_name
* description:
* type: string
* default: description
*
*
*/
/**
* @swagger
* tags:
* name: Issue_taxonomy
* description: The Issue_taxonomy managing API
*/
/**
* @swagger
* /api/issue_taxonomy:
* post:
* security:
* - bearerAuth: []
* tags: [Issue_taxonomy]
* 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/Issue_taxonomy"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Issue_taxonomy"
* 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 Issue_taxonomyService.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: [Issue_taxonomy]
* 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/Issue_taxonomy"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Issue_taxonomy"
* 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 Issue_taxonomyService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/issue_taxonomy/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Issue_taxonomy]
* 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/Issue_taxonomy"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Issue_taxonomy"
* 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 Issue_taxonomyService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/issue_taxonomy/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Issue_taxonomy]
* 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/Issue_taxonomy"
* 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 Issue_taxonomyService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/issue_taxonomy/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Issue_taxonomy]
* 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/Issue_taxonomy"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Issue_taxonomyService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/issue_taxonomy:
* get:
* security:
* - bearerAuth: []
* tags: [Issue_taxonomy]
* summary: Get all issue_taxonomy
* description: Get all issue_taxonomy
* responses:
* 200:
* description: Issue_taxonomy list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Issue_taxonomy"
* 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 Issue_taxonomyDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','issue_name','description',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/issue_taxonomy/count:
* get:
* security:
* - bearerAuth: []
* tags: [Issue_taxonomy]
* summary: Count all issue_taxonomy
* description: Count all issue_taxonomy
* responses:
* 200:
* description: Issue_taxonomy count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Issue_taxonomy"
* 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 Issue_taxonomyDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/issue_taxonomy/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Issue_taxonomy]
* summary: Find all issue_taxonomy that match search criteria
* description: Find all issue_taxonomy that match search criteria
* responses:
* 200:
* description: Issue_taxonomy list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Issue_taxonomy"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Issue_taxonomyDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/issue_taxonomy/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Issue_taxonomy]
* 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/Issue_taxonomy"
* 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 Issue_taxonomyDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

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

View File

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

View File

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

View File

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

429
backend/src/routes/roles.js Normal file
View File

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

View File

@ -0,0 +1,52 @@
const express = require('express');
const SearchService = require('../services/search');
const router = express.Router();
const { checkCrudPermissions } = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('search'));
/**
* @swagger
* path:
* /api/search:
* post:
* summary: Search
* description: Search results across multiple tables
* requestBody:
* content:
* application/json:
* schema:
* type: object
* properties:
* searchQuery:
* type: string
* required:
* - searchQuery
* responses:
* 200:
* description: Successful request
* 400:
* description: Invalid request
* 500:
* description: Internal server error
*/
router.post('/', async (req, res) => {
const { searchQuery } = req.body;
if (!searchQuery) {
return res.status(400).json({ error: 'Please enter a search query' });
}
try {
const foundMatches = await SearchService.search(searchQuery, req.currentUser );
res.json(foundMatches);
} catch (error) {
console.error('Internal Server Error', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
module.exports = router;

61
backend/src/routes/sql.js Normal file
View File

@ -0,0 +1,61 @@
const express = require('express');
const db = require('../db/models');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
/**
* @swagger
* /api/sql:
* post:
* security:
* - bearerAuth: []
* summary: Execute a SELECT-only SQL query
* description: Executes a read-only SQL query and returns rows.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* sql:
* type: string
* required:
* - sql
* responses:
* 200:
* description: Query result
* 400:
* description: Invalid SQL
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 500:
* description: Internal server error
*/
router.post(
'/',
wrapAsync(async (req, res) => {
const { sql } = req.body;
if (typeof sql !== 'string' || !sql.trim()) {
return res.status(400).json({ error: 'SQL is required' });
}
const normalized = sql.trim().replace(/;+\s*$/, '');
if (!/^select\b/i.test(normalized)) {
return res.status(400).json({ error: 'Only SELECT statements are allowed' });
}
if (normalized.includes(';')) {
return res.status(400).json({ error: 'Only a single SELECT statement is allowed' });
}
const rows = await db.sequelize.query(normalized, {
type: db.Sequelize.QueryTypes.SELECT,
});
return res.status(200).json({ rows });
}),
);
module.exports = router;

View File

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

View File

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

440
backend/src/routes/users.js Normal file
View File

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

View File

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

View File

@ -0,0 +1,138 @@
const db = require('../db/models');
const Ai_modelsDBApi = require('../db/api/ai_models');
const processFile = require("../middlewares/upload");
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class Ai_modelsService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Ai_modelsDBApi.create(
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, "utf-8")); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
})
await Ai_modelsDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let ai_models = await Ai_modelsDBApi.findBy(
{id},
{transaction},
);
if (!ai_models) {
throw new ValidationError(
'ai_modelsNotFound',
);
}
const updatedAi_models = await Ai_modelsDBApi.update(
id,
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
return updatedAi_models;
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Ai_modelsDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Ai_modelsDBApi.remove(
id,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,138 @@
const db = require('../db/models');
const Ai_runsDBApi = require('../db/api/ai_runs');
const processFile = require("../middlewares/upload");
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class Ai_runsService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Ai_runsDBApi.create(
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, "utf-8")); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
})
await Ai_runsDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let ai_runs = await Ai_runsDBApi.findBy(
{id},
{transaction},
);
if (!ai_runs) {
throw new ValidationError(
'ai_runsNotFound',
);
}
const updatedAi_runs = await Ai_runsDBApi.update(
id,
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
return updatedAi_runs;
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Ai_runsDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Ai_runsDBApi.remove(
id,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

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